diff --git a/.editorconfig b/.editorconfig index 347d2d66..79e1b281 100644 --- a/.editorconfig +++ b/.editorconfig @@ -9,7 +9,7 @@ root = true ############################### # Exclude Thirdweb.Api generated files from all linting and formatting rules -[Thirdweb/Thirdweb.Api/GeneratedClient.cs] +[Thirdweb/Thirdweb.Api/ThirdwebApi.cs] generated_code = true dotnet_analyzer_diagnostic.severity = none dotnet_style_qualification_for_field = false diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..1d242d6c --- /dev/null +++ b/Makefile @@ -0,0 +1,184 @@ +# Thirdweb Makefile +# Cross-platform targets to mirror tw.bat functionality +# Requires: GNU Make, dotnet SDK, optional CSharpier + +# Use bash for consistent behavior across platforms (Git Bash/MSYS2/WSL/macOS/Linux) +SHELL := bash +.SHELLFLAGS := -o pipefail -c + +# Default target +.DEFAULT_GOAL := help + +# Tools and paths +DOTNET := dotnet +API_CLIENT := Thirdweb/Thirdweb.Api/ThirdwebApi.cs +CONSOLE_PROJ := Thirdweb.Console +GENERATOR_PROJ := Thirdweb.Generator +LIB_PROJ := Thirdweb/Thirdweb.csproj + +# Defaults for publishing/building +CONFIG ?= Release +TFM ?= netstandard2.1 +RID ?= +OUT ?= + +# Colors (best effort; will be empty if tput is unavailable) +C_RST := $(shell tput sgr0 2>/dev/null || echo "") +C_BOLD := $(shell tput bold 2>/dev/null || echo "") +C_DIM := $(shell tput dim 2>/dev/null || echo "") +C_RED := $(shell tput setaf 1 2>/dev/null || echo "") +C_GRN := $(shell tput setaf 2 2>/dev/null || echo "") +C_YEL := $(shell tput setaf 3 2>/dev/null || echo "") +C_BLU := $(shell tput setaf 4 2>/dev/null || echo "") +C_MAG := $(shell tput setaf 5 2>/dev/null || echo "") +C_CYN := $(shell tput setaf 6 2>/dev/null || echo "") + +# Icons +IC_BUILD := BUILD +IC_CLEAN := CLEAN +IC_RESTORE := RESTORE +IC_TEST := TEST +IC_PACK := PACK +IC_RUN := RUN +IC_GEN := GEN +IC_INFO := INFO +IC_OK := OK +IC_WARN := WARN +IC_ERR := ERR +IC_FMT := FMT +IC_PUB := PUBLISH + +hr = printf '$(C_DIM)%s$(C_RST)\n' '--------------------------------------------------------------------' +msg = printf '%s[%s]%s %s\n' '$(1)' '$(2)' '$(C_RST)' '$(3)' + +.PHONY: help +help: + @printf '\n$(C_CYN)$(C_BOLD)%s$(C_RST)\n' 'Thirdweb Tools' + @$(hr) + @printf 'Usage: $(C_BOLD)make$(C_RST) $(C_CYN)[target]$(C_RST)\n\n' + @printf '$(C_BOLD)Targets:$(C_RST)\n' + @printf ' $(C_CYN)%-12s$(C_RST) - %s\n' 'build' 'Generate API and build the solution' + @printf ' $(C_CYN)%-12s$(C_RST) - %s\n' 'clean' 'Clean build artifacts' + @printf ' $(C_CYN)%-12s$(C_RST) - %s\n' 'restore' 'Restore NuGet packages' + @printf ' $(C_CYN)%-12s$(C_RST) - %s\n' 'test' 'Run tests' + @printf ' $(C_CYN)%-12s$(C_RST) - %s\n' 'pack' 'Generate API (if needed) and create NuGet package' + @printf ' $(C_CYN)%-12s$(C_RST) - %s\n' 'publish' 'Publish the Thirdweb project (dotnet publish)' + @printf ' $(C_CYN)%-12s$(C_RST) - %s\n' 'run' 'Run the console application' + @printf ' $(C_CYN)%-12s$(C_RST) - %s\n' 'generate' 'Generate API client from OpenAPI spec' + @printf ' $(C_CYN)%-12s$(C_RST) - %s\n' 'lint' 'Check code formatting (dry run)' + @printf ' $(C_CYN)%-12s$(C_RST) - %s\n' 'fix' 'Fix code formatting issues' + @printf ' $(C_CYN)%-12s$(C_RST) - %s\n' 'help' 'Show this help message' + @$(hr) + +.PHONY: publish +# Publish the Thirdweb library project +# Usage examples: +# make publish # Release publish +# make publish CONFIG=Debug # Debug config +# make publish RID=win-x64 # Target runtime +# make publish OUT=artifacts/publish # Custom output dir +publish: + @if [ ! -f '$(API_CLIENT)' ]; then \ + $(call msg,$(C_YEL),$(IC_WARN),API client not found, generating it first) ; \ + $(MAKE) --no-print-directory generate ; \ + fi + @$(call msg,$(C_BLU),$(IC_INFO),$(IC_PUB) Publishing Thirdweb project) + @CMD="$(DOTNET) publish '$(LIB_PROJ)' -c '$(CONFIG)' -f '$(TFM)'"; \ + if [ -n "$(RID)" ]; then CMD="$$CMD -r '$(RID)'"; fi; \ + if [ -n "$(OUT)" ]; then CMD="$$CMD -o '$(OUT)'"; fi; \ + echo $$CMD; eval $$CMD && \ + $(call msg,$(C_GRN),$(IC_OK),Publish succeeded) || \ + $(call msg,$(C_RED),$(IC_ERR),Publish failed) + +.PHONY: generate +# Clean previous file and generate API client +generate: + @$(call msg,$(C_BLU),$(IC_INFO),$(IC_GEN) Cleaning generated API files) + @rm -f '$(API_CLIENT)' 2>/dev/null || true + @$(call msg,$(C_BLU),$(IC_INFO),$(IC_GEN) Generating Thirdweb API client with custom generator) + @$(DOTNET) run --project '$(GENERATOR_PROJ)' --no-build >/dev/null 2>&1 \ + || ( \ + $(call msg,$(C_MAG),>> ,Building generator) ; \ + $(DOTNET) build '$(GENERATOR_PROJ)' ; \ + $(call msg,$(C_MAG),>> ,Running generator) ; \ + $(DOTNET) run --project '$(GENERATOR_PROJ)' \ + ) + @$(call msg,$(C_GRN),$(IC_OK),API client generation complete) + +.PHONY: build +build: + @$(MAKE) --no-print-directory generate + @$(call msg,$(C_BLU),$(IC_INFO),$(IC_BUILD) Building with dotnet build) + @$(DOTNET) build && \ + $(call msg,$(C_GRN),$(IC_OK),Build succeeded) || \ + $(call msg,$(C_RED),$(IC_ERR),Build failed) + +.PHONY: clean +clean: + @$(call msg,$(C_BLU),$(IC_INFO),$(IC_CLEAN) Cleaning with dotnet clean) + @$(DOTNET) clean && \ + $(call msg,$(C_GRN),$(IC_OK),Clean completed) || \ + $(call msg,$(C_RED),$(IC_ERR),Clean failed) + +.PHONY: restore +restore: + @$(call msg,$(C_BLU),$(IC_INFO),$(IC_RESTORE) Restoring with dotnet restore) + @$(DOTNET) restore && \ + $(call msg,$(C_GRN),$(IC_OK),Restore completed) || \ + $(call msg,$(C_RED),$(IC_ERR),Restore failed) + +.PHONY: test +test: + @$(call msg,$(C_BLU),$(IC_INFO),$(IC_TEST) Running dotnet test) + @$(DOTNET) test && \ + $(call msg,$(C_GRN),$(IC_OK),All tests passed) || \ + $(call msg,$(C_RED),$(IC_ERR),Some tests failed) + +.PHONY: pack +pack: + @if [ ! -f '$(API_CLIENT)' ]; then \ + $(call msg,$(C_YEL),$(IC_WARN),API client not found, generating it first) ; \ + $(MAKE) --no-print-directory generate ; \ + fi + @$(call msg,$(C_BLU),$(IC_INFO),$(IC_BUILD) Building Release) + @$(DOTNET) build --configuration Release || { $(call msg,$(C_RED),$(IC_ERR),Build (Release) failed); exit 1; } + @$(call msg,$(C_BLU),$(IC_INFO),$(IC_PACK) Packing NuGet package(s)) + @$(DOTNET) pack --configuration Release && \ + $(call msg,$(C_GRN),$(IC_OK),Pack completed) || \ + $(call msg,$(C_RED),$(IC_ERR),Packing failed) + +.PHONY: run +run: + @$(call msg,$(C_BLU),$(IC_INFO),$(IC_RUN) dotnet run --project $(CONSOLE_PROJ)) + @$(DOTNET) run --project '$(CONSOLE_PROJ)' && \ + $(call msg,$(C_GRN),$(IC_OK),Application exited) || \ + $(call msg,$(C_RED),$(IC_ERR),Application exited with errors) + +.PHONY: lint +lint: + @$(call msg,$(C_BLU),$(IC_INFO),$(IC_FMT) Checking code formatting with CSharpier) + @csharpier --help >/dev/null 2>&1 || { \ + $(call msg,$(C_YEL),$(IC_WARN),CSharpier is not installed) ; \ + printf ' Install it with: dotnet tool install -g csharpier\n' ; \ + exit 0 ; \ + } + @csharpier check . >/dev/null 2>&1 || { \ + $(call msg,$(C_YEL),$(IC_WARN),Formatting issues found) ; \ + printf ' Run "make fix" to automatically fix them.\n' ; \ + exit 0 ; \ + } + @$(call msg,$(C_GRN),$(IC_OK),Code formatting is correct) + +.PHONY: fix +fix: + @$(call msg,$(C_BLU),$(IC_INFO),$(IC_FMT) Running CSharpier formatter) + @csharpier --help >/dev/null 2>&1 || { \ + $(call msg,$(C_YEL),$(IC_WARN),CSharpier is not installed) ; \ + printf ' Install it with: dotnet tool install -g csharpier\n' ; \ + exit 0 ; \ + } + @csharpier format . >/dev/null 2>&1 || { \ + $(call msg,$(C_RED),$(IC_ERR),CSharpier formatting failed) ; \ + exit 1 ; \ + } + @$(call msg,$(C_GRN),$(IC_OK),Code formatting completed) diff --git a/README.md b/README.md index c3945fd9..a471dc71 100644 --- a/README.md +++ b/README.md @@ -9,23 +9,21 @@ The Thirdweb .NET SDK is a comprehensive and easy to use library that allows developers to interact with the blockchain using the .NET framework. It simplifies the integration of all [thirdweb](https://thirdweb.com/) functionality with a minimal set of dependencies. -## Features +## Core Features -- **Connect to any EVM network:** Easily connect to Ethereum and other EVM-compatible networks. -- **Query blockchain data:** Use Thirdweb RPC to fetch blockchain data efficiently. +- **Connect to any EVM network:** Easily connect to blockchain network with its chain id alone. - **Interact with smart contracts:** Simplified read and write operations for smart contracts, with various out-of-the-box extensions provided. -- **In-App Wallets:** Integrate user-friendly wallets within your applications, supporting email, phone, and OAuth login. +- **In-App Wallets:** Integrate user-friendly wallets within your applications, supporting email, phone, OAuth login or plug your own auth in. - **Ecosystem Wallets:** Basically In-App Wallets functionality wise, with the added benefit of being able to securely share your wallets with third party partners. -- **Account Abstraction:** Simplify complex account management tasks with smart wallets. -- **Gasless Transactions:** Enable transactions without requiring users to pay gas fees. -- **Storage Solutions:** Download and upload files using IPFS. +- **Account Abstraction:** Turn any wallet into a programmable smart wallet (EIP-4337 or EIP-7702) with built-in gas sponsorship and granular session key features. +- **Storage Solutions:** Download and upload files using IPFS or HTTPS. - **Transaction Builder:** Create, manipulate and send low level transactions. - **Session Keys:** Advanced control for smart wallets to manage permissions and session durations. - **Thirdweb Bridge:** Universal interface to use any asset onchain. - **Thirdweb Nebula:** Create blockchain-powered AI Agents. - **Thirdweb Insight:** Query blockchain data at the speed of light. - **Thirdweb Engine:** Interact in creative ways from your backend. -- **Unity Compatibility**: This SDK has been tested successfully in [Unity 2021.3+](https://portal.thirdweb.com/unity/v5) (Standalone, Mobile and WebGL). +- **Unity Compatibility**: This SDK has been tested successfully in [Unity 2022.3+](https://portal.thirdweb.com/unity/v5) (All build targets). - **Godot Compatibility**: This SDK has been tested successfully in [Godot .NET](https://portal.thirdweb.com/dotnet/godot) - **MAUI Compatibility**: This SDK has been tested successfully in [MAUI](https://portal.thirdweb.com/dotnet/maui) diff --git a/Thirdweb.Console/Program.cs b/Thirdweb.Console/Program.cs index 28fa0217..b7260bb5 100644 --- a/Thirdweb.Console/Program.cs +++ b/Thirdweb.Console/Program.cs @@ -14,313 +14,105 @@ // Fetch timeout options are optional, default is 120000ms var client = ThirdwebClient.Create(secretKey: secretKey); -#region Basic Wallet Interaction +#region Signing Messages -// Create a private key wallet -var privateKeyWallet = await PrivateKeyWallet.Generate(client); +// Create a guest wallet +var guestWallet = await InAppWallet.Create(client, authProvider: AuthProvider.Guest); +var walletAddress = await guestWallet.LoginWithGuest(); +Console.WriteLine($"Guest Wallet address: {walletAddress}"); -// var walletAddress = await privateKeyWallet.GetAddress(); -// Console.WriteLine($"PK Wallet address: {walletAddress}"); +var signature = await guestWallet.PersonalSign("Hello, Thirdweb!"); +Console.WriteLine($"Guest Wallet personal sign: {signature}"); #endregion -#region Basic Contract Interaction +#region Reading from Contracts // var contract = await ThirdwebContract.Create(client: client, address: "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d", chain: 1); -// var nfts = await contract.ERC721_GetAllNFTs(); +// var nfts = await contract.ERC721_GetNFT(0); // Console.WriteLine($"NFTs: {JsonConvert.SerializeObject(nfts, Formatting.Indented)}"); #endregion -#region Deploy Contract - -// var serverWallet = await ServerWallet.Create(client: client, label: "TestFromDotnet"); - -// var abi = -// "[ { \"inputs\": [], \"name\": \"welcome\", \"outputs\": [ { \"internalType\": \"string\", \"name\": \"\", \"type\": \"string\" } ], \"stateMutability\": \"pure\", \"type\": \"function\" } ]"; - -// var contractAddress = await ThirdwebContract.Deploy( -// client: client, -// chainId: 11155111, -// serverWalletAddress: await serverWallet.GetAddress(), -// bytecode: "6080604052348015600e575f5ffd5b5061014e8061001c5f395ff3fe608060405234801561000f575f5ffd5b5060043610610029575f3560e01c8063b627cf3b1461002d575b5f5ffd5b61003561004b565b60405161004291906100f8565b60405180910390f35b60606040518060400160405280601481526020017f57656c636f6d6520746f20746869726477656221000000000000000000000000815250905090565b5f81519050919050565b5f82825260208201905092915050565b8281835e5f83830152505050565b5f601f19601f8301169050919050565b5f6100ca82610088565b6100d48185610092565b93506100e48185602086016100a2565b6100ed816100b0565b840191505092915050565b5f6020820190508181035f83015261011081846100c0565b90509291505056fea264697066735822122001498e9d7d6125ce22613ef32fdb7e8e03bf11ad361d7b00e210b82d7b7e0d4464736f6c634300081e0033", -// abi: abi -// ); -// Console.WriteLine($"Contract deployed at: {contractAddress}"); +#region User Wallets (Social Auth Example) -// var contract = await ThirdwebContract.Create(client: client, address: contractAddress, chain: 11155111, abi: abi); -// var welcomeMessage = await contract.Read("welcome"); -// Console.WriteLine($"Welcome message from deployed contract: {welcomeMessage}"); - -#endregion - -#region Bridge - -// // Create a ThirdwebBridge instance -// var bridge = await ThirdwebBridge.Create(client); - -// // Buy - Get a quote for buying a specific amount of tokens -// var buyQuote = await bridge.Buy_Quote( -// originChainId: 1, -// originTokenAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC on Ethereum -// destinationChainId: 324, -// destinationTokenAddress: Constants.NATIVE_TOKEN_ADDRESS, // ETH on zkSync -// buyAmountWei: BigInteger.Parse("0.01".ToWei()) -// ); -// Console.WriteLine($"Buy quote: {JsonConvert.SerializeObject(buyQuote, Formatting.Indented)}"); - -// // Buy - Get an executable set of transactions (alongside a quote) for buying a specific amount of tokens -// var preparedBuy = await bridge.Buy_Prepare( -// originChainId: 1, -// originTokenAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC on Ethereum -// destinationChainId: 324, -// destinationTokenAddress: Constants.NATIVE_TOKEN_ADDRESS, // ETH on zkSync -// buyAmountWei: BigInteger.Parse("0.01".ToWei()), -// sender: await Utils.GetAddressFromENS(client, "vitalik.eth"), -// receiver: await myWallet.GetAddress() -// ); -// Console.WriteLine($"Prepared Buy contains {preparedBuy.Steps.Count} steps(s) with a total of {preparedBuy.Steps.Sum(step => step.Transactions.Count)} transactions!"); - -// // Sell - Get a quote for selling a specific amount of tokens -// var sellQuote = await bridge.Sell_Quote( -// originChainId: 324, -// originTokenAddress: Constants.NATIVE_TOKEN_ADDRESS, // ETH on zkSync -// destinationChainId: 1, -// destinationTokenAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC on Ethereum -// sellAmountWei: BigInteger.Parse("0.01".ToWei()) -// ); -// Console.WriteLine($"Sell quote: {JsonConvert.SerializeObject(sellQuote, Formatting.Indented)}"); - -// // Sell - Get an executable set of transactions (alongside a quote) for selling a specific amount of tokens -// var preparedSell = await bridge.Sell_Prepare( -// originChainId: 324, -// originTokenAddress: Constants.NATIVE_TOKEN_ADDRESS, // ETH on zkSync -// destinationChainId: 1, -// destinationTokenAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC on Ethereum -// sellAmountWei: BigInteger.Parse("0.01".ToWei()), -// sender: await Utils.GetAddressFromENS(client, "vitalik.eth"), -// receiver: await myWallet.GetAddress() -// ); -// Console.WriteLine($"Prepared Sell contains {preparedBuy.Steps.Count} steps(s) with a total of {preparedBuy.Steps.Sum(step => step.Transactions.Count)} transactions!"); - -// // Transfer - Get an executable transaction for transferring a specific amount of tokens -// var preparedTransfer = await bridge.Transfer_Prepare( -// chainId: 137, -// tokenAddress: Constants.NATIVE_TOKEN_ADDRESS, // POL on Polygon -// transferAmountWei: BigInteger.Parse("0.01".ToWei()), -// sender: await Utils.GetAddressFromENS(client, "vitalik.eth"), -// receiver: await myWallet.GetAddress() -// ); -// Console.WriteLine($"Prepared Transfer: {JsonConvert.SerializeObject(preparedTransfer, Formatting.Indented)}"); - -// // You may use our extensions to execute yourself... -// var myTx = await preparedTransfer.Transactions[0].ToThirdwebTransaction(myWallet); -// var myHash = await ThirdwebTransaction.Send(myTx); - -// // ...and poll for the status... -// var status = await bridge.Status(transactionHash: myHash, chainId: 1); -// var isComplete = status.StatusType == StatusType.COMPLETED; -// Console.WriteLine($"Status: {JsonConvert.SerializeObject(status, Formatting.Indented)}"); - -// // Or use our Execute extensions directly to handle everything for you! - -// // Execute a prepared Buy -// var buyResult = await bridge.Execute(myWallet, preparedBuy); -// var buyHashes = buyResult.Select(receipt => receipt.TransactionHash).ToList(); -// Console.WriteLine($"Buy hashes: {JsonConvert.SerializeObject(buyHashes, Formatting.Indented)}"); - -// // Execute a prepared Sell -// var sellResult = await bridge.Execute(myWallet, preparedSell); -// var sellHashes = sellResult.Select(receipt => receipt.TransactionHash).ToList(); -// Console.WriteLine($"Sell hashes: {JsonConvert.SerializeObject(sellHashes, Formatting.Indented)}"); - -// // Execute a prepared Transfer -// var transferResult = await bridge.Execute(myWallet, preparedTransfer); -// var transferHashes = transferResult.Select(receipt => receipt.TransactionHash).ToList(); -// Console.WriteLine($"Transfer hashes: {JsonConvert.SerializeObject(transferHashes, Formatting.Indented)}"); - -// // Onramp - Get a quote for buying crypto with Fiat -// var preparedOnramp = await bridge.Onramp_Prepare( -// onramp: OnrampProvider.Coinbase, -// chainId: 8453, -// tokenAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC on Base -// amount: "10000000", -// receiver: await myWallet.GetAddress() -// ); -// Console.WriteLine($"Onramp link: {preparedOnramp.Link}"); -// Console.WriteLine($"Full onramp quote and steps data: {JsonConvert.SerializeObject(preparedOnramp, Formatting.Indented)}"); - -// while (true) +// var inAppWalletOAuth = await InAppWallet.Create(client: client, authProvider: AuthProvider.Google); +// if (!await inAppWalletOAuth.IsConnected()) // { -// var onrampStatus = await bridge.Onramp_Status(id: preparedOnramp.Id); -// Console.WriteLine($"Full Onramp Status: {JsonConvert.SerializeObject(onrampStatus, Formatting.Indented)}"); -// if (onrampStatus.StatusType is StatusType.COMPLETED or StatusType.FAILED) -// { -// break; -// } -// await ThirdwebTask.Delay(5000); +// _ = await inAppWalletOAuth.LoginWithOauth( +// isMobile: false, +// (url) => +// { +// var psi = new ProcessStartInfo { FileName = url, UseShellExecute = true }; +// _ = Process.Start(psi); +// }, +// "thirdweb://", +// new InAppWalletBrowser() +// ); // } +// var inAppWalletOAuthAddress = await inAppWalletOAuth.GetAddress(); +// Console.WriteLine($"InAppWallet OAuth address: {inAppWalletOAuthAddress}"); -// if (preparedOnramp.IsSwapRequiredPostOnramp()) -// { -// // Execute additional steps that are required post-onramp to get to your token, manually or via the Execute extension -// var receipts = await bridge.Execute(myWallet, preparedOnramp); -// Console.WriteLine($"Onramp receipts: {JsonConvert.SerializeObject(receipts, Formatting.Indented)}"); -// } -// else -// { -// Console.WriteLine("No additional steps required post-onramp, you can use the tokens directly!"); -// } +// var inAppWalletAuthDetails = inAppWalletOAuth.GetUserAuthDetails(); +// Console.WriteLine($"InAppWallet OAuth auth details: {JsonConvert.SerializeObject(inAppWalletAuthDetails, Formatting.Indented)}"); #endregion -#region Indexer - -// // Create a ThirdwebInsight instance -// var insight = await ThirdwebInsight.Create(client); - -// var ethPriceToday = await insight.GetTokenPrice(addressOrSymbol: "ETH", chainId: 1); -// Console.WriteLine($"ETH price today: {ethPriceToday.PriceUsd}"); - -// var ethPriceYesterday = await insight.GetTokenPrice(addressOrSymbol: "ETH", chainId: 1, timestamp: Utils.GetUnixTimeStampNow() - 86400); -// Console.WriteLine($"ETH price yesterday: {ethPriceYesterday.PriceUsd}"); - -// var multiTokenPrices = await insight.GetTokenPrices(addressOrSymbols: new[] { "POL", "APE" }, chainIds: new BigInteger[] { 137, 33139 }); -// Console.WriteLine($"Multi token prices: {JsonConvert.SerializeObject(multiTokenPrices, Formatting.Indented)}"); - -// // Setup some filters -// var address = await Utils.GetAddressFromENS(client, "vitalik.eth"); -// var chains = new BigInteger[] { 1, 137, 42161 }; - -// // Fetch all token types -// var tokens = await insight.GetTokens(address, chains); -// Console.WriteLine($"ERC20 Count: {tokens.erc20Tokens.Length} | ERC721 Count: {tokens.erc721Tokens.Length} | ERC1155 Count: {tokens.erc1155Tokens.Length}"); +#region Server Wallets -// // Fetch specific token types -// var erc20Tokens = await insight.GetTokens_ERC20(address, chains); -// Console.WriteLine($"ERC20 Tokens: {JsonConvert.SerializeObject(erc20Tokens, Formatting.Indented)}"); - -// // Fetch specific token types -// var erc721Tokens = await insight.GetTokens_ERC721(address, chains); -// Console.WriteLine($"ERC721 Tokens: {JsonConvert.SerializeObject(erc721Tokens, Formatting.Indented)}"); - -// // Fetch specific token types -// var erc1155Tokens = await insight.GetTokens_ERC1155(address, chains); -// Console.WriteLine($"ERC1155 Tokens: {JsonConvert.SerializeObject(erc1155Tokens, Formatting.Indented)}"); - -// // Fetch events (great amount of optional filters available) -// var events = await insight.GetEvents( -// chainIds: new BigInteger[] { 1 }, // ethereum -// contractAddress: "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d", // bored apes -// eventSignature: "Transfer(address,address,uint256)", // transfer event -// fromTimestamp: Utils.GetUnixTimeStampNow() - 3600, // last hour -// sortBy: SortBy.TransactionIndex, // block number, block timestamp or transaction index -// sortOrder: SortOrder.Desc, // latest first -// limit: 5 // last 5 transfers -// ); -// Console.WriteLine($"Events: {JsonConvert.SerializeObject(events, Formatting.Indented)}"); - -// // Fetch transactions (great amount of optional filters available) -// var transactions = await insight.GetTransactions( -// chainIds: new BigInteger[] { 1 }, // ethereum -// contractAddress: "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d", // bored apes -// fromTimestamp: Utils.GetUnixTimeStampNow() - 3600, // last hour -// sortBy: SortBy.TransactionIndex, // block number, block timestamp or transaction index -// sortOrder: SortOrder.Desc, // latest first -// limit: 5 // last 5 transactions +// // ServerWallet is compatible with IThirdwebWallet and can be used with any SDK method/extension +// var serverWallet = await ServerWallet.Create( +// client: client, +// label: "Test", +// // Optional, defaults to Auto - we choose between EIP-7702, EIP-4337 or native zkSync AA execution / EOA is also available +// executionOptions: new AutoExecutionOptions() // ); -// Console.WriteLine($"Transactions: {JsonConvert.SerializeObject(transactions, Formatting.Indented)}"); - -// // Use ToNFT to ToNFTList extensions -// var convertedNft = erc721Tokens[0].ToNFT(); - -// var convertedNfts = erc721Tokens.ToNFTList(); - -// // Use NFT Extensions (GetNFTImageBytes, or GetNFTSprite in Unity) -// var imageBytes = await convertedNft.GetNFTImageBytes(client); -// var pathToSave = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "nft.png"); -// await File.WriteAllBytesAsync(pathToSave, imageBytes); -// Console.WriteLine($"NFT image saved to: {pathToSave}"); - -#endregion -#region AI +// var serverWalletAddress = await serverWallet.GetAddress(); +// Console.WriteLine($"Server Wallet address: {serverWalletAddress}"); -// // Prepare some context -// var myChain = 11155111; -// var myWallet = await SmartWallet.Create(personalWallet: await PrivateKeyWallet.Generate(client), chainId: myChain, gasless: true); -// var myContractAddress = "0xe2cb0eb5147b42095c2FfA6F7ec953bb0bE347D8"; // DropERC1155 -// var usdcAddress = "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238"; +// var serverWalletPersonalSig = await serverWallet.PersonalSign("Hello, Thirdweb!"); +// Console.WriteLine($"Server Wallet personal sign: {serverWalletPersonalSig}"); -// // Create a Nebula session -// var nebula = await ThirdwebNebula.Create(client); +// var json = +// /*lang=json,strict*/ +// "{\"types\":{\"EIP712Domain\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"version\",\"type\":\"string\"},{\"name\":\"chainId\",\"type\":\"uint256\"},{\"name\":\"verifyingContract\",\"type\":\"address\"}],\"Person\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"wallet\",\"type\":\"address\"}],\"Mail\":[{\"name\":\"from\",\"type\":\"Person\"},{\"name\":\"to\",\"type\":\"Person\"},{\"name\":\"contents\",\"type\":\"string\"}]},\"primaryType\":\"Mail\",\"domain\":{\"name\":\"Ether Mail\",\"version\":\"1\",\"chainId\":84532,\"verifyingContract\":\"0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC\"},\"message\":{\"from\":{\"name\":\"Cow\",\"wallet\":\"0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826\"},\"to\":{\"name\":\"Bob\",\"wallet\":\"0xbBbBBBBbbBBBbbbBbbBbbBBbBbbBbBbBbBbbBBbB\"},\"contents\":\"Hello, Bob!\"}}"; +// var serverWalletTypedDataSign = await serverWallet.SignTypedDataV4(json); +// Console.WriteLine($"Server Wallet typed data sign: {serverWalletTypedDataSign}"); -// // Chat, passing wallet context -// var response1 = await nebula.Chat(message: "What is my wallet address?", wallet: myWallet); -// Console.WriteLine($"Response 1: {response1.Message}"); +// // Simple self transfer +// var serverWalletReceipt = await serverWallet.Transfer(chainId: 84532, toAddress: await serverWallet.GetAddress(), weiAmount: 0); +// Console.WriteLine($"Server Wallet Hash: {serverWalletReceipt.TransactionHash}"); -// // Chat, passing contract context -// var response2 = await nebula.Chat( -// message: "What's the total supply of token id 0 for this contract?", -// context: new NebulaContext(contractAddresses: new List { myContractAddress }, chainIds: new List { myChain }) -// ); -// Console.WriteLine($"Response 2: {response2.Message}"); +// // ServerWallet forcing ERC-4337 Execution Mode +// var smartServerWallet = await ServerWallet.Create(client: client, label: "Test", executionOptions: new ERC4337ExecutionOptions(chainId: 84532, signerAddress: serverWalletAddress)); +// var smartServerWalletAddress = await smartServerWallet.GetAddress(); +// Console.WriteLine($"Smart Server Wallet address: {smartServerWalletAddress}"); -// // Chat, passing multiple messages and context -// var response3 = await nebula.Chat( -// messages: new List -// { -// new($"Tell me the name of this contract: {myContractAddress}", NebulaChatRole.User), -// new("The name of the contract is CatDrop", NebulaChatRole.Assistant), -// new("What's the symbol of this contract?", NebulaChatRole.User), -// }, -// context: new NebulaContext(contractAddresses: new List { myContractAddress }, chainIds: new List { myChain }) -// ); -// Console.WriteLine($"Response 3: {response3.Message}"); +// var smartServerWalletPersonalSig = await smartServerWallet.PersonalSign("Hello, Thirdweb!"); +// Console.WriteLine($"Smart Server Wallet personal sign: {smartServerWalletPersonalSig}"); -// // Execute, this directly sends transactions -// var executionResult = await nebula.Execute("Approve 1 USDC to vitalik.eth", wallet: myWallet, context: new NebulaContext(contractAddresses: new List() { usdcAddress })); -// if (executionResult.TransactionReceipts != null && executionResult.TransactionReceipts.Count > 0) -// { -// Console.WriteLine($"Receipt: {executionResult.TransactionReceipts[0]}"); -// } -// else -// { -// Console.WriteLine($"Message: {executionResult.Message}"); -// } +// var smartServerWalletTypedDataSign = await smartServerWallet.SignTypedDataV4(json); +// Console.WriteLine($"Smart Server Wallet typed data sign: {smartServerWalletTypedDataSign}"); -// // Batch execute -// var batchExecutionResult = await nebula.Execute( -// new List -// { -// new("What's the address of vitalik.eth", NebulaChatRole.User), -// new("The address of vitalik.eth is 0xd8dA6BF26964aF8E437eEa5e3616511D7G3a3298", NebulaChatRole.Assistant), -// new("Approve 1 USDC to them", NebulaChatRole.User), -// }, -// wallet: myWallet, -// context: new NebulaContext(contractAddresses: new List() { usdcAddress }) -// ); -// if (batchExecutionResult.TransactionReceipts != null && batchExecutionResult.TransactionReceipts.Count > 0) -// { -// Console.WriteLine($"Receipts: {JsonConvert.SerializeObject(batchExecutionResult.TransactionReceipts, Formatting.Indented)}"); -// } -// else -// { -// Console.WriteLine($"Message: {batchExecutionResult.Message}"); -// } +// // Simple self transfer +// var smartServerWalletReceipt = await smartServerWallet.Transfer(chainId: 84532, toAddress: await smartServerWallet.GetAddress(), weiAmount: 0); +// Console.WriteLine($"Server Wallet Hash: {smartServerWalletReceipt.TransactionHash}"); #endregion -#region Get Social Profiles +#region Thirdweb API Wrapper -// var socialProfiles = await Utils.GetSocialProfiles(client, "joenrv.eth"); -// Console.WriteLine($"Social Profiles: {socialProfiles}"); +var metadata = await client.Api.GetContractMetadataAsync(chainId: 1, address: "0xBd3531dA5CF5857e7CfAA92426877b022e612cf8"); + +Console.WriteLine($"ABI: {JsonConvert.SerializeObject(metadata.Result.Output.Abi, Formatting.Indented)}"); +Console.WriteLine($"Compiler version: {metadata.Result.Compiler.Version}"); #endregion #region AA 0.6 -// var smartWallet06 = await SmartWallet.Create(personalWallet: privateKeyWallet, chainId: 421614, gasless: true); +// var smartWallet06 = await SmartWallet.Create(personalWallet: guestWallet, chainId: 421614, gasless: true); // var receipt06 = await smartWallet06.Transfer(chainId: 421614, toAddress: await smartWallet06.GetAddress(), weiAmount: 0); // Console.WriteLine($"Receipt: {receipt06}"); @@ -328,7 +120,7 @@ #region AA 0.7 -// var smartWallet07 = await SmartWallet.Create(personalWallet: privateKeyWallet, chainId: 421614, gasless: true, entryPoint: Constants.ENTRYPOINT_ADDRESS_V07); +// var smartWallet07 = await SmartWallet.Create(personalWallet: guestWallet, chainId: 421614, gasless: true, entryPoint: Constants.ENTRYPOINT_ADDRESS_V07); // var receipt07 = await smartWallet07.Transfer(chainId: 421614, toAddress: await smartWallet07.GetAddress(), weiAmount: 0); // Console.WriteLine($"Receipt: {receipt07}"); @@ -344,50 +136,36 @@ #endregion -#region Server Wallet - -// // ServerWallet is compatible with IThirdwebWallet and can be used with any SDK method/extension -// var serverWallet = await ServerWallet.Create( -// client: client, -// label: "Test", -// // Optional, defaults to Auto - we choose between EIP-7702, EIP-4337 or native zkSync AA execution / EOA is also available -// executionOptions: new AutoExecutionOptions() -// ); - -// var serverWalletAddress = await serverWallet.GetAddress(); -// Console.WriteLine($"Server Wallet address: {serverWalletAddress}"); +#region Deploy Contract -// var serverWalletPersonalSig = await serverWallet.PersonalSign("Hello, Thirdweb!"); -// Console.WriteLine($"Server Wallet personal sign: {serverWalletPersonalSig}"); +// var serverWallet = await ServerWallet.Create(client: client, label: "TestFromDotnet"); -// var json = -// /*lang=json,strict*/ -// "{\"types\":{\"EIP712Domain\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"version\",\"type\":\"string\"},{\"name\":\"chainId\",\"type\":\"uint256\"},{\"name\":\"verifyingContract\",\"type\":\"address\"}],\"Person\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"wallet\",\"type\":\"address\"}],\"Mail\":[{\"name\":\"from\",\"type\":\"Person\"},{\"name\":\"to\",\"type\":\"Person\"},{\"name\":\"contents\",\"type\":\"string\"}]},\"primaryType\":\"Mail\",\"domain\":{\"name\":\"Ether Mail\",\"version\":\"1\",\"chainId\":84532,\"verifyingContract\":\"0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC\"},\"message\":{\"from\":{\"name\":\"Cow\",\"wallet\":\"0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826\"},\"to\":{\"name\":\"Bob\",\"wallet\":\"0xbBbBBBBbbBBBbbbBbbBbbBBbBbbBbBbBbBbbBBbB\"},\"contents\":\"Hello, Bob!\"}}"; -// var serverWalletTypedDataSign = await serverWallet.SignTypedDataV4(json); -// Console.WriteLine($"Server Wallet typed data sign: {serverWalletTypedDataSign}"); +// var abi = +// "[ { \"inputs\": [], \"name\": \"welcome\", \"outputs\": [ { \"internalType\": \"string\", \"name\": \"\", \"type\": \"string\" } ], \"stateMutability\": \"pure\", \"type\": \"function\" } ]"; -// // Simple self transfer -// var serverWalletReceipt = await serverWallet.Transfer(chainId: 84532, toAddress: await serverWallet.GetAddress(), weiAmount: 0); -// Console.WriteLine($"Server Wallet Hash: {serverWalletReceipt.TransactionHash}"); +// var contractAddress = await ThirdwebContract.Deploy( +// client: client, +// chainId: 11155111, +// serverWalletAddress: await serverWallet.GetAddress(), +// bytecode: "6080604052348015600e575f5ffd5b5061014e8061001c5f395ff3fe608060405234801561000f575f5ffd5b5060043610610029575f3560e01c8063b627cf3b1461002d575b5f5ffd5b61003561004b565b60405161004291906100f8565b60405180910390f35b60606040518060400160405280601481526020017f57656c636f6d6520746f20746869726477656221000000000000000000000000815250905090565b5f81519050919050565b5f82825260208201905092915050565b8281835e5f83830152505050565b5f601f19601f8301169050919050565b5f6100ca82610088565b6100d48185610092565b93506100e48185602086016100a2565b6100ed816100b0565b840191505092915050565b5f6020820190508181035f83015261011081846100c0565b90509291505056fea264697066735822122001498e9d7d6125ce22613ef32fdb7e8e03bf11ad361d7b00e210b82d7b7e0d4464736f6c634300081e0033", +// abi: abi +// ); +// Console.WriteLine($"Contract deployed at: {contractAddress}"); -// // ServerWallet forcing ERC-4337 Execution Mode -// var smartServerWallet = await ServerWallet.Create(client: client, label: "Test", executionOptions: new ERC4337ExecutionOptions(chainId: 84532, signerAddress: serverWalletAddress)); -// var smartServerWalletAddress = await smartServerWallet.GetAddress(); -// Console.WriteLine($"Smart Server Wallet address: {smartServerWalletAddress}"); +// var contract = await ThirdwebContract.Create(client: client, address: contractAddress, chain: 11155111, abi: abi); +// var welcomeMessage = await contract.Read("welcome"); +// Console.WriteLine($"Welcome message from deployed contract: {welcomeMessage}"); -// var smartServerWalletPersonalSig = await smartServerWallet.PersonalSign("Hello, Thirdweb!"); -// Console.WriteLine($"Smart Server Wallet personal sign: {smartServerWalletPersonalSig}"); +#endregion -// var smartServerWalletTypedDataSign = await smartServerWallet.SignTypedDataV4(json); -// Console.WriteLine($"Smart Server Wallet typed data sign: {smartServerWalletTypedDataSign}"); +#region Get Social Profiles -// // Simple self transfer -// var smartServerWalletReceipt = await smartServerWallet.Transfer(chainId: 84532, toAddress: await smartServerWallet.GetAddress(), weiAmount: 0); -// Console.WriteLine($"Server Wallet Hash: {smartServerWalletReceipt.TransactionHash}"); +// var socialProfiles = await Utils.GetSocialProfiles(client, "joenrv.eth"); +// Console.WriteLine($"Social Profiles: {socialProfiles}"); #endregion -#region EIP-7702 +#region EIP-7702 (Low Level) // var chain = 11155111; // 7702-compatible chain @@ -498,8 +276,6 @@ // var ecosystemPersonalSignature = await ecosystemWallet.PersonalSign("Hello, Thirdweb!"); // Console.WriteLine($"Ecosystem Wallet personal sign: {ecosystemPersonalSignature}"); -// var isValidPersonal = (await ecosystemWallet.RecoverAddressFromPersonalSign("Hello, Thirdweb!", ecosystemPersonalSignature)) == ecosystemWalletAddress; -// Console.WriteLine($"Ecosystem Wallet personal sign valid: {isValidPersonal}"); // var ecosystemTypedSignature = await ecosystemWallet.SignTypedDataV4( // /*lang=json,strict*/ @@ -581,29 +357,6 @@ #endregion -#region Guest Login - -// var guestWallet = await EcosystemWallet.Create(ecosystemId: "ecosystem.the-bonfire", client: client, authProvider: AuthProvider.Guest); -// if (!await guestWallet.IsConnected()) -// { -// _ = await guestWallet.LoginWithGuest(); -// } -// var address = await guestWallet.GetAddress(); -// Console.WriteLine($"Guest address: {address}"); - -// var oldLinkedAccounts = await guestWallet.GetLinkedAccounts(); -// Console.WriteLine($"Old linked accounts: {JsonConvert.SerializeObject(oldLinkedAccounts, Formatting.Indented)}"); - -// var emailWalletFresh = await EcosystemWallet.Create(ecosystemId: "ecosystem.the-bonfire", client: client, email: "firekeeper+guestupgrade5@thirdweb.com"); -// _ = await emailWalletFresh.SendOTP(); -// Console.WriteLine("Enter OTP:"); -// var otp = Console.ReadLine(); - -// var linkedAccounts = await guestWallet.LinkAccount(walletToLink: emailWalletFresh, otp: otp); -// Console.WriteLine($"Linked accounts: {JsonConvert.SerializeObject(linkedAccounts, Formatting.Indented)}"); - -#endregion - #region Backend Wallet Auth // var inAppWalletBackend = await InAppWallet.Create(client: client, authProvider: AuthProvider.Backend, walletSecret: "very-secret"); @@ -728,90 +481,6 @@ #endregion -#region Self Transfer Transaction - -// var tx = await ThirdwebTransaction.Create( -// wallet: privateKeyWallet, -// txInput: new ThirdwebTransactionInput() -// { -// To = await privateKeyWallet.GetAddress(), -// Value = new HexBigInteger(BigInteger.Zero), -// }, -// chainId: 842 -// ); -// var txHash = await ThirdwebTransaction.Send(tx); -// Console.WriteLine($"Transaction hash: {txHash}"); - -#endregion - -#region InAppWallet - OAuth - -// var inAppWalletOAuth = await InAppWallet.Create(client: client, authProvider: AuthProvider.TikTok); -// if (!await inAppWalletOAuth.IsConnected()) -// { -// _ = await inAppWalletOAuth.LoginWithOauth( -// isMobile: false, -// (url) => -// { -// var psi = new ProcessStartInfo { FileName = url, UseShellExecute = true }; -// _ = Process.Start(psi); -// }, -// "thirdweb://", -// new InAppWalletBrowser() -// ); -// } -// var inAppWalletOAuthAddress = await inAppWalletOAuth.GetAddress(); -// Console.WriteLine($"InAppWallet OAuth address: {inAppWalletOAuthAddress}"); - -// var inAppWalletAuthDetails = inAppWalletOAuth.GetUserAuthDetails(); -// Console.WriteLine($"InAppWallet OAuth auth details: {JsonConvert.SerializeObject(inAppWalletAuthDetails, Formatting.Indented)}"); - -#endregion - -#region InAppWallet - SiweExternal - -// var inAppWalletSiweExternal = await InAppWallet.Create(client: client, authProvider: AuthProvider.SiweExternal); -// if (!await inAppWalletSiweExternal.IsConnected()) -// { -// _ = await inAppWalletSiweExternal.LoginWithSiweExternal( -// isMobile: false, -// browserOpenAction: (url) => -// { -// var psi = new ProcessStartInfo { FileName = url, UseShellExecute = true }; -// _ = Process.Start(psi); -// }, -// forceWalletIds: new List { "io.metamask", "com.coinbase.wallet", "xyz.abs" } -// ); -// } -// var inAppWalletOAuthAddress = await inAppWalletSiweExternal.GetAddress(); -// Console.WriteLine($"InAppWallet SiweExternal address: {inAppWalletOAuthAddress}"); - -// var inAppWalletAuthDetails = inAppWalletSiweExternal.GetUserAuthDetails(); -// Console.WriteLine($"InAppWallet OAuth auth details: {JsonConvert.SerializeObject(inAppWalletAuthDetails, Formatting.Indented)}"); - -// await inAppWalletSiweExternal.Disconnect(); - -#endregion - -#region Smart Wallet - Gasless Transaction - -// var smartWallet = await SmartWallet.Create(privateKeyWallet, 78600); - -// // Self transfer 0 -// var tx2 = await ThirdwebTransaction.Create( -// smartWallet, -// new ThirdwebTransactionInput() -// { -// To = await smartWallet.GetAddress(), -// Value = new HexBigInteger(BigInteger.Zero) -// }, -// 78600 -// ); -// var txHash2 = await ThirdwebTransaction.Send(tx2); -// Console.WriteLine($"Transaction hash: {txHash2}"); - -#endregion - #region Storage Actions // // Will download from IPFS or normal urls diff --git a/Thirdweb.Generator/Program.cs b/Thirdweb.Generator/Program.cs new file mode 100644 index 00000000..795508cc --- /dev/null +++ b/Thirdweb.Generator/Program.cs @@ -0,0 +1,179 @@ +using System.Globalization; +using NJsonSchema; +using NSwag; +using NSwag.CodeGeneration.CSharp; + +static string FindRepoRoot() +{ + var dir = new DirectoryInfo(Directory.GetCurrentDirectory()); + while (dir != null) + { + if (File.Exists(Path.Combine(dir.FullName, "thirdweb.sln"))) + { + return dir.FullName; + } + dir = dir.Parent; + } + // Fallback to current directory + return Directory.GetCurrentDirectory(); +} + +var specUrl = "https://api.thirdweb.com/openapi.json"; +var repoRoot = FindRepoRoot(); +var outputPath = Path.Combine(repoRoot, "Thirdweb", "Thirdweb.Api", "ThirdwebApi.cs"); + +Console.WriteLine($"Loading OpenAPI from {specUrl}..."); +var document = await OpenApiDocument.FromUrlAsync(specUrl); + +Console.WriteLine("Deduplicating enum values across all schemas (inline + components)..."); + +var visited = new HashSet(); + +void DedupeEnumOnSchema(JsonSchema schema, string? debugPath) +{ + if (schema == null) + { + return; + } + if (!visited.Add(schema)) + { + return; + } + + var s = schema.ActualSchema ?? schema; + + if (s.Enumeration != null && s.Enumeration.Count > 0) + { + var seen = new HashSet(StringComparer.Ordinal); + var newEnum = new List(); + var enumList = s.Enumeration.ToList(); + + for (var i = 0; i < enumList.Count; i++) + { + var v = enumList[i]; + var key = Convert.ToString(v, CultureInfo.InvariantCulture) ?? ""; + if (seen.Add(key)) + { + newEnum.Add(v!); + } + } + + if (newEnum.Count != s.Enumeration.Count) + { + s.Enumeration.Clear(); + foreach (var v in newEnum) + { + s.Enumeration.Add(v); + } + + // Remove x-enumNames to avoid misalignment with deduped values + if (s.ExtensionData != null && s.ExtensionData.ContainsKey("x-enumNames")) + { + _ = s.ExtensionData.Remove("x-enumNames"); + } + + Console.WriteLine($" - Deduped enum at {debugPath ?? ""}: {newEnum.Count} unique values"); + } + } + + // Recurse into nested schemas + foreach (var p in s.Properties) + { + DedupeEnumOnSchema(p.Value, $"{debugPath}/properties/{p.Key}"); + } + + if (s.AdditionalPropertiesSchema != null) + { + DedupeEnumOnSchema(s.AdditionalPropertiesSchema, $"{debugPath}/additionalProperties"); + } + + if (s.Item != null) + { + DedupeEnumOnSchema(s.Item, $"{debugPath}/items"); + } + + foreach (var a in s.AllOf) + { + DedupeEnumOnSchema(a, $"{debugPath}/allOf"); + } + foreach (var o in s.OneOf) + { + DedupeEnumOnSchema(o, $"{debugPath}/oneOf"); + } + foreach (var a in s.AnyOf) + { + DedupeEnumOnSchema(a, $"{debugPath}/anyOf"); + } + if (s.Not != null) + { + DedupeEnumOnSchema(s.Not, $"{debugPath}/not"); + } +} + +// Components +foreach (var kvp in document.Components.Schemas) +{ + DedupeEnumOnSchema(kvp.Value, $"#/components/schemas/{kvp.Key}"); +} + +// Parameters +foreach (var path in document.Paths) +{ + foreach (var opKvp in path.Value) + { + var op = opKvp.Value; + foreach (var prm in op.Parameters) + { + if (prm.Schema != null) + { + DedupeEnumOnSchema(prm.Schema, $"#/paths{path.Key}/{op.OperationId}/parameters/{prm.Name}"); + } + } + // Request body + var rb = op.RequestBody; + if (rb?.Content != null) + { + foreach (var c in rb.Content) + { + if (c.Value.Schema != null) + { + DedupeEnumOnSchema(c.Value.Schema, $"#/paths{path.Key}/{op.OperationId}/requestBody/{c.Key}"); + } + } + } + // Responses + foreach (var resp in op.Responses) + { + if (resp.Value.Content != null) + { + foreach (var c in resp.Value.Content) + { + if (c.Value.Schema != null) + { + DedupeEnumOnSchema(c.Value.Schema, $"#/paths{path.Key}/{op.OperationId}/responses/{resp.Key}/{c.Key}"); + } + } + } + } + } +} + +var settings = new CSharpClientGeneratorSettings +{ + ClassName = "ThirdwebApiClient", + CSharpGeneratorSettings = { Namespace = "Thirdweb.Api", ClassStyle = NJsonSchema.CodeGeneration.CSharp.CSharpClassStyle.Poco }, + GenerateClientClasses = true, + GenerateDtoTypes = true, + GenerateExceptionClasses = true, + ClientClassAccessModifier = "public", + // Use our HttpClient wrapper type + HttpClientType = "ThirdwebHttpClientWrapper", +}; + +Console.WriteLine("Generating C# client code..."); +var generator = new CSharpClientGenerator(document, settings); +var code = generator.GenerateFile(); + +Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); +await File.WriteAllTextAsync(outputPath, code); +Console.WriteLine($"Wrote generated client to {outputPath}"); diff --git a/Thirdweb.Generator/Thirdweb.Generator.csproj b/Thirdweb.Generator/Thirdweb.Generator.csproj new file mode 100644 index 00000000..6d6375cd --- /dev/null +++ b/Thirdweb.Generator/Thirdweb.Generator.csproj @@ -0,0 +1,12 @@ + + + Exe + net8.0 + enable + enable + + + + + + diff --git a/Thirdweb.Tests/BaseTests.cs b/Thirdweb.Tests/BaseTests.cs index fecb140d..cc70c5fe 100644 --- a/Thirdweb.Tests/BaseTests.cs +++ b/Thirdweb.Tests/BaseTests.cs @@ -29,4 +29,22 @@ public void DotEnvTest() { Assert.NotNull(this.SecretKey); } + + public async Task GetGuestAccount() + { + var iaw = await InAppWallet.Create(this.Client, authProvider: AuthProvider.Guest); + if (await iaw.IsConnected()) + { + await iaw.Disconnect(); + } + _ = await iaw.LoginWithGuest(defaultSessionIdOverride: Guid.NewGuid().ToString()); + return iaw; + } + + public async Task GetSmartAccount(int chainId = 421614) + { + var guestAccount = await this.GetGuestAccount(); + var smartAccount = await SmartWallet.Create(personalWallet: guestAccount, chainId: chainId); + return smartAccount; + } } diff --git a/Thirdweb.Tests/Thirdweb.AI/Thirdweb.AI.Tests.cs b/Thirdweb.Tests/Thirdweb.AI/Thirdweb.AI.Tests.cs deleted file mode 100644 index 28f03e8e..00000000 --- a/Thirdweb.Tests/Thirdweb.AI/Thirdweb.AI.Tests.cs +++ /dev/null @@ -1,83 +0,0 @@ -// using System.Numerics; -using System.Numerics; -using Thirdweb.AI; - -namespace Thirdweb.Tests.AI; - -public class NebulaTests : BaseTests -{ - // private const string NEBULA_TEST_USDC_ADDRESS = "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238"; - - private const string NEBULA_TEST_CONTRACT = "0xe2cb0eb5147b42095c2FfA6F7ec953bb0bE347D8"; - - private const int NEBULA_TEST_CHAIN = 11155111; - - public NebulaTests(ITestOutputHelper output) - : base(output) { } - - [Fact(Timeout = 120000)] - public async Task Create_CreatesSession() - { - var nebula = await ThirdwebNebula.Create(this.Client); - Assert.NotNull(nebula); - Assert.NotNull(nebula.SessionId); - } - - [Fact(Timeout = 120000)] - public async Task Create_ResumesSession() - { - var nebula = await ThirdwebNebula.Create(this.Client); - var sessionId = nebula.SessionId; - Assert.NotNull(nebula); - Assert.NotNull(nebula.SessionId); - - nebula = await ThirdwebNebula.Create(this.Client, sessionId); - Assert.NotNull(nebula); - Assert.Equal(sessionId, nebula.SessionId); - } - - [Fact(Timeout = 120000)] - public async Task Chat_Single_ReturnsResponse() - { - var nebula = await ThirdwebNebula.Create(this.Client); - var response = await nebula.Chat(message: $"What's the symbol of this contract {NEBULA_TEST_CONTRACT}?", context: new NebulaContext(chainIds: new List() { NEBULA_TEST_CHAIN })); - Assert.NotNull(response); - Assert.NotNull(response.Message); - Assert.Contains("CAT", response.Message); - } - - [Fact(Timeout = 120000)] - public async Task Chat_UnderstandsWalletContext() - { - var wallet = await PrivateKeyWallet.Generate(this.Client); - var expectedAddress = await wallet.GetAddress(); - var nebula = await ThirdwebNebula.Create(this.Client); - var response = await nebula.Chat(message: "What is my wallet address?", wallet: wallet); - Assert.NotNull(response); - Assert.NotNull(response.Message); - Assert.Contains(expectedAddress, response.Message); - } - - // [Fact(Timeout = 120000)] - // public async Task Execute_ReturnsMessageAndReceipt() - // { - // var signer = await PrivateKeyWallet.Generate(this.Client); - // var wallet = await SmartWallet.Create(signer, NEBULA_TEST_CHAIN); - // var nebula = await ThirdwebNebula.Create(this.Client); - // var response = await nebula.Execute( - // new List - // { - // new("What's the address of vitalik.eth", NebulaChatRole.User), - // new("The address of vitalik.eth is 0xd8dA6BF26964aF8E437eEa5e3616511D7G3a3298", NebulaChatRole.Assistant), - // new($"Approve 1 USDC (this contract: {NEBULA_TEST_USDC_ADDRESS}) to them", NebulaChatRole.User), - // }, - // wallet: wallet - // ); - // Assert.NotNull(response); - // Assert.NotNull(response.Message); - // Assert.NotNull(response.TransactionReceipts); - // Assert.NotEmpty(response.TransactionReceipts); - // Assert.NotNull(response.TransactionReceipts[0].TransactionHash); - // Assert.True(response.TransactionReceipts[0].TransactionHash.Length == 66); - // } -} diff --git a/Thirdweb.Tests/Thirdweb.Contracts/Thirdweb.Contracts.Tests.cs b/Thirdweb.Tests/Thirdweb.Contracts/Thirdweb.Contracts.Tests.cs index 844a4b77..a9b6a1a3 100644 --- a/Thirdweb.Tests/Thirdweb.Contracts/Thirdweb.Contracts.Tests.cs +++ b/Thirdweb.Tests/Thirdweb.Contracts/Thirdweb.Contracts.Tests.cs @@ -189,7 +189,7 @@ public async Task WriteTest_SmartAccount_FullSig() public async Task WriteTest_PrivateKeyAccount() { var contract = await this.GetContract(); - var privateKeyAccount = await PrivateKeyWallet.Generate(contract.Client); + var privateKeyAccount = await this.GetGuestAccount(); var receiver = await privateKeyAccount.GetAddress(); var quantity = BigInteger.One; var currency = Constants.NATIVE_TOKEN_ADDRESS; @@ -212,27 +212,13 @@ public async Task WriteTest_PrivateKeyAccount() [Fact(Timeout = 120000)] public async Task SignatureMint_Generate() { - var client = this.Client; - var signer = await PrivateKeyWallet.Generate(client); + var signer = await this.GetGuestAccount(); var randomDomain = "Test"; var randomVersion = "1.0.0"; var randomChainId = 421614; var randomContractAddress = "0xD04F98C88cE1054c90022EE34d566B9237a1203C"; - // GenerateSignature_MinimalForwarder - var forwardRequest = new Forwarder_ForwardRequest - { - From = "0x123", - To = "0x456", - Value = BigInteger.Zero, - Gas = BigInteger.Zero, - Nonce = BigInteger.Zero, - Data = "0x", - }; - var signature = await EIP712.GenerateSignature_MinimalForwarder(randomDomain, randomVersion, randomChainId, randomContractAddress, forwardRequest, signer); - Assert.NotNull(signature); - Assert.StartsWith("0x", signature); // GenerateSignature_TokenERC20 var mintRequest20 = new TokenERC20_MintRequest { @@ -290,8 +276,7 @@ public async Task SignatureMint_Generate() private async Task GetAccount() { - var client = this.Client; - var privateKeyAccount = await PrivateKeyWallet.Generate(client); + var privateKeyAccount = await this.GetGuestAccount(); var smartAccount = await SmartWallet.Create(personalWallet: privateKeyAccount, factoryAddress: "0xbf1C9aA4B1A085f7DA890a44E82B0A1289A40052", gasless: true, chainId: 421614); return smartAccount; } diff --git a/Thirdweb.Tests/Thirdweb.Extensions/Thirdweb.Extensions.Tests.cs b/Thirdweb.Tests/Thirdweb.Extensions/Thirdweb.Extensions.Tests.cs index 43447cc4..ad8293cc 100644 --- a/Thirdweb.Tests/Thirdweb.Extensions/Thirdweb.Extensions.Tests.cs +++ b/Thirdweb.Tests/Thirdweb.Extensions/Thirdweb.Extensions.Tests.cs @@ -20,7 +20,7 @@ public ExtensionsTests(ITestOutputHelper output) private async Task GetSmartWallet() { - var privateKeyWallet = await PrivateKeyWallet.Generate(this.Client); + var privateKeyWallet = await this.GetGuestAccount(); return await SmartWallet.Create(personalWallet: privateKeyWallet, chainId: 421614); } @@ -1420,8 +1420,8 @@ public async Task TokenERC20_NullChecks() public async Task TokenERC20_GenerateMintSignature_WithVerify() { var contract = await this.GetTokenERC20Contract(); - var fakeAuthorizedSigner = await PrivateKeyWallet.Generate(this.Client); - var randomReceiver = await PrivateKeyWallet.Generate(this.Client); + var fakeAuthorizedSigner = await this.GetGuestAccount(); + var randomReceiver = await this.GetGuestAccount(); var mintRequest = new TokenERC20_MintRequest { To = await randomReceiver.GetAddress(), Quantity = BigInteger.Parse("1.5".ToWei()) }; (var payload, var signature) = await contract.TokenERC20_GenerateMintSignature(fakeAuthorizedSigner, mintRequest); @@ -1528,8 +1528,8 @@ public async Task TokenERC721_NullChecks() public async Task TokenERC721_GenerateMintSignature_WithUri_WithVerify() { var contract = await this.GetTokenERC721Contract(); - var fakeAuthorizedSigner = await PrivateKeyWallet.Generate(this.Client); - var randomReceiver = await PrivateKeyWallet.Generate(this.Client); + var fakeAuthorizedSigner = await this.GetGuestAccount(); + var randomReceiver = await this.GetGuestAccount(); var mintRequest = new TokenERC721_MintRequest { To = await randomReceiver.GetAddress(), Uri = "" }; (var payload, var signature) = await contract.TokenERC721_GenerateMintSignature(fakeAuthorizedSigner, mintRequest); @@ -1563,8 +1563,8 @@ public async Task TokenERC721_GenerateMintSignature_WithUri_WithVerify() public async Task TokenERC721_GenerateMintSignature_WithNFTMetadata_WithVerify() { var contract = await this.GetTokenERC721Contract(); - var fakeAuthorizedSigner = await PrivateKeyWallet.Generate(this.Client); - var randomReceiver = await PrivateKeyWallet.Generate(this.Client); + var fakeAuthorizedSigner = await this.GetGuestAccount(); + var randomReceiver = await this.GetGuestAccount(); var mintRequest = new TokenERC721_MintRequest { To = await randomReceiver.GetAddress() }; (var payload, var signature) = await contract.TokenERC721_GenerateMintSignature( @@ -1696,8 +1696,8 @@ public async Task TokenERC1155_NullChecks() public async Task TokenERC1155_GenerateMintSignature_WithUri_WithVerify() { var contract = await this.GetTokenERC1155Contract(); - var fakeAuthorizedSigner = await PrivateKeyWallet.Generate(this.Client); - var randomReceiver = await PrivateKeyWallet.Generate(this.Client); + var fakeAuthorizedSigner = await this.GetGuestAccount(); + var randomReceiver = await this.GetGuestAccount(); var mintRequest = new TokenERC1155_MintRequest { To = await randomReceiver.GetAddress(), Uri = "" }; (var payload, var signature) = await contract.TokenERC1155_GenerateMintSignature(fakeAuthorizedSigner, mintRequest); @@ -1733,8 +1733,8 @@ public async Task TokenERC1155_GenerateMintSignature_WithUri_WithVerify() public async Task TokenERC1155_GenerateMintSignature_WithNFTMetadata_WithVerify() { var contract = await this.GetTokenERC1155Contract(); - var fakeAuthorizedSigner = await PrivateKeyWallet.Generate(this.Client); - var randomReceiver = await PrivateKeyWallet.Generate(this.Client); + var fakeAuthorizedSigner = await this.GetGuestAccount(); + var randomReceiver = await this.GetGuestAccount(); var mintRequest = new TokenERC1155_MintRequest { To = await randomReceiver.GetAddress() }; (var payload, var signature) = await contract.TokenERC1155_GenerateMintSignature( diff --git a/Thirdweb.Tests/Thirdweb.Extensions/Thirdweb.MarketplaceExtensions.Tests.cs b/Thirdweb.Tests/Thirdweb.Extensions/Thirdweb.MarketplaceExtensions.Tests.cs deleted file mode 100644 index c13f62ab..00000000 --- a/Thirdweb.Tests/Thirdweb.Extensions/Thirdweb.MarketplaceExtensions.Tests.cs +++ /dev/null @@ -1,376 +0,0 @@ -using System.Numerics; - -namespace Thirdweb.Tests.Extensions; - -public class MarketplaceExtensionsTests : BaseTests -{ - private readonly string _marketplaceContractAddress = "0xb80E83b73571e63b3581b68f20bFC9E97965F329"; - private readonly string _drop1155ContractAddress = "0x37116cAe5e152C1A7345AAB0EC286Ff6E97c0605"; - - private readonly BigInteger _chainId = 421614; - - public MarketplaceExtensionsTests(ITestOutputHelper output) - : base(output) { } - - private async Task GetSmartWallet(int claimAmount) - { - var privateKeyWallet = await PrivateKeyWallet.Generate(this.Client); - var smartWallet = await SmartWallet.Create(personalWallet: privateKeyWallet, chainId: 421614); - - if (claimAmount > 0) - { - var drop1155Contract = await ThirdwebContract.Create(this.Client, this._drop1155ContractAddress, this._chainId); - var tokenId = 0; - _ = await drop1155Contract.DropERC1155_Claim(smartWallet, await smartWallet.GetAddress(), tokenId, claimAmount); - } - - return smartWallet; - } - - private async Task GetMarketplaceContract() - { - return await ThirdwebContract.Create(this.Client, this._marketplaceContractAddress, this._chainId); - } - - #region IDirectListings - - [Fact(Timeout = 120000)] - public async Task Marketplace_DirectListings_CreateListing_Success() - { - var contract = await this.GetMarketplaceContract(); - var wallet = await this.GetSmartWallet(1); - - var listingParams = new ListingParameters() - { - AssetContract = this._drop1155ContractAddress, - TokenId = 0, - Quantity = 1, - Currency = Constants.NATIVE_TOKEN_ADDRESS, - PricePerToken = 1, - StartTimestamp = Utils.GetUnixTimeStampNow(), - EndTimestamp = Utils.GetUnixTimeStampNow() + 3600, - Reserved = false, - }; - - var receipt = await contract.Marketplace_DirectListings_CreateListing(wallet, listingParams, true); - - Assert.NotNull(receipt); - Assert.True(receipt.TransactionHash.Length == 66); - - var listingId = await contract.Marketplace_DirectListings_TotalListings() - 1; - var listing = await contract.Marketplace_DirectListings_GetListing(listingId); - - Assert.NotNull(listing); - Assert.Equal(listing.ListingId, listingId); - Assert.Equal(listing.TokenId, listingParams.TokenId); - Assert.Equal(listing.Quantity, listingParams.Quantity); - Assert.Equal(listing.PricePerToken, listingParams.PricePerToken); - Assert.True(listing.StartTimestamp >= listingParams.StartTimestamp); - Assert.True(listing.EndTimestamp >= listingParams.EndTimestamp); - Assert.Equal(listing.ListingCreator, await wallet.GetAddress()); - Assert.Equal(listing.AssetContract, listingParams.AssetContract); - Assert.Equal(listing.Currency, listingParams.Currency); - Assert.Equal(TokenType.ERC1155, listing.TokenTypeEnum); - Assert.Equal(Status.CREATED, listing.StatusEnum); - Assert.Equal(listing.Reserved, listingParams.Reserved); - } - - [Fact(Timeout = 120000)] - public async Task Marketplace_DirectListings_UpdateListing_Success() - { - var contract = await this.GetMarketplaceContract(); - var wallet = await this.GetSmartWallet(1); - - var originalTotal = await contract.Marketplace_DirectListings_TotalListings(); - - var originalListing = new ListingParameters() - { - AssetContract = this._drop1155ContractAddress, - TokenId = 0, - Quantity = 1, - Currency = Constants.NATIVE_TOKEN_ADDRESS, - PricePerToken = 1, - StartTimestamp = Utils.GetUnixTimeStampNow() + 1800, - EndTimestamp = Utils.GetUnixTimeStampNow() + 3600, - Reserved = false, - }; - - var receipt = await contract.Marketplace_DirectListings_CreateListing(wallet, originalListing, true); - Assert.NotNull(receipt); - - var listingId = await contract.Marketplace_DirectListings_TotalListings() - 1; - Assert.True(listingId == originalTotal); - - var updatedListingParams = originalListing; - updatedListingParams.PricePerToken = 2; - - var updatedReceipt = await contract.Marketplace_DirectListings_UpdateListing(wallet, listingId, updatedListingParams); - Assert.NotNull(updatedReceipt); - Assert.True(updatedReceipt.TransactionHash.Length == 66); - - var listing = await contract.Marketplace_DirectListings_GetListing(listingId); - Assert.NotNull(listing); - Assert.Equal(listing.PricePerToken, 2); - } - - [Fact(Timeout = 120000)] - public async Task Marketplace_DirectListings_CancelListing_Success() - { - var contract = await this.GetMarketplaceContract(); - var wallet = await this.GetSmartWallet(1); - - var originalTotal = await contract.Marketplace_DirectListings_TotalListings(); - - var originalListing = new ListingParameters() - { - AssetContract = this._drop1155ContractAddress, - TokenId = 0, - Quantity = 1, - Currency = Constants.NATIVE_TOKEN_ADDRESS, - PricePerToken = 1, - StartTimestamp = Utils.GetUnixTimeStampNow() + 1800, - EndTimestamp = Utils.GetUnixTimeStampNow() + 3600, - Reserved = false, - }; - - var receipt = await contract.Marketplace_DirectListings_CreateListing(wallet, originalListing, true); - Assert.NotNull(receipt); - - var listingId = await contract.Marketplace_DirectListings_TotalListings() - 1; - Assert.True(listingId == originalTotal); - - var removeReceipt = await contract.Marketplace_DirectListings_CancelListing(wallet, listingId); - Assert.NotNull(removeReceipt); - Assert.True(removeReceipt.TransactionHash.Length == 66); - } - - [Fact(Timeout = 120000)] - public async Task Marketplace_DirectListings_ApproveBuyerForListing() - { - var contract = await this.GetMarketplaceContract(); - var wallet = await this.GetSmartWallet(1); - - var reservedListing = new ListingParameters() - { - AssetContract = this._drop1155ContractAddress, - TokenId = 0, - Quantity = 1, - Currency = Constants.NATIVE_TOKEN_ADDRESS, - PricePerToken = 1, - StartTimestamp = Utils.GetUnixTimeStampNow(), - EndTimestamp = Utils.GetUnixTimeStampNow() + 3600, - Reserved = true, - }; - - var receipt = await contract.Marketplace_DirectListings_CreateListing(wallet, reservedListing, true); - Assert.NotNull(receipt); - Assert.True(receipt.TransactionHash.Length == 66); - - var listingId = await contract.Marketplace_DirectListings_TotalListings() - 1; - - var buyer = await PrivateKeyWallet.Generate(this.Client); - var approveReceipt = await contract.Marketplace_DirectListings_ApproveBuyerForListing(wallet, listingId, await buyer.GetAddress(), true); - Assert.NotNull(approveReceipt); - Assert.True(approveReceipt.TransactionHash.Length == 66); - - var isApproved = await contract.Marketplace_DirectListings_IsBuyerApprovedForListing(listingId, await buyer.GetAddress()); - Assert.True(isApproved); - } - - [Fact(Timeout = 120000)] - public async Task Marketplace_DirectListings_TotalListings_Success() - { - var contract = await this.GetMarketplaceContract(); - var totalListings = await contract.Marketplace_DirectListings_TotalListings(); - Assert.True(totalListings >= 0); - } - - [Fact(Timeout = 120000)] - public async Task Marketplace_DirectListings_GetAllListings_Success() - { - var contract = await this.GetMarketplaceContract(); - var startId = BigInteger.Zero; - var endId = 10; - - var listings = await contract.Marketplace_DirectListings_GetAllListings(startId, endId); - Assert.NotNull(listings); - Assert.True(listings.Count >= 0); - } - - [Fact(Timeout = 120000)] - public async Task Marketplace_DirectListings_GetAllValidListings_Success() - { - var contract = await this.GetMarketplaceContract(); - var startId = BigInteger.Zero; - var endId = 10; - - var listings = await contract.Marketplace_DirectListings_GetAllValidListings(startId, endId); - Assert.NotNull(listings); - Assert.True(listings.Count >= 0); - } - - [Fact(Timeout = 120000)] - public async Task Marketplace_DirectListings_GetListing_Success() - { - var contract = await this.GetMarketplaceContract(); - var listingId = BigInteger.One; - - var listing = await contract.Marketplace_DirectListings_GetListing(listingId); - Assert.NotNull(listing); - } - - #endregion - - #region IEnglishAuctions - - [Fact(Timeout = 120000)] - public async Task Marketplace_EnglishAuctions_CreateAuction_Success() - { - var contract = await this.GetMarketplaceContract(); - var wallet = await this.GetSmartWallet(1); - - var auctionParams = new AuctionParameters() - { - AssetContract = this._drop1155ContractAddress, - TokenId = 0, - Quantity = 1, - Currency = Constants.NATIVE_TOKEN_ADDRESS, - MinimumBidAmount = 1, - BuyoutBidAmount = BigInteger.Parse("1".ToWei()), - TimeBufferInSeconds = 3600, - BidBufferBps = 100, - StartTimestamp = Utils.GetUnixTimeStampNow() - 3000, - EndTimestamp = Utils.GetUnixTimeStampNow() + (3600 * 24 * 7), - }; - - var receipt = await contract.Marketplace_EnglishAuctions_CreateAuction(wallet, auctionParams, true); - Assert.NotNull(receipt); - Assert.True(receipt.TransactionHash.Length == 66); - - var auctionId = await contract.Marketplace_EnglishAuctions_TotalAuctions() - 1; - var auction = await contract.Marketplace_EnglishAuctions_GetAuction(auctionId); - Assert.NotNull(auction); - Assert.Equal(auction.AuctionId, auctionId); - Assert.Equal(auction.TokenId, auctionParams.TokenId); - Assert.Equal(auction.Quantity, auctionParams.Quantity); - Assert.Equal(auction.MinimumBidAmount, auctionParams.MinimumBidAmount); - Assert.Equal(auction.BuyoutBidAmount, auctionParams.BuyoutBidAmount); - Assert.True(auction.TimeBufferInSeconds >= auctionParams.TimeBufferInSeconds); - Assert.True(auction.BidBufferBps >= auctionParams.BidBufferBps); - Assert.True(auction.StartTimestamp >= auctionParams.StartTimestamp); - Assert.True(auction.EndTimestamp >= auctionParams.EndTimestamp); - Assert.Equal(auction.AuctionCreator, await wallet.GetAddress()); - Assert.Equal(auction.AssetContract, auctionParams.AssetContract); - Assert.Equal(auction.Currency, auctionParams.Currency); - Assert.Equal(TokenType.ERC1155, auction.TokenTypeEnum); - Assert.Equal(Status.CREATED, auction.StatusEnum); - } - - [Fact(Timeout = 120000)] - public async Task Marketplace_EnglishAuctions_GetAuction_Success() - { - var contract = await this.GetMarketplaceContract(); - var auctionId = BigInteger.One; - - var auction = await contract.Marketplace_EnglishAuctions_GetAuction(auctionId); - Assert.NotNull(auction); - } - - [Fact(Timeout = 120000)] - public async Task Marketplace_EnglishAuctions_GetAllAuctions_Success() - { - var contract = await this.GetMarketplaceContract(); - var startId = BigInteger.Zero; - var endId = BigInteger.Zero; - - var auctions = await contract.Marketplace_EnglishAuctions_GetAllAuctions(startId, endId); - Assert.NotNull(auctions); - } - - [Fact(Timeout = 120000)] - public async Task Marketplace_EnglishAuctions_GetAllValidAuctions_Success() - { - var contract = await this.GetMarketplaceContract(); - var startId = BigInteger.Zero; - var endId = BigInteger.Zero; - - var auctions = await contract.Marketplace_EnglishAuctions_GetAllValidAuctions(startId, endId); - Assert.NotNull(auctions); - Assert.True(auctions.Count >= 0); - } - - #endregion - - #region IOffers - - // [Fact(Timeout = 120000)] - // public async Task Marketplace_Offers_MakeOffer_Success() - // { - // var contract = await this.GetMarketplaceContract(); - // var wallet = await this.GetSmartWallet(0); - - // var offerParams = new OfferParams() - // { - // AssetContract = this._drop1155ContractAddress, - // TokenId = 0, - // Quantity = 1, - // Currency = ERC20_HERE, - // TotalPrice = 0, - // ExpirationTimestamp = Utils.GetUnixTimeStampNow() + (3600 * 24), - // }; - - // var receipt = await contract.Marketplace_Offers_MakeOffer(wallet, offerParams, true); - // Assert.NotNull(receipt); - // Assert.True(receipt.TransactionHash.Length == 66); - - // var offerId = await contract.Marketplace_Offers_TotalOffers() - 1; - // var offer = await contract.Marketplace_Offers_GetOffer(offerId); - // Assert.NotNull(offer); - // Assert.Equal(offer.OfferId, offerId); - // Assert.Equal(offer.TokenId, offerParams.TokenId); - // Assert.Equal(offer.Quantity, offerParams.Quantity); - // Assert.Equal(offer.TotalPrice, offerParams.TotalPrice); - // Assert.True(offer.ExpirationTimestamp >= offerParams.ExpirationTimestamp); - // Assert.Equal(offer.Offeror, await wallet.GetAddress()); - // Assert.Equal(offer.AssetContract, offerParams.AssetContract); - // Assert.Equal(offer.Currency, offerParams.Currency); - // Assert.Equal(TokenType.ERC1155, offer.TokenTypeEnum); - // Assert.Equal(Status.CREATED, offer.StatusEnum); - // } - - // [Fact(Timeout = 120000)] - // public async Task Marketplace_Offers_GetOffer_Success() - // { - // var contract = await this.GetMarketplaceContract(); - // var offerId = BigInteger.One; - - // var offer = await contract.Marketplace_Offers_GetOffer(offerId); - // Assert.NotNull(offer); - // } - - // [Fact(Timeout = 120000)] - // public async Task Marketplace_Offers_GetAllOffers_Success() - // { - // var contract = await this.GetMarketplaceContract(); - // var startId = BigInteger.Zero; - // var endId = 10; - - // var offers = await contract.Marketplace_Offers_GetAllOffers(startId, endId); - // Assert.NotNull(offers); - // Assert.True(offers.Count >= 0); - // } - - // [Fact(Timeout = 120000)] - // public async Task Marketplace_Offers_GetAllValidOffers_Success() - // { - // var contract = await this.GetMarketplaceContract(); - // var startId = BigInteger.Zero; - // var endId = 10; - - // var offers = await contract.Marketplace_Offers_GetAllValidOffers(startId, endId); - // Assert.NotNull(offers); - // Assert.True(offers.Count >= 0); - // } - - #endregion -} diff --git a/Thirdweb.Tests/Thirdweb.Transactions/Thirdweb.Transactions.Tests.cs b/Thirdweb.Tests/Thirdweb.Transactions/Thirdweb.Transactions.Tests.cs index 3d3bce7a..a84321cd 100644 --- a/Thirdweb.Tests/Thirdweb.Transactions/Thirdweb.Transactions.Tests.cs +++ b/Thirdweb.Tests/Thirdweb.Transactions/Thirdweb.Transactions.Tests.cs @@ -1,5 +1,4 @@ using System.Numerics; -using Nethereum.Hex.HexTypes; namespace Thirdweb.Tests.Transactions; @@ -10,7 +9,7 @@ public TransactionTests(ITestOutputHelper output) private async Task CreateSampleTransaction() { - var wallet = await PrivateKeyWallet.Generate(this.Client); + var wallet = await this.GetGuestAccount(); var transaction = await ThirdwebTransaction.Create(wallet, new ThirdwebTransactionInput(421614) { To = await wallet.GetAddress() }); return transaction; } @@ -48,8 +47,7 @@ public void ConstructorArgs_TransactionInput() [Fact(Timeout = 120000)] public async Task Create_ValidatesInputParameters() { - var client = this.Client; - var wallet = await PrivateKeyWallet.Generate(client); + var wallet = await this.GetGuestAccount(); var txInput = new ThirdwebTransactionInput(421614) { To = Constants.ADDRESS_ZERO }; var transaction = await ThirdwebTransaction.Create(wallet, txInput); Assert.NotNull(transaction); @@ -59,7 +57,7 @@ public async Task Create_ValidatesInputParameters() public async Task Create_ThrowsOnNoTo() { var client = this.Client; - var wallet = await PrivateKeyWallet.Generate(client); + var wallet = await this.GetGuestAccount(); var txInput = new ThirdwebTransactionInput(421614) { }; var ex = await Assert.ThrowsAsync(() => ThirdwebTransaction.Create(wallet, txInput)); Assert.Contains("Transaction recipient (to) must be provided", ex.Message); @@ -69,7 +67,7 @@ public async Task Create_ThrowsOnNoTo() public async Task Create_ThrowsOnNoWallet() { var client = this.Client; - var wallet = await PrivateKeyWallet.Generate(client); + var wallet = await this.GetGuestAccount(); var txInput = new ThirdwebTransactionInput(421614) { To = Constants.ADDRESS_ZERO }; var ex = await Assert.ThrowsAsync(() => ThirdwebTransaction.Create(null, txInput)); Assert.Contains("Wallet must be provided", ex.Message); @@ -79,7 +77,7 @@ public async Task Create_ThrowsOnNoWallet() public async Task Create_ThrowsOnChainIdZero() { var client = this.Client; - var wallet = await PrivateKeyWallet.Generate(client); + var wallet = await this.GetGuestAccount(); var ex = Assert.Throws(() => new ThirdwebTransactionInput(0) { To = Constants.ADDRESS_ZERO }); Assert.Contains("Invalid Chain ID", ex.Message); } @@ -106,7 +104,7 @@ public async Task SetValue_SetsValue() var transaction = await this.CreateSampleTransaction(); var value = new BigInteger(1000); _ = transaction.SetValue(value); - Assert.Equal(value.ToHexBigInteger(), transaction.Input.Value); + Assert.Equal(value, transaction.Input.Value.Value); } [Fact(Timeout = 120000)] @@ -124,7 +122,7 @@ public async Task SetGasPrice_SetsGasPrice() var transaction = await this.CreateSampleTransaction(); var gas = new BigInteger(1000); _ = transaction.SetGasPrice(gas); - Assert.Equal(gas.ToHexBigInteger(), transaction.Input.GasPrice); + Assert.Equal(gas, transaction.Input.GasPrice.Value); } [Fact(Timeout = 120000)] @@ -133,7 +131,7 @@ public async Task SetMaxFeePerGas_SetsMaxFeePerGas() var transaction = await this.CreateSampleTransaction(); var gas = new BigInteger(1000); _ = transaction.SetMaxFeePerGas(gas); - Assert.Equal(gas.ToHexBigInteger(), transaction.Input.MaxFeePerGas); + Assert.Equal(gas, transaction.Input.MaxFeePerGas.Value); } [Fact(Timeout = 120000)] @@ -142,7 +140,7 @@ public async Task SetMaxPriorityFeePerGas_SetsMaxPriorityFeePerGas() var transaction = await this.CreateSampleTransaction(); var gas = new BigInteger(1000); _ = transaction.SetMaxPriorityFeePerGas(gas); - Assert.Equal(gas.ToHexBigInteger(), transaction.Input.MaxPriorityFeePerGas); + Assert.Equal(gas, transaction.Input.MaxPriorityFeePerGas.Value); } [Fact(Timeout = 120000)] @@ -161,8 +159,7 @@ public async Task SetAllGasParams_ThrowsInvalid() [Fact(Timeout = 120000)] public async Task Sign_SmartWallet_SignsTransaction() { - var client = this.Client; - var privateKeyAccount = await PrivateKeyWallet.Generate(client); + var privateKeyAccount = await this.GetGuestAccount(); var smartAccount = await SmartWallet.Create(personalWallet: privateKeyAccount, factoryAddress: "0xbf1C9aA4B1A085f7DA890a44E82B0A1289A40052", gasless: true, chainId: 421614); var transaction = await ThirdwebTransaction.Create(smartAccount, new ThirdwebTransactionInput(421614) { To = Constants.ADDRESS_ZERO }); var signed = await ThirdwebTransaction.Sign(transaction); @@ -329,7 +326,7 @@ public async Task EstimateTotalCosts_HigherThanGasCostsByValue() [Fact(Timeout = 120000)] public async Task EstimateGasFees_ReturnsCorrectly() { - var transaction = await ThirdwebTransaction.Create(await PrivateKeyWallet.Generate(this.Client), new ThirdwebTransactionInput(250) { To = Constants.ADDRESS_ZERO }); + var transaction = await ThirdwebTransaction.Create(await this.GetGuestAccount(), new ThirdwebTransactionInput(250) { To = Constants.ADDRESS_ZERO }); (var maxFee, var maxPrio) = await ThirdwebTransaction.EstimateGasFees(transaction); @@ -362,10 +359,9 @@ public async Task Simulate_ThrowsInsufficientFunds() [Fact(Timeout = 120000)] public async Task Simulate_ReturnsDataOrThrowsIntrinsic() { - var client = this.Client; - var privateKeyAccount = await PrivateKeyWallet.Generate(client); + var privateKeyAccount = await this.GetGuestAccount(); var smartAccount = await SmartWallet.Create(personalWallet: privateKeyAccount, factoryAddress: "0xbf1C9aA4B1A085f7DA890a44E82B0A1289A40052", gasless: true, chainId: 421614); - var transaction = await ThirdwebTransaction.Create(smartAccount, new ThirdwebTransactionInput(421614) { To = Constants.ADDRESS_ZERO, Gas = new HexBigInteger(250000) }); + var transaction = await ThirdwebTransaction.Create(smartAccount, new ThirdwebTransactionInput(chainId: 421614, to: Constants.ADDRESS_ZERO, gas: 250000)); try { @@ -386,7 +382,6 @@ public async Task WaitForTransactionReceipt() var normalTxHash = "0x5a0b6cdb01ecfb25b368d3de1ac844414980ee3c330ec8c1435117b75027b5d7"; var failedTxHash = "0xd2840219ffe172377c8a455c13d95e4dca204d5c0dd72232093e092eef412488"; var aaTxHash = "0xbf76bd85e1759cf5cf9f4c7c52e76a74d32687f0b516017ff28192d04df50782"; - var aaSilentRevertTxHash = "0x8ada86c63846da7a3f91b8c8332de03f134e7619886425df858ee5400a9d9958"; var normalReceipt = await ThirdwebTransaction.WaitForTransactionReceipt(client, chainId, normalTxHash); Assert.NotNull(normalReceipt); @@ -396,19 +391,6 @@ public async Task WaitForTransactionReceipt() var aaReceipt = await ThirdwebTransaction.WaitForTransactionReceipt(client, chainId, aaTxHash); Assert.NotNull(aaReceipt); - - var aaFailedReceipt = await Assert.ThrowsAsync(async () => await ThirdwebTransaction.WaitForTransactionReceipt(client, chainId, aaSilentRevertTxHash)); - Assert.StartsWith($"Transaction {aaSilentRevertTxHash} execution silently reverted", aaFailedReceipt.Message); - } - - [Fact(Timeout = 120000)] - public async Task WaitForTransactionReceipt_AAReasonString() - { - var client = this.Client; - var chainId = 84532; - var aaSilentRevertTxHashWithReason = "0x5374743bbb749df47a279ac21e6ed472c30cd471923a7bc78db6a40e1b6924de"; - var aaFailedReceiptWithReason = await Assert.ThrowsAsync(async () => await ThirdwebTransaction.WaitForTransactionReceipt(client, chainId, aaSilentRevertTxHashWithReason)); - Assert.StartsWith($"Transaction {aaSilentRevertTxHashWithReason} execution silently reverted:", aaFailedReceiptWithReason.Message); } [Fact(Timeout = 120000)] @@ -419,7 +401,6 @@ public async Task WaitForTransactionReceipt_CancellationToken() var normalTxHash = "0x5a0b6cdb01ecfb25b368d3de1ac844414980ee3c330ec8c1435117b75027b5d7"; var failedTxHash = "0xd2840219ffe172377c8a455c13d95e4dca204d5c0dd72232093e092eef412488"; var aaTxHash = "0xbf76bd85e1759cf5cf9f4c7c52e76a74d32687f0b516017ff28192d04df50782"; - var aaSilentRevertTxHash = "0x8ada86c63846da7a3f91b8c8332de03f134e7619886425df858ee5400a9d9958"; var cts = new CancellationTokenSource(); cts.CancelAfter(10000); @@ -438,8 +419,6 @@ public async Task WaitForTransactionReceipt_CancellationToken() cts = new CancellationTokenSource(); cts.CancelAfter(10000); - var aaFailedReceipt = await Assert.ThrowsAsync(async () => await ThirdwebTransaction.WaitForTransactionReceipt(client, chainId, aaSilentRevertTxHash, cts.Token)); - Assert.StartsWith($"Transaction {aaSilentRevertTxHash} execution silently reverted", aaFailedReceipt.Message); var aaReceipt2 = await ThirdwebTransaction.WaitForTransactionReceipt(client, chainId, aaTxHash, CancellationToken.None); Assert.NotNull(aaReceipt2); diff --git a/Thirdweb.Tests/Thirdweb.Transactions/Thirdweb.ZkSmartWallet.Tests.cs b/Thirdweb.Tests/Thirdweb.Transactions/Thirdweb.ZkSmartWallet.Tests.cs index 5aad82db..09b9dba4 100644 --- a/Thirdweb.Tests/Thirdweb.Transactions/Thirdweb.ZkSmartWallet.Tests.cs +++ b/Thirdweb.Tests/Thirdweb.Transactions/Thirdweb.ZkSmartWallet.Tests.cs @@ -7,7 +7,7 @@ public ZkSmartWalletTests(ITestOutputHelper output) private async Task GetSmartAccount(int zkChainId = 300, bool gasless = true) { - var privateKeyAccount = await PrivateKeyWallet.Generate(this.Client); + var privateKeyAccount = await this.GetGuestAccount(); var smartAccount = await SmartWallet.Create(personalWallet: privateKeyAccount, gasless: gasless, chainId: zkChainId); return smartAccount; } diff --git a/Thirdweb.Tests/Thirdweb.Utils/Thirdweb.Utils.Tests.cs b/Thirdweb.Tests/Thirdweb.Utils/Thirdweb.Utils.Tests.cs index cf628fb5..3aad3125 100644 --- a/Thirdweb.Tests/Thirdweb.Utils/Thirdweb.Utils.Tests.cs +++ b/Thirdweb.Tests/Thirdweb.Utils/Thirdweb.Utils.Tests.cs @@ -502,7 +502,7 @@ public async Task FetchThirdwebChainDataAsync_ThrowsException_InvalidChainId() [Fact(Timeout = 120000)] public async void ToJsonExternalWalletFriendly_ReturnsCorrectValue4() { - var pkWallet = await PrivateKeyWallet.Generate(this.Client); // Assume external wallet + var pkWallet = await this.GetGuestAccount(); // Assume external wallet var msg = new AccountAbstraction.AccountMessage { Message = new byte[] { 0x01, 0x02, 0x03, 0x04 } }; var verifyingContract = await pkWallet.GetAddress(); // doesn't matter here var typedDataRaw = EIP712.GetTypedDefinition_SmartAccount_AccountMessage("Account", "1", 137, verifyingContract); @@ -844,32 +844,4 @@ public void PreprocessTypedDataJson_NestedLargeNumbers() Assert.Equal(expectedJObject, processedJObject); } - - [Fact] - public void DecodeTransaction_1559WithAuthList() - { - var signedTxStr = - "0x04f8ca830de9fb8082011882031083025bee94ff5d95e5aa1b5af3f106079518228a92818737728080c0f85ef85c830de9fb94654f42b74885ee6803f403f077bc0409f1066c588080a0a5caed9b0c46657a452250a3279f45937940c87c45854aead6a902d99bc638f39faa58026c6b018d36b8935a42f2bcf68097c712c9f09ca014c70887678e08a980a027ecc69e66eb9e28cbe6edab10fc827fcb6d2a34cdcb89d8b6aabc6e35608692a0750d306b04a50a35de57bd6aca11f207a8dd404f9d92502ce6e3817e52f79a1c"; - (var txInput, var signature) = Utils.DecodeTransaction(signedTxStr); - Assert.Equal("0xfF5D95e5aA1B5Af3F106079518228A9281873772", txInput.To); - Assert.Equal("0x", txInput.Data); - Assert.Equal(0, txInput.Value.Value); - Assert.NotNull(txInput.AuthorizationList); - _ = Assert.Single(txInput.AuthorizationList); - Assert.Equal("0x654F42b74885EE6803F403f077bc0409f1066c58", txInput.AuthorizationList[0].Address); - Assert.Equal("0xde9fb", txInput.AuthorizationList[0].ChainId); - Assert.Equal("0x0", txInput.AuthorizationList[0].Nonce); - - (txInput, var signature2) = Utils.DecodeTransaction(signedTxStr.HexToBytes()); - Assert.Equal("0xfF5D95e5aA1B5Af3F106079518228A9281873772", txInput.To); - Assert.Equal("0x", txInput.Data); - Assert.Equal(0, txInput.Value.Value); - Assert.NotNull(txInput.AuthorizationList); - _ = Assert.Single(txInput.AuthorizationList); - Assert.Equal("0x654F42b74885EE6803F403f077bc0409f1066c58", txInput.AuthorizationList[0].Address); - Assert.Equal("0xde9fb", txInput.AuthorizationList[0].ChainId); - Assert.Equal("0x0", txInput.AuthorizationList[0].Nonce); - - Assert.Equal(signature, signature2); - } } diff --git a/Thirdweb.Tests/Thirdweb.Wallets/Thirdweb.PrivateKeyWallet.Tests.cs b/Thirdweb.Tests/Thirdweb.Wallets/Thirdweb.PrivateKeyWallet.Tests.cs deleted file mode 100644 index fe33ed02..00000000 --- a/Thirdweb.Tests/Thirdweb.Wallets/Thirdweb.PrivateKeyWallet.Tests.cs +++ /dev/null @@ -1,506 +0,0 @@ -using Nethereum.Hex.HexTypes; - -namespace Thirdweb.Tests.Wallets; - -public class PrivateKeyWalletTests : BaseTests -{ - public PrivateKeyWalletTests(ITestOutputHelper output) - : base(output) { } - - private async Task GetAccount() - { - var privateKeyAccount = await PrivateKeyWallet.Generate(this.Client); - return privateKeyAccount; - } - - [Fact(Timeout = 120000)] - public async Task Initialization_Success() - { - var account = await this.GetAccount(); - Assert.NotNull(account); - } - - [Fact(Timeout = 120000)] - public async void Create_NullClient() - { - _ = await Assert.ThrowsAsync(() => PrivateKeyWallet.Create(null, "0x1234567890abcdef")); - } - - [Fact(Timeout = 120000)] - public async void Create_NullPrivateKey() - { - var client = this.Client; - var ex = await Assert.ThrowsAsync(async () => await PrivateKeyWallet.Create(client, null)); - Assert.Equal("Private key cannot be null or empty. (Parameter 'privateKeyHex')", ex.Message); - } - - [Fact(Timeout = 120000)] - public async void Create_EmptyPrivateKey() - { - var client = this.Client; - var ex = await Assert.ThrowsAsync(async () => await PrivateKeyWallet.Create(client, string.Empty)); - Assert.Equal("Private key cannot be null or empty. (Parameter 'privateKeyHex')", ex.Message); - } - - [Fact(Timeout = 120000)] - public async void Generate_NullClient() - { - _ = await Assert.ThrowsAsync(() => PrivateKeyWallet.Generate(null)); - } - - [Fact(Timeout = 120000)] - public async void LoadOrGenerate_NullClient() - { - _ = await Assert.ThrowsAsync(() => PrivateKeyWallet.LoadOrGenerate(null)); - } - - [Fact(Timeout = 120000)] - public async void SaveAndDelete_CheckPath() - { - var wallet = await PrivateKeyWallet.Generate(this.Client); - await wallet.Save(); - - var path = PrivateKeyWallet.GetSavePath(); - Assert.True(File.Exists(path)); - - PrivateKeyWallet.Delete(); - Assert.False(File.Exists(path)); - } - - [Fact(Timeout = 120000)] - public async Task Connect() - { - var account = await this.GetAccount(); - Assert.True(await account.IsConnected()); - } - - [Fact(Timeout = 120000)] - public async Task GetAddress() - { - var account = await this.GetAccount(); - var address = await account.GetAddress(); - Assert.True(address.Length == 42); - } - - [Fact(Timeout = 120000)] - public async Task EthSign_Success() - { - var account = await this.GetAccount(); - var message = "Hello, World!"; - var signature = await account.EthSign(message); - Assert.True(signature.Length == 132); - } - - [Fact(Timeout = 120000)] - public async Task EthSign_NullMessage() - { - var account = await this.GetAccount(); - var ex = await Assert.ThrowsAsync(() => account.EthSign(null as string)); - Assert.Equal("Message to sign cannot be null. (Parameter 'message')", ex.Message); - } - - [Fact(Timeout = 120000)] - public async Task EthSignRaw_Success() - { - var account = await this.GetAccount(); - var message = "Hello, World!"; - var signature = await account.EthSign(System.Text.Encoding.UTF8.GetBytes(message)); - Assert.True(signature.Length == 132); - } - - [Fact(Timeout = 120000)] - public async Task EthSignRaw_NullMessage() - { - var account = await this.GetAccount(); - var ex = await Assert.ThrowsAsync(() => account.EthSign(null as byte[])); - Assert.Equal("Message to sign cannot be null. (Parameter 'rawMessage')", ex.Message); - } - - [Fact(Timeout = 120000)] - public async Task PersonalSign_Success() - { - var account = await this.GetAccount(); - var message = "Hello, World!"; - var signature = await account.PersonalSign(message); - Assert.True(signature.Length == 132); - } - - [Fact(Timeout = 120000)] - public async Task PersonalSign_EmptyMessage() - { - var account = await this.GetAccount(); - var ex = await Assert.ThrowsAsync(() => account.PersonalSign(string.Empty)); - Assert.Equal("Message to sign cannot be null. (Parameter 'message')", ex.Message); - } - - [Fact(Timeout = 120000)] - public async Task PersonalSign_NullyMessage() - { - var account = await this.GetAccount(); - - var ex = await Assert.ThrowsAsync(() => account.PersonalSign(null as string)); - Assert.Equal("Message to sign cannot be null. (Parameter 'message')", ex.Message); - } - - [Fact(Timeout = 120000)] - public async Task PersonalSignRaw_Success() - { - var account = await this.GetAccount(); - var message = System.Text.Encoding.UTF8.GetBytes("Hello, World!"); - var signature = await account.PersonalSign(message); - Assert.True(signature.Length == 132); - } - - [Fact(Timeout = 120000)] - public async Task PersonalSignRaw_NullMessage() - { - var account = await this.GetAccount(); - var ex = await Assert.ThrowsAsync(() => account.PersonalSign(null as byte[])); - Assert.Equal("Message to sign cannot be null. (Parameter 'rawMessage')", ex.Message); - } - - [Fact(Timeout = 120000)] - public async Task SignTypedDataV4_Success() - { - var account = await this.GetAccount(); - var json = - /*lang=json,strict*/ - "{\"types\":{\"EIP712Domain\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"version\",\"type\":\"string\"},{\"name\":\"chainId\",\"type\":\"uint256\"},{\"name\":\"verifyingContract\",\"type\":\"address\"}],\"Person\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"wallet\",\"type\":\"address\"}],\"Mail\":[{\"name\":\"from\",\"type\":\"Person\"},{\"name\":\"to\",\"type\":\"Person\"},{\"name\":\"contents\",\"type\":\"string\"}]},\"primaryType\":\"Mail\",\"domain\":{\"name\":\"Ether Mail\",\"version\":\"1\",\"chainId\":1,\"verifyingContract\":\"0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC\"},\"message\":{\"from\":{\"name\":\"Cow\",\"wallet\":\"0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826\"},\"to\":{\"name\":\"Bob\",\"wallet\":\"0xbBbBBBBbbBBBbbbBbbBbbBBbBbbBbBbBbBbbBBbB\"},\"contents\":\"Hello, Bob!\"}}"; - var signature = await account.SignTypedDataV4(json); - Assert.True(signature.Length == 132); - } - - [Fact(Timeout = 120000)] - public async Task SignTypedDataV4_NullJson() - { - var account = await this.GetAccount(); - var ex = await Assert.ThrowsAsync(() => account.SignTypedDataV4(null)); - Assert.Equal("Json to sign cannot be null. (Parameter 'json')", ex.Message); - } - - [Fact(Timeout = 120000)] - public async Task SignTypedDataV4_EmptyJson() - { - var account = await this.GetAccount(); - var ex = await Assert.ThrowsAsync(() => account.SignTypedDataV4(string.Empty)); - Assert.Equal("Json to sign cannot be null. (Parameter 'json')", ex.Message); - } - - [Fact(Timeout = 120000)] - public async Task SignTypedDataV4_Typed() - { - var account = await this.GetAccount(); - var typedData = EIP712.GetTypedDefinition_SmartAccount_AccountMessage("Account", "1", 421614, await account.GetAddress()); - var accountMessage = new AccountAbstraction.AccountMessage { Message = System.Text.Encoding.UTF8.GetBytes("Hello, world!") }; - var signature = await account.SignTypedDataV4(accountMessage, typedData); - Assert.True(signature.Length == 132); - } - - [Fact(Timeout = 120000)] - public async Task SignTypedDataV4_Typed_NullData() - { - var account = await this.GetAccount(); - var typedData = EIP712.GetTypedDefinition_SmartAccount_AccountMessage("Account", "1", 421614, await account.GetAddress()); - var ex = await Assert.ThrowsAsync(() => account.SignTypedDataV4(null as string, typedData)); - Assert.Equal("Data to sign cannot be null. (Parameter 'data')", ex.Message); - } - - [Fact(Timeout = 120000)] - public async Task SignTransaction_Success() - { - var account = await this.GetAccount(); - var transaction = new ThirdwebTransactionInput( - chainId: 421614, - from: await account.GetAddress(), - to: Constants.ADDRESS_ZERO, - value: 0, - gas: 21000, - data: "0x", - nonce: 99999999999, - gasPrice: 10000000000 - ); - var signature = await account.SignTransaction(transaction); - Assert.NotNull(signature); - } - - [Fact(Timeout = 120000)] - public async Task SignTransaction_WithAuthorizationList_Success() - { - var account = await this.GetAccount(); - var authorization = await account.SignAuthorization(421614, Constants.ADDRESS_ZERO, false); - var transaction = new ThirdwebTransactionInput( - chainId: 421614, - from: await account.GetAddress(), - to: Constants.ADDRESS_ZERO, - value: 0, - gas: 21000, - data: "0x", - nonce: 99999999999, - gasPrice: 10000000000, - authorization: authorization - ); - var signature = await account.SignTransaction(transaction); - Assert.NotNull(signature); - } - - [Fact(Timeout = 120000)] - public async Task SignTransaction_NoFrom_Success() - { - var account = await this.GetAccount(); - var transaction = new ThirdwebTransactionInput(chainId: 421614, to: Constants.ADDRESS_ZERO, value: 0, gas: 21000, data: "0x", nonce: 99999999999, gasPrice: 10000000000); - var signature = await account.SignTransaction(transaction); - Assert.NotNull(signature); - } - - [Fact(Timeout = 120000)] - public async Task SignTransaction_NullTransaction() - { - var account = await this.GetAccount(); - var ex = await Assert.ThrowsAsync(() => account.SignTransaction(null)); - Assert.Equal("Value cannot be null. (Parameter 'transaction')", ex.Message); - } - - [Fact(Timeout = 120000)] - public async Task SignTransaction_NoNonce() - { - var account = await this.GetAccount(); - var transaction = new ThirdwebTransactionInput(421614) - { - From = await account.GetAddress(), - To = Constants.ADDRESS_ZERO, - Value = new HexBigInteger(0), - Gas = new HexBigInteger(21000), - Data = "0x", - }; - var ex = await Assert.ThrowsAsync(() => account.SignTransaction(transaction)); - Assert.Equal("Transaction nonce has not been set (Parameter 'transaction')", ex.Message); - } - - [Fact(Timeout = 120000)] - public async Task SignTransaction_NoGasPrice() - { - var account = await this.GetAccount(); - var transaction = new ThirdwebTransactionInput(421614) - { - From = await account.GetAddress(), - To = Constants.ADDRESS_ZERO, - Value = new HexBigInteger(0), - Gas = new HexBigInteger(21000), - Data = "0x", - Nonce = new HexBigInteger(99999999999), - ChainId = new HexBigInteger(421614), - }; - var ex = await Assert.ThrowsAsync(() => account.SignTransaction(transaction)); - Assert.Equal("Transaction MaxPriorityFeePerGas and MaxFeePerGas must be set for EIP-1559 transactions", ex.Message); - } - - [Fact(Timeout = 120000)] - public async Task SignTransaction_1559_Success() - { - var account = await this.GetAccount(); - var transaction = new ThirdwebTransactionInput(421614) - { - From = await account.GetAddress(), - To = Constants.ADDRESS_ZERO, - Value = new HexBigInteger(0), - Gas = new HexBigInteger(21000), - Data = "0x", - Nonce = new HexBigInteger(99999999999), - MaxFeePerGas = new HexBigInteger(10000000000), - MaxPriorityFeePerGas = new HexBigInteger(10000000000), - }; - var signature = await account.SignTransaction(transaction); - Assert.NotNull(signature); - } - - [Fact(Timeout = 120000)] - public async Task SignTransaction_1559_NoMaxFeePerGas() - { - var account = await this.GetAccount(); - var transaction = new ThirdwebTransactionInput(421614) - { - From = await account.GetAddress(), - To = Constants.ADDRESS_ZERO, - Value = new HexBigInteger(0), - Gas = new HexBigInteger(21000), - Data = "0x", - Nonce = new HexBigInteger(99999999999), - MaxPriorityFeePerGas = new HexBigInteger(10000000000), - }; - var ex = await Assert.ThrowsAsync(() => account.SignTransaction(transaction)); - Assert.Equal("Transaction MaxPriorityFeePerGas and MaxFeePerGas must be set for EIP-1559 transactions", ex.Message); - } - - [Fact(Timeout = 120000)] - public async Task SignTransaction_1559_NoMaxPriorityFeePerGas() - { - var account = await this.GetAccount(); - var transaction = new ThirdwebTransactionInput(421614) - { - From = await account.GetAddress(), - To = Constants.ADDRESS_ZERO, - Value = new HexBigInteger(0), - Gas = new HexBigInteger(21000), - Data = "0x", - Nonce = new HexBigInteger(99999999999), - MaxFeePerGas = new HexBigInteger(10000000000), - }; - var ex = await Assert.ThrowsAsync(() => account.SignTransaction(transaction)); - Assert.Equal("Transaction MaxPriorityFeePerGas and MaxFeePerGas must be set for EIP-1559 transactions", ex.Message); - } - - [Fact(Timeout = 120000)] - public async Task IsConnected_True() - { - var account = await this.GetAccount(); - Assert.True(await account.IsConnected()); - } - - [Fact(Timeout = 120000)] - public async Task IsConnected_False() - { - var account = await this.GetAccount(); - await account.Disconnect(); - Assert.False(await account.IsConnected()); - } - - [Fact(Timeout = 120000)] - public async Task Disconnect() - { - var account = await this.GetAccount(); - await account.Disconnect(); - Assert.False(await account.IsConnected()); - } - - [Fact(Timeout = 120000)] - public async Task Disconnect_NotConnected() - { - var account = await this.GetAccount(); - await account.Disconnect(); - Assert.False(await account.IsConnected()); - } - - [Fact(Timeout = 120000)] - public async Task Disconnect_Connected() - { - var account = await this.GetAccount(); - await account.Disconnect(); - Assert.False(await account.IsConnected()); - } - - [Fact(Timeout = 120000)] - public async Task SendTransaction_InvalidOperation() - { - var account = await this.GetAccount(); - var transaction = new ThirdwebTransactionInput(421614) - { - From = await account.GetAddress(), - To = Constants.ADDRESS_ZERO, - Value = new HexBigInteger(0), - Data = "0x", - }; - _ = await Assert.ThrowsAsync(() => account.SendTransaction(transaction)); - } - - [Fact(Timeout = 120000)] - public async Task ExecuteTransaction_InvalidOperation() - { - var account = await this.GetAccount(); - var transaction = new ThirdwebTransactionInput(421614) - { - From = await account.GetAddress(), - To = Constants.ADDRESS_ZERO, - Value = new HexBigInteger(0), - Data = "0x", - }; - _ = await Assert.ThrowsAsync(() => account.ExecuteTransaction(transaction)); - } - - [Fact(Timeout = 120000)] - public async Task LoadOrGenerate_LoadsExistingWallet() - { - // Generate and save a wallet to simulate an existing wallet file - var wallet = await PrivateKeyWallet.Generate(this.Client); - await wallet.Save(); - - var loadedWallet = await PrivateKeyWallet.LoadOrGenerate(this.Client); - - Assert.NotNull(loadedWallet); - Assert.Equal(await wallet.Export(), await loadedWallet.Export()); - Assert.Equal(await wallet.GetAddress(), await loadedWallet.GetAddress()); - - // Clean up - var path = PrivateKeyWallet.GetSavePath(); - if (File.Exists(path)) - { - File.Delete(path); - } - } - - [Fact(Timeout = 120000)] - public async Task LoadOrGenerate_GeneratesNewWalletIfNoExistingWallet() - { - var path = PrivateKeyWallet.GetSavePath(); - - if (File.Exists(path)) - { - File.Delete(path); - } - - var wallet = await PrivateKeyWallet.LoadOrGenerate(this.Client); - - Assert.NotNull(wallet); - Assert.NotNull(await wallet.Export()); - Assert.False(File.Exists(path)); - } - - [Fact(Timeout = 120000)] - public async Task Save_SavesPrivateKeyToFile() - { - var wallet = await PrivateKeyWallet.Generate(this.Client); - - await wallet.Save(); - - var path = PrivateKeyWallet.GetSavePath(); - Assert.True(File.Exists(path)); - - var savedPrivateKey = await File.ReadAllTextAsync(path); - Assert.Equal(await wallet.Export(), savedPrivateKey); - - // Clean up - File.Delete(path); - } - - [Fact(Timeout = 120000)] - public async Task Export_ReturnsPrivateKey() - { - var wallet = await PrivateKeyWallet.Generate(this.Client); - - var privateKey = await wallet.Export(); - - Assert.NotNull(privateKey); - Assert.Equal(privateKey, await wallet.Export()); - } - - [Fact(Timeout = 120000)] - public async Task SignAuthorization_SelfExecution() - { - var wallet = await PrivateKeyWallet.Generate(this.Client); - var chainId = 911867; - var targetAddress = "0x654F42b74885EE6803F403f077bc0409f1066c58"; - - var currentNonce = await wallet.GetTransactionCount(chainId); - - var authorization = await wallet.SignAuthorization(chainId: chainId, contractAddress: targetAddress, willSelfExecute: false); - - Assert.Equal(chainId.NumberToHex(), authorization.ChainId); - Assert.Equal(targetAddress, authorization.Address); - Assert.True(authorization.Nonce.HexToNumber() == currentNonce); - - authorization = await wallet.SignAuthorization(chainId: chainId, contractAddress: targetAddress, willSelfExecute: true); - - Assert.Equal(chainId.NumberToHex(), authorization.ChainId); - Assert.Equal(targetAddress, authorization.Address); - Assert.True(authorization.Nonce.HexToNumber() == currentNonce + 1); - } -} diff --git a/Thirdweb.Tests/Thirdweb.Wallets/Thirdweb.SmartWallet.Tests.cs b/Thirdweb.Tests/Thirdweb.Wallets/Thirdweb.SmartWallet.Tests.cs index ce299687..ca62cbc1 100644 --- a/Thirdweb.Tests/Thirdweb.Wallets/Thirdweb.SmartWallet.Tests.cs +++ b/Thirdweb.Tests/Thirdweb.Wallets/Thirdweb.SmartWallet.Tests.cs @@ -7,7 +7,7 @@ public SmartWalletTests(ITestOutputHelper output) private async Task GetSmartAccount() { - var privateKeyAccount = await PrivateKeyWallet.Generate(this.Client); + var privateKeyAccount = await this.GetGuestAccount(); var smartAccount = await SmartWallet.Create(personalWallet: privateKeyAccount, gasless: true, chainId: 421614); return smartAccount; } @@ -22,8 +22,8 @@ public async Task Initialization_Success() [Fact(Timeout = 120000)] public async Task Initialization_WithoutFactory_Success() { - var client = this.Client; - var privateKeyAccount = await PrivateKeyWallet.Generate(client); + _ = this.Client; + var privateKeyAccount = await this.GetGuestAccount(); var smartAccount = await SmartWallet.Create(personalWallet: privateKeyAccount, chainId: 421614); Assert.NotNull(await smartAccount.GetAddress()); } @@ -32,7 +32,7 @@ public async Task Initialization_WithoutFactory_Success() public async Task Initialization_Fail() { var client = this.Client; - var privateKeyAccount = await PrivateKeyWallet.Generate(client); + var privateKeyAccount = await this.GetGuestAccount(); await privateKeyAccount.Disconnect(); var ex = await Assert.ThrowsAsync(async () => await SmartWallet.Create(personalWallet: privateKeyAccount, factoryAddress: "0xbf1C9aA4B1A085f7DA890a44E82B0A1289A40052", gasless: true, chainId: 421614) @@ -43,8 +43,8 @@ await SmartWallet.Create(personalWallet: privateKeyAccount, factoryAddress: "0xb [Fact(Timeout = 120000)] public async Task ForceDeploy_Success() { - var client = this.Client; - var privateKeyAccount = await PrivateKeyWallet.Generate(client); + _ = this.Client; + var privateKeyAccount = await this.GetGuestAccount(); var smartAccount = await SmartWallet.Create(personalWallet: privateKeyAccount, factoryAddress: "0xbf1C9aA4B1A085f7DA890a44E82B0A1289A40052", gasless: true, chainId: 421614); await smartAccount.ForceDeploy(); Assert.True(await smartAccount.IsDeployed()); @@ -61,8 +61,8 @@ public async Task IsDeployed_True() [Fact(Timeout = 120000)] public async Task IsDeployed_False() { - var client = this.Client; - var privateKeyAccount = await PrivateKeyWallet.Generate(client); + _ = this.Client; + var privateKeyAccount = await this.GetGuestAccount(); var smartAccount = await SmartWallet.Create( personalWallet: privateKeyAccount, factoryAddress: "0xbf1C9aA4B1A085f7DA890a44E82B0A1289A40052", @@ -92,8 +92,8 @@ public async Task SendTransaction_Success() [Fact(Timeout = 120000)] public async Task SendTransaction_ClientBundleId_Success() { - var client = ThirdwebClient.Create(clientId: this.ClientIdBundleIdOnly, bundleId: this.BundleIdBundleIdOnly); - var privateKeyAccount = await PrivateKeyWallet.Generate(client); + _ = ThirdwebClient.Create(clientId: this.ClientIdBundleIdOnly, bundleId: this.BundleIdBundleIdOnly); + var privateKeyAccount = await this.GetGuestAccount(); var smartAccount = await SmartWallet.Create(personalWallet: privateKeyAccount, factoryAddress: "0xbf1C9aA4B1A085f7DA890a44E82B0A1289A40052", gasless: true, chainId: 421614); var tx = await smartAccount.SendTransaction(new ThirdwebTransactionInput(421614) { To = await smartAccount.GetAddress() }); Assert.NotNull(tx); @@ -121,14 +121,14 @@ public async Task GetPersonalAccount() var account = await this.GetSmartAccount(); var personalAccount = await account.GetPersonalWallet(); Assert.NotNull(personalAccount); - _ = Assert.IsType(personalAccount); + _ = Assert.IsType(personalAccount); } [Fact(Timeout = 120000)] public async Task GetAddress_WithOverride() { - var client = this.Client; - var privateKeyAccount = await PrivateKeyWallet.Generate(client); + _ = this.Client; + var privateKeyAccount = await this.GetGuestAccount(); var smartAccount = await SmartWallet.Create( personalWallet: privateKeyAccount, factoryAddress: "0xbf1C9aA4B1A085f7DA890a44E82B0A1289A40052", @@ -228,7 +228,7 @@ public async Task GetAllActiveSigners() var count = signers.Count; // add signer - var randomSigner = await (await PrivateKeyWallet.Generate(this.Client)).GetAddress(); + var randomSigner = await (await this.GetGuestAccount()).GetAddress(); _ = await account.CreateSessionKey( signerAddress: randomSigner, approvedTargets: new List() { Constants.ADDRESS_ZERO }, @@ -263,7 +263,7 @@ public async Task GetAllAdmins() var count = admins.Count; // add admin - var randomAdmin = await (await PrivateKeyWallet.Generate(this.Client)).GetAddress(); + var randomAdmin = await (await this.GetGuestAccount()).GetAddress(); _ = await account.AddAdmin(randomAdmin); admins = await account.GetAllAdmins(); @@ -282,7 +282,7 @@ public async Task GetAllAdmins() public async Task SendTransaction_07_Success() { var smartWallet07 = await SmartWallet.Create( - personalWallet: await PrivateKeyWallet.Generate(this.Client), + personalWallet: await this.GetGuestAccount(), chainId: 11155111, gasless: true, factoryAddress: "0xc5A43D081Dc10316EE640504Ea1cBc74666F3874", @@ -299,7 +299,7 @@ public async Task SendTransaction_07_Success() public async Task ExecuteTransaction_07_WhenAll_Success() { var smartWallet07 = await SmartWallet.Create( - personalWallet: await PrivateKeyWallet.Generate(this.Client), + personalWallet: await this.GetGuestAccount(), chainId: 11155111, gasless: true, factoryAddress: "0xc5A43D081Dc10316EE640504Ea1cBc74666F3874", @@ -319,7 +319,7 @@ public async Task ExecuteTransaction_07_WhenAll_Success() [Fact(Timeout = 120000)] public async Task SwitchNetwork_Success() { - var smartWallet = await SmartWallet.Create(personalWallet: await PrivateKeyWallet.Generate(this.Client), chainId: 11155111); + var smartWallet = await SmartWallet.Create(personalWallet: await this.GetGuestAccount(), chainId: 11155111); var addy1 = await smartWallet.GetAddress(); await smartWallet.SwitchNetwork(421614); var addy2 = await smartWallet.GetAddress(); @@ -329,7 +329,7 @@ public async Task SwitchNetwork_Success() [Fact(Timeout = 120000)] public async Task SwitchNetwork_WithCustomFactory_ToZk_Success() { - var smartWallet = await SmartWallet.Create(personalWallet: await PrivateKeyWallet.Generate(this.Client), chainId: 11155111, factoryAddress: "0xc5A43D081Dc10316EE640504Ea1cBc74666F3874"); + var smartWallet = await SmartWallet.Create(personalWallet: await this.GetGuestAccount(), chainId: 11155111, factoryAddress: "0xc5A43D081Dc10316EE640504Ea1cBc74666F3874"); var addy1 = await smartWallet.GetAddress(); await smartWallet.SwitchNetwork(300); var addy2 = await smartWallet.GetAddress(); @@ -339,7 +339,7 @@ public async Task SwitchNetwork_WithCustomFactory_ToZk_Success() [Fact(Timeout = 120000)] public async Task SwitchNetwork_WithCustomFactory_FromZk_Success() { - var smartWallet = await SmartWallet.Create(personalWallet: await PrivateKeyWallet.Generate(this.Client), chainId: 300, factoryAddress: "0xc5A43D081Dc10316EE640504Ea1cBc74666F3874"); + var smartWallet = await SmartWallet.Create(personalWallet: await this.GetGuestAccount(), chainId: 300, factoryAddress: "0xc5A43D081Dc10316EE640504Ea1cBc74666F3874"); var addy1 = await smartWallet.GetAddress(); await smartWallet.SwitchNetwork(11155111); var addy2 = await smartWallet.GetAddress(); @@ -349,7 +349,7 @@ public async Task SwitchNetwork_WithCustomFactory_FromZk_Success() [Fact(Timeout = 120000)] public async Task SwitchNetwork_ZkToNonZkSuccess() { - var smartWallet = await SmartWallet.Create(personalWallet: await PrivateKeyWallet.Generate(this.Client), chainId: 300); + var smartWallet = await SmartWallet.Create(personalWallet: await this.GetGuestAccount(), chainId: 300); var addy1 = await smartWallet.GetAddress(); await smartWallet.SwitchNetwork(421614); var addy2 = await smartWallet.GetAddress(); @@ -359,7 +359,7 @@ public async Task SwitchNetwork_ZkToNonZkSuccess() [Fact(Timeout = 120000)] public async Task SwitchNetwork_NonZkToZk_Success() { - var smartWallet = await SmartWallet.Create(personalWallet: await PrivateKeyWallet.Generate(this.Client), chainId: 421614); + var smartWallet = await SmartWallet.Create(personalWallet: await this.GetGuestAccount(), chainId: 421614); var addy1 = await smartWallet.GetAddress(); await smartWallet.SwitchNetwork(300); var addy2 = await smartWallet.GetAddress(); @@ -367,9 +367,9 @@ public async Task SwitchNetwork_NonZkToZk_Success() } [Fact(Timeout = 120000)] - public async Task SignAuthorization_WithPrivateKeyWallet_Success() + public async Task SignAuthorization_WithInAppWallet_Success() { - var smartWallet = await SmartWallet.Create(personalWallet: await PrivateKeyWallet.Generate(this.Client), chainId: 421614); + var smartWallet = await SmartWallet.Create(personalWallet: await this.GetGuestAccount(), chainId: 421614); var smartWalletSigner = await smartWallet.GetPersonalWallet(); var signature1 = await smartWallet.SignAuthorization(chainId: 421614, contractAddress: Constants.ADDRESS_ZERO, willSelfExecute: true); var signature2 = await smartWalletSigner.SignAuthorization(chainId: 421614, contractAddress: Constants.ADDRESS_ZERO, willSelfExecute: true); @@ -384,9 +384,9 @@ public async Task SignAuthorization_WithPrivateKeyWallet_Success() // var chainId1 = 11155111; // var chainId2 = 421614; - // var smartWallet = await SmartWallet.Create(personalWallet: await PrivateKeyWallet.Generate(this.Client), chainId: chainId1, gasless: true); + // var smartWallet = await SmartWallet.Create(personalWallet: await this.GetGuestAccount(), chainId: chainId1, gasless: true); - // var randomAddy = await (await PrivateKeyWallet.Generate(this.Client)).GetAddress(); + // var randomAddy = await (await this.GetGuestAccount()).GetAddress(); // var receipt1 = await smartWallet.ExecuteTransaction(new ThirdwebTransactionInput(chainId1) { To = randomAddy, }); // var nonce1 = await smartWallet.GetTransactionCount(chainId: chainId1, blocktag: "latest"); @@ -418,9 +418,9 @@ public async Task SignAuthorization_WithPrivateKeyWallet_Success() // var chainId1 = 300; // var chainId2 = 421614; - // var smartWallet = await SmartWallet.Create(personalWallet: await PrivateKeyWallet.Generate(this.Client), chainId: chainId1, gasless: true); + // var smartWallet = await SmartWallet.Create(personalWallet: await this.GetGuestAccount(), chainId: chainId1, gasless: true); - // var randomAddy = await (await PrivateKeyWallet.Generate(this.Client)).GetAddress(); + // var randomAddy = await (await this.GetGuestAccount()).GetAddress(); // var receipt1 = await smartWallet.ExecuteTransaction(new ThirdwebTransactionInput(chainId1) { To = randomAddy, }); // var nonce1 = await smartWallet.GetTransactionCount(chainId: chainId1, blocktag: "latest"); @@ -452,9 +452,9 @@ public async Task SignAuthorization_WithPrivateKeyWallet_Success() // var chainId1 = 421614; // var chainId2 = 300; - // var smartWallet = await SmartWallet.Create(personalWallet: await PrivateKeyWallet.Generate(this.Client), chainId: chainId1, gasless: true); + // var smartWallet = await SmartWallet.Create(personalWallet: await this.GetGuestAccount(), chainId: chainId1, gasless: true); - // var randomAddy = await (await PrivateKeyWallet.Generate(this.Client)).GetAddress(); + // var randomAddy = await (await this.GetGuestAccount()).GetAddress(); // var receipt1 = await smartWallet.ExecuteTransaction(new ThirdwebTransactionInput(chainId1) { To = randomAddy, }); // var nonce1 = await smartWallet.GetTransactionCount(chainId: chainId1, blocktag: "latest"); diff --git a/Thirdweb.Tests/Thirdweb.Wallets/Thirdweb.Wallets.Tests.cs b/Thirdweb.Tests/Thirdweb.Wallets/Thirdweb.Wallets.Tests.cs index cbe822a8..d318cdc1 100644 --- a/Thirdweb.Tests/Thirdweb.Wallets/Thirdweb.Wallets.Tests.cs +++ b/Thirdweb.Tests/Thirdweb.Wallets/Thirdweb.Wallets.Tests.cs @@ -1,24 +1,10 @@ -using Nethereum.Hex.HexTypes; - -namespace Thirdweb.Tests.Wallets; +namespace Thirdweb.Tests.Wallets; public class WalletTests : BaseTests { public WalletTests(ITestOutputHelper output) : base(output) { } - private async Task GetSmartAccount() - { - var privateKeyAccount = await PrivateKeyWallet.Generate(this.Client); - var smartAccount = await SmartWallet.Create(personalWallet: privateKeyAccount, chainId: 421614); - return smartAccount; - } - - private async Task GetPrivateKeyAccount() - { - return await PrivateKeyWallet.Generate(this.Client); - } - [Fact(Timeout = 120000)] public async Task GetAddress() { @@ -26,28 +12,10 @@ public async Task GetAddress() Assert.Equal(await wallet.GetAddress(), await wallet.GetAddress()); } - [Fact(Timeout = 120000)] - public async Task EthSignRaw() - { - var wallet = await this.GetPrivateKeyAccount(); - var message = "Hello, world!"; - var signature = await wallet.EthSign(System.Text.Encoding.UTF8.GetBytes(message)); - Assert.NotNull(signature); - } - - [Fact(Timeout = 120000)] - public async Task EthSign() - { - var wallet = await this.GetPrivateKeyAccount(); - var message = "Hello, world!"; - var signature = await wallet.EthSign(message); - Assert.NotNull(signature); - } - [Fact(Timeout = 120000)] public async Task PersonalSignRaw() { - var wallet = await this.GetPrivateKeyAccount(); + var wallet = await this.GetGuestAccount(); var message = "Hello, world!"; var signature = await wallet.PersonalSign(System.Text.Encoding.UTF8.GetBytes(message)); Assert.NotNull(signature); @@ -56,7 +24,7 @@ public async Task PersonalSignRaw() [Fact(Timeout = 120000)] public async Task PersonalSign() { - var wallet = await this.GetPrivateKeyAccount(); + var wallet = await this.GetGuestAccount(); var message = "Hello, world!"; var signature = await wallet.PersonalSign(message); Assert.NotNull(signature); @@ -117,120 +85,12 @@ await wallet.GetAddress(), public async Task SignTransaction() { var wallet = await this.GetSmartAccount(); - var transaction = new ThirdwebTransactionInput(421614) - { - To = await wallet.GetAddress(), - Data = "0x", - Value = new HexBigInteger(0), - Gas = new HexBigInteger(21000), - GasPrice = new HexBigInteger(10000000000), - Nonce = new HexBigInteger(9999999999999), - }; + var transaction = new ThirdwebTransactionInput(chainId: 421614, to: await wallet.GetAddress(), data: "0x", value: 0, gas: 21000, gasPrice: 10000000000, nonce: 9999999999999); _ = ThirdwebRPC.GetRpcInstance(this.Client, 421614); var signature = await wallet.SignTransaction(transaction); Assert.NotNull(signature); } - [Fact(Timeout = 120000)] - public async Task RecoverAddressFromEthSign_ReturnsSameAddress() - { - var wallet = await PrivateKeyWallet.Generate(this.Client); - var message = "Hello, world!"; - var signature = await wallet.EthSign(message); - var recoveredAddress = await wallet.RecoverAddressFromEthSign(message, signature); - Assert.Equal(await wallet.GetAddress(), recoveredAddress); - } - - [Fact(Timeout = 120000)] - public async Task RecoverAddressFromPersonalSign_ReturnsSameAddress() - { - var wallet = await PrivateKeyWallet.Generate(this.Client); - var message = "Hello, world!"; - var signature = await wallet.PersonalSign(message); - var recoveredAddress = await wallet.RecoverAddressFromPersonalSign(message, signature); - Assert.Equal(await wallet.GetAddress(), recoveredAddress); - } - - [Fact(Timeout = 120000)] - public async Task RecoverAddressFromPersonalSign_ReturnsSameAddress_SmartWallet() - { - var wallet = await this.GetSmartAccount(); - var message = "Hello, world!"; - var signature = await wallet.PersonalSign(message); - var recoveredAddress = await wallet.RecoverAddressFromPersonalSign(message, signature); - Assert.Equal(await wallet.GetAddress(), recoveredAddress); - } - - [Fact(Timeout = 120000)] - public async Task RecoverAddressFromSignTypedDataV4_ReturnsSameAddress() - { - var wallet = await PrivateKeyWallet.Generate(this.Client); - var typedData = EIP712.GetTypedDefinition_SmartAccount_AccountMessage("Account", "1", 421614, await wallet.GetAddress()); - var accountMessage = new AccountAbstraction.AccountMessage { Message = System.Text.Encoding.UTF8.GetBytes("Hello, world!").HashPrefixedMessage() }; - var signature = await wallet.SignTypedDataV4(accountMessage, typedData); - var recoveredAddress = await wallet.RecoverAddressFromTypedDataV4(accountMessage, typedData, signature); - Assert.Equal(await wallet.GetAddress(), recoveredAddress); - } - - [Fact(Timeout = 120000)] - public async Task RecoverAddressFromEthSign_InvalidSignature() - { - var wallet = await PrivateKeyWallet.Generate(this.Client); - var wallet2 = await PrivateKeyWallet.Generate(this.Client); - var message = "Hello, world!"; - var signature = await wallet2.EthSign(message); - var recoveredAddress = await wallet.RecoverAddressFromEthSign(message, signature); - Assert.NotEqual(await wallet.GetAddress(), recoveredAddress); - } - - [Fact(Timeout = 120000)] - public async Task RecoverAddressFromPersonalSign_InvalidSignature() - { - var wallet = await PrivateKeyWallet.Generate(this.Client); - var wallet2 = await PrivateKeyWallet.Generate(this.Client); - var message = "Hello, world!"; - var signature = await wallet2.PersonalSign(message); - var recoveredAddress = await wallet.RecoverAddressFromPersonalSign(message, signature); - Assert.NotEqual(await wallet.GetAddress(), recoveredAddress); - } - - [Fact(Timeout = 120000)] - public async Task RecoverAddressFromPersonalSign_InvalidSignature_SmartWallet() - { - var wallet = await this.GetSmartAccount(); - var wallet2 = await this.GetSmartAccount(); - var message = "Hello, world!"; - var signature = await wallet2.PersonalSign(message); - var recoveredAddress = await wallet.RecoverAddressFromPersonalSign(message, signature); - Assert.NotEqual(await wallet.GetAddress(), recoveredAddress); - } - - [Fact(Timeout = 120000)] - public async Task RecoverAddress_AllVariants_NullTests() - { - var wallet = await PrivateKeyWallet.Generate(this.Client); - var message = "Hello, world!"; - var signature = await wallet.PersonalSign(message); - - _ = await Assert.ThrowsAsync(async () => await wallet.RecoverAddressFromEthSign(null, signature)); - _ = await Assert.ThrowsAsync(async () => await wallet.RecoverAddressFromEthSign(message, null)); - _ = await Assert.ThrowsAsync(async () => await wallet.RecoverAddressFromPersonalSign(null, signature)); - _ = await Assert.ThrowsAsync(async () => await wallet.RecoverAddressFromPersonalSign(message, null)); - -#nullable disable - var nullData = null as AccountAbstraction.SignerPermissionRequest; - var nullTypedData = null as Nethereum.ABI.EIP712.TypedData; - var nullSig = null as string; - _ = await Assert.ThrowsAsync(async () => - await wallet.RecoverAddressFromTypedDataV4(nullData, nullTypedData, nullSig) - ); - _ = await Assert.ThrowsAsync(async () => await wallet.RecoverAddressFromTypedDataV4(new AccountAbstraction.SignerPermissionRequest(), nullTypedData, nullSig)); - _ = await Assert.ThrowsAsync(async () => - await wallet.RecoverAddressFromTypedDataV4(new AccountAbstraction.SignerPermissionRequest(), new Nethereum.ABI.EIP712.TypedData(), nullSig) - ); -#nullable restore - } - [Fact(Timeout = 120000)] public async Task SwitchNetwork_Success() { @@ -245,6 +105,6 @@ public async Task SwitchNetwork_Success() Assert.Equal(11155111, wrappedSmartWallet.ActiveChainId); Assert.Equal(11155111, smartWallet.ActiveChainId); - await (await PrivateKeyWallet.Generate(this.Client)).SwitchNetwork(11155111); + await (await this.GetGuestAccount()).SwitchNetwork(11155111); } } diff --git a/Thirdweb/Thirdweb.AI/ChatClient.cs b/Thirdweb/Thirdweb.AI/ChatClient.cs deleted file mode 100644 index 73c19ee3..00000000 --- a/Thirdweb/Thirdweb.AI/ChatClient.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Text; -using Newtonsoft.Json; - -namespace Thirdweb.AI; - -internal class ChatClient -{ - private readonly IThirdwebHttpClient _httpClient; - - public ChatClient(IThirdwebHttpClient httpClient) - { - this._httpClient = httpClient; - } - - public async Task SendMessageAsync(ChatParamsSingleMessage message) - { - var content = new StringContent(JsonConvert.SerializeObject(message), Encoding.UTF8, "application/json"); - var response = await this._httpClient.PostAsync($"{Constants.NEBULA_API_URL}/chat", content); - _ = response.EnsureSuccessStatusCode(); - var responseContent = await response.Content.ReadAsStringAsync(); - return JsonConvert.DeserializeObject(responseContent); - } - - public async Task SendMessagesAsync(ChatParamsMultiMessages messages) - { - var content = new StringContent(JsonConvert.SerializeObject(messages), Encoding.UTF8, "application/json"); - var response = await this._httpClient.PostAsync($"{Constants.NEBULA_API_URL}/chat", content); - _ = response.EnsureSuccessStatusCode(); - var responseContent = await response.Content.ReadAsStringAsync(); - return JsonConvert.DeserializeObject(responseContent); - } -} diff --git a/Thirdweb/Thirdweb.AI/ExecutionClient.cs b/Thirdweb/Thirdweb.AI/ExecutionClient.cs deleted file mode 100644 index 831789fa..00000000 --- a/Thirdweb/Thirdweb.AI/ExecutionClient.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Text; -using Newtonsoft.Json; - -namespace Thirdweb.AI; - -internal class ExecutionClient -{ - private readonly IThirdwebHttpClient _httpClient; - - public ExecutionClient(IThirdwebHttpClient httpClient) - { - this._httpClient = httpClient; - } - - public async Task ExecuteAsync(ChatParamsSingleMessage command) - { - var content = new StringContent(JsonConvert.SerializeObject(command), Encoding.UTF8, "application/json"); - var response = await this._httpClient.PostAsync($"{Constants.NEBULA_API_URL}/execute", content); - _ = response.EnsureSuccessStatusCode(); - var responseContent = await response.Content.ReadAsStringAsync(); - return JsonConvert.DeserializeObject(responseContent); - } - - public async Task ExecuteBatchAsync(ChatParamsMultiMessages commands) - { - var content = new StringContent(JsonConvert.SerializeObject(commands), Encoding.UTF8, "application/json"); - var response = await this._httpClient.PostAsync($"{Constants.NEBULA_API_URL}/execute", content); - _ = response.EnsureSuccessStatusCode(); - var responseContent = await response.Content.ReadAsStringAsync(); - return JsonConvert.DeserializeObject(responseContent); - } -} diff --git a/Thirdweb/Thirdweb.AI/SessionManager.cs b/Thirdweb/Thirdweb.AI/SessionManager.cs deleted file mode 100644 index b608bb6a..00000000 --- a/Thirdweb/Thirdweb.AI/SessionManager.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System.Text; -using Newtonsoft.Json; - -namespace Thirdweb.AI; - -internal class SessionManager -{ - private readonly IThirdwebHttpClient _httpClient; - - public SessionManager(IThirdwebHttpClient httpClient) - { - this._httpClient = httpClient; - } - - public async Task> ListSessionsAsync() - { - var response = await this._httpClient.GetAsync($"{Constants.NEBULA_API_URL}/session/list"); - _ = response.EnsureSuccessStatusCode(); - var content = await response.Content.ReadAsStringAsync(); - return JsonConvert.DeserializeObject>>(content).Result; - } - - public async Task GetSessionAsync(string sessionId) - { - var response = await this._httpClient.GetAsync($"{Constants.NEBULA_API_URL}/session/{sessionId}"); - _ = response.EnsureSuccessStatusCode(); - var content = await response.Content.ReadAsStringAsync(); - return JsonConvert.DeserializeObject>(content).Result; - } - - public async Task CreateSessionAsync(CreateSessionParams parameters) - { - var content = new StringContent(JsonConvert.SerializeObject(parameters), Encoding.UTF8, "application/json"); - var response = await this._httpClient.PostAsync($"{Constants.NEBULA_API_URL}/session", content); - _ = response.EnsureSuccessStatusCode(); - var responseContent = await response.Content.ReadAsStringAsync(); - return JsonConvert.DeserializeObject>(responseContent).Result; - } - - public async Task UpdateSessionAsync(string sessionId, UpdateSessionParams parameters) - { - var content = new StringContent(JsonConvert.SerializeObject(parameters), Encoding.UTF8, "application/json"); - var response = await this._httpClient.PutAsync($"{Constants.NEBULA_API_URL}/session/{sessionId}", content); - _ = response.EnsureSuccessStatusCode(); - var responseContent = await response.Content.ReadAsStringAsync(); - return JsonConvert.DeserializeObject>(responseContent).Result; - } - - public async Task DeleteSessionAsync(string sessionId) - { - var response = await this._httpClient.DeleteAsync($"{Constants.NEBULA_API_URL}/session/{sessionId}"); - _ = response.EnsureSuccessStatusCode(); - var content = await response.Content.ReadAsStringAsync(); - return JsonConvert.DeserializeObject>(content).Result; - } - - public async Task ClearSessionAsync(string sessionId) - { - var response = await this._httpClient.PostAsync($"{Constants.NEBULA_API_URL}/session/{sessionId}/clear", null); - _ = response.EnsureSuccessStatusCode(); - var content = await response.Content.ReadAsStringAsync(); - return JsonConvert.DeserializeObject>(content).Result; - } -} diff --git a/Thirdweb/Thirdweb.AI/ThirdwebNebula.Types.cs b/Thirdweb/Thirdweb.AI/ThirdwebNebula.Types.cs deleted file mode 100644 index 0c5b13d4..00000000 --- a/Thirdweb/Thirdweb.AI/ThirdwebNebula.Types.cs +++ /dev/null @@ -1,254 +0,0 @@ -using System.Numerics; -using Newtonsoft.Json; - -namespace Thirdweb.AI; - -/// -/// Represents the response model wrapping the result of an API call. -/// -/// The type of the result. -internal class ResponseModel -{ - /// - /// The result returned by the API. - /// - [JsonProperty("result")] - internal T Result { get; set; } -} - -/// -/// Represents an action performed by an agent in a session. -/// -internal class AgentAction -{ - [JsonProperty("session_id")] - internal string SessionId { get; set; } - - [JsonProperty("request_id")] - internal string RequestId { get; set; } - - [JsonProperty("type")] - internal string Type { get; set; } - - [JsonProperty("source")] - internal string Source { get; set; } - - [JsonProperty("data")] - internal string Data { get; set; } -} - -/// -/// Represents a single chat message. -/// -internal class ChatMessage -{ - [JsonProperty("role")] - internal string Role { get; set; } = "user"; - - [JsonProperty("content")] - internal string Content { get; set; } -} - -/// -/// Represents parameters for sending multiple chat messages in a single request. -/// -internal class ChatParamsMultiMessages -{ - [JsonProperty("stream")] - internal bool? Stream { get; set; } = false; - - [JsonProperty("session_id")] - internal string SessionId { get; set; } - - [JsonProperty("context")] - internal CompletionContext ContextFilter { get; set; } - - [JsonProperty("model_name")] - internal string ModelName { get; set; } - - [JsonProperty("messages")] - internal List Messages { get; set; } -} - -/// -/// Represents parameters for sending a single chat message. -/// -internal class ChatParamsSingleMessage -{ - [JsonProperty("stream")] - internal bool? Stream { get; set; } = false; - - [JsonProperty("session_id")] - internal string SessionId { get; set; } - - [JsonProperty("context")] - internal CompletionContext ContextFilter { get; set; } - - [JsonProperty("model_name")] - internal string ModelName { get; set; } - - [JsonProperty("message")] - internal string Message { get; set; } -} - -/// -/// Represents the response from a chat interaction. -/// -public class ChatResponse -{ - [JsonProperty("message")] - internal string Message { get; set; } - - [JsonProperty("actions")] - internal List Actions { get; set; } - - [JsonProperty("session_id")] - internal string SessionId { get; set; } - - [JsonProperty("request_id")] - internal string RequestId { get; set; } -} - -/// -/// Represents filters for narrowing down context in which operations are performed. -/// -internal class CompletionContext -{ - [JsonProperty("session_id")] - public string SessionId { get; set; } = null; - - [JsonProperty("wallet_address")] - public string WalletAddress { get; set; } = null; - - [JsonProperty("chain_ids")] - public List ChainIds { get; set; } = null; -} - -/// -/// Nebula representation of a smart contract. -/// -public class DeployedContract -{ - [JsonProperty("name")] - public string Name { get; set; } = string.Empty; - - [JsonProperty("address")] - public string Address { get; set; } - - [JsonProperty("chain_id")] - public BigInteger ChainId { get; set; } - - [JsonProperty("contract_type")] - public string ContractType { get; set; } = string.Empty; -} - -/// -/// Represents parameters for creating a new session. -/// -internal class CreateSessionParams -{ - [JsonProperty("model_name")] - internal string ModelName { get; set; } = Constants.NEBULA_DEFAULT_MODEL; - - [JsonProperty("title")] - internal string Title { get; set; } - - [JsonProperty("is_public")] - internal bool? IsPublic { get; set; } - - [JsonProperty("context")] - internal CompletionContext ContextFilter { get; set; } -} - -/// -/// Represents session details. -/// -internal class Session -{ - [JsonProperty("id")] - internal string Id { get; set; } - - [JsonProperty("account_id")] - internal string AccountId { get; set; } - - [JsonProperty("model_name")] - internal string ModelName { get; set; } - - [JsonProperty("is_public")] - internal bool? IsPublic { get; set; } - - [JsonProperty("title")] - internal string Title { get; set; } - - [JsonProperty("memory")] - internal List Memory { get; set; } - - [JsonProperty("history")] - internal List History { get; set; } - - [JsonProperty("action")] - internal List Action { get; set; } - - [JsonProperty("context")] - internal CompletionContext ContextFilter { get; set; } - - [JsonProperty("archive_at")] - internal DateTime? ArchiveAt { get; set; } - - [JsonProperty("deleted_at")] - internal DateTime? DeletedAt { get; set; } - - [JsonProperty("created_at")] - internal DateTime? CreatedAt { get; set; } - - [JsonProperty("updated_at")] - internal DateTime? UpdatedAt { get; set; } -} - -/// -/// Represents parameters for updating a session. -/// -internal class UpdateSessionParams -{ - [JsonProperty("title")] - internal string Title { get; set; } - - [JsonProperty("model_name")] - internal string ModelName { get; set; } - - [JsonProperty("is_public")] - internal bool? IsPublic { get; set; } - - [JsonProperty("context")] - internal CompletionContext ContextFilter { get; set; } -} - -/// -/// Represents the response for deleting a session. -/// -internal class SessionDeleteResponse -{ - [JsonProperty("id")] - internal string Id { get; set; } - - [JsonProperty("deleted_at")] - internal DateTime DeletedAt { get; set; } -} - -/// -/// Represents a session in a session list. -/// -internal class SessionList -{ - [JsonProperty("id")] - internal string Id { get; set; } - - [JsonProperty("title")] - internal string Title { get; set; } - - [JsonProperty("created_at")] - internal DateTime CreatedAt { get; set; } - - [JsonProperty("updated_at")] - internal DateTime UpdatedAt { get; set; } -} diff --git a/Thirdweb/Thirdweb.AI/ThirdwebNebula.cs b/Thirdweb/Thirdweb.AI/ThirdwebNebula.cs deleted file mode 100644 index c30f6538..00000000 --- a/Thirdweb/Thirdweb.AI/ThirdwebNebula.cs +++ /dev/null @@ -1,265 +0,0 @@ -using System.Numerics; -using Newtonsoft.Json; - -namespace Thirdweb.AI; - -public enum NebulaChatRole -{ - User, - Assistant, -} - -public class NebulaChatMessage -{ - public NebulaChatRole Role { get; set; } = NebulaChatRole.User; - public string Message { get; set; } - - public NebulaChatMessage(string message, NebulaChatRole role = NebulaChatRole.User) - { - this.Message = message; - this.Role = role; - } -} - -public class NebulaChatResult -{ - public string Message { get; set; } - public List Transactions { get; set; } -} - -public class NebulaExecuteResult -{ - public string Message { get; set; } - public List TransactionReceipts { get; set; } -} - -public class NebulaContext -{ - public List ChainIds { get; set; } - public string WalletAddress { get; set; } - - /// - /// Represents filters for narrowing down context in which operations are performed. - /// - /// The chain IDs to filter by. - /// The wallet addresses to filter by. - public NebulaContext(List chainIds = null, string walletAddress = null) - { - this.ChainIds = chainIds; - this.WalletAddress = walletAddress; - } -} - -public class ThirdwebNebula -{ - public string SessionId { get; private set; } - - internal SessionManager Sessions { get; } - internal ChatClient ChatClient { get; } - internal ExecutionClient ExecuteClient { get; } - - internal ThirdwebNebula(ThirdwebClient client) - { - var httpClient = client.HttpClient; - this.Sessions = new SessionManager(httpClient); - this.ChatClient = new ChatClient(httpClient); - this.ExecuteClient = new ExecutionClient(httpClient); - } - - public static async Task Create(ThirdwebClient client, string sessionId = null, string model = Constants.NEBULA_DEFAULT_MODEL) - { - var nebula = new ThirdwebNebula(client); - - if (!string.IsNullOrWhiteSpace(sessionId)) - { - nebula.SessionId = sessionId; - return nebula; - } - else - { - var session = await nebula.Sessions.CreateSessionAsync( - new CreateSessionParams() - { - ModelName = model, - Title = $"Thirdweb .NET SDK (v{Constants.VERSION}) | Nebula {model} Session | Client ID: {client.ClientId}", - IsPublic = false, - } - ); - nebula.SessionId = session.Id; - return nebula; - } - } - - public async Task Chat(string message, IThirdwebWallet wallet = null, NebulaContext context = null) - { - if (string.IsNullOrWhiteSpace(message)) - { - throw new ArgumentException("Message cannot be null or empty.", nameof(message)); - } - - var contextFiler = await this.PrepareContextFilter(wallet, context); - - var result = await this.ChatClient.SendMessageAsync( - new ChatParamsSingleMessage() - { - SessionId = this.SessionId, - Message = message, - ContextFilter = contextFiler, - } - ); - - var transactions = await PrepareTransactions(wallet, result.Actions); - - return new NebulaChatResult() { Message = result.Message, Transactions = transactions == null || transactions.Count == 0 ? null : transactions }; - } - - public async Task Chat(List messages, IThirdwebWallet wallet = null, NebulaContext context = null) - { - if (messages == null || messages.Count == 0 || messages.Any(m => string.IsNullOrWhiteSpace(m.Message))) - { - throw new ArgumentException("Messages cannot be null or empty.", nameof(messages)); - } - - var contextFiler = await this.PrepareContextFilter(wallet, context); - - var result = await this.ChatClient.SendMessagesAsync( - new ChatParamsMultiMessages() - { - SessionId = this.SessionId, - Messages = messages.Select(prompt => new ChatMessage() { Content = prompt.Message, Role = prompt.Role.ToString().ToLower() }).ToList(), - ContextFilter = contextFiler, - } - ); - - var transactions = await PrepareTransactions(wallet, result.Actions); - - return new NebulaChatResult() { Message = result.Message, Transactions = transactions == null || transactions.Count == 0 ? null : transactions }; - } - - public async Task Execute(string message, IThirdwebWallet wallet, NebulaContext context = null) - { - if (string.IsNullOrWhiteSpace(message)) - { - throw new ArgumentException("Message cannot be null or empty.", nameof(message)); - } - - if (wallet == null) - { - throw new ArgumentException("Wallet cannot be null.", nameof(wallet)); - } - - var contextFiler = await this.PrepareContextFilter(wallet, context); - var result = await this.ExecuteClient.ExecuteAsync( - new ChatParamsSingleMessage() - { - SessionId = this.SessionId, - Message = message, - ContextFilter = contextFiler, - } - ); - - var transactions = await PrepareTransactions(wallet, result.Actions); - if (transactions == null || transactions.Count == 0) - { - return new NebulaExecuteResult() { Message = result.Message }; - } - else - { - var receipts = await Task.WhenAll(transactions.Select(ThirdwebTransaction.SendAndWaitForTransactionReceipt)); - return new NebulaExecuteResult() { Message = result.Message, TransactionReceipts = receipts.ToList() }; - } - } - - public async Task Execute(List messages, IThirdwebWallet wallet, NebulaContext context = null) - { - if (messages == null || messages.Count == 0 || messages.Any(m => string.IsNullOrWhiteSpace(m.Message))) - { - throw new ArgumentException("Messages cannot be null or empty.", nameof(messages)); - } - - if (wallet == null) - { - throw new ArgumentException("Wallet cannot be null.", nameof(wallet)); - } - - var contextFiler = await this.PrepareContextFilter(wallet, context); - var result = await this.ExecuteClient.ExecuteBatchAsync( - new ChatParamsMultiMessages() - { - SessionId = this.SessionId, - Messages = messages.Select(prompt => new ChatMessage() { Content = prompt.Message, Role = prompt.Role.ToString().ToLower() }).ToList(), - ContextFilter = contextFiler, - } - ); - - var transactions = await PrepareTransactions(wallet, result.Actions); - if (transactions == null || transactions.Count == 0) - { - return new NebulaExecuteResult() { Message = result.Message }; - } - else - { - var receipts = await Task.WhenAll(transactions.Select(ThirdwebTransaction.SendAndWaitForTransactionReceipt)); - return new NebulaExecuteResult() { Message = result.Message, TransactionReceipts = receipts.ToList() }; - } - } - - private async Task PrepareContextFilter(IThirdwebWallet wallet, NebulaContext context) - { - context ??= new NebulaContext(); - - if (wallet != null) - { - context.WalletAddress ??= await wallet.GetAddress(); - if (wallet is SmartWallet smartWallet) - { - context.ChainIds ??= new List(); - if (context.ChainIds.Count == 0 || !context.ChainIds.Contains(smartWallet.ActiveChainId)) - { - context.ChainIds.Add(smartWallet.ActiveChainId); - } - } - } - - return new CompletionContext() - { - SessionId = this.SessionId, - ChainIds = context?.ChainIds?.Select(id => id).ToList(), - WalletAddress = context?.WalletAddress, - }; - } - - private static async Task> PrepareTransactions(IThirdwebWallet wallet, List actions) - { - if (wallet != null && actions != null && actions.Count > 0) - { - var transactionTasks = actions - .Select(action => - { - if (action.Type == "sign_transaction") - { - var txInput = JsonConvert.DeserializeObject(action.Data); - return ThirdwebTransaction.Create(wallet, txInput); - } - else - { - return null; - } - }) - .ToList(); - - if (transactionTasks == null || transactionTasks.Count == 0) - { - return null; - } - - _ = transactionTasks.RemoveAll(task => task == null); - - return (await Task.WhenAll(transactionTasks)).Where(tx => tx != null).ToList(); - } - else - { - return null; - } - } -} diff --git a/Thirdweb/Thirdweb.Api/GeneratedClient.cs b/Thirdweb/Thirdweb.Api/ThirdwebApi.cs similarity index 63% rename from Thirdweb/Thirdweb.Api/GeneratedClient.cs rename to Thirdweb/Thirdweb.Api/ThirdwebApi.cs index b8c1579e..5047043a 100644 --- a/Thirdweb/Thirdweb.Api/GeneratedClient.cs +++ b/Thirdweb/Thirdweb.Api/ThirdwebApi.cs @@ -25,7 +25,7 @@ namespace Thirdweb.Api using System = global::System; [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - internal partial class ThirdwebApiClient + public partial class ThirdwebApiClient { #pragma warning disable 8618 private string _baseUrl; @@ -81,7 +81,6 @@ public string BaseUrl ///
**Supported Methods:** ///
- **SMS** - Send verification code to phone number ///
- **Email** - Send verification code to email address - ///
- **OAuth** - Generate redirect link (Google, Apple, Facebook, Discord, GitHub, X, Coinbase, Farcaster, Telegram, LINE, Twitch, Steam) ///
- **Passkey** - Generate WebAuthn challenge for biometric authentication ///
- **SIWE** - Generate Sign-In with Ethereum payload ///
@@ -89,14 +88,22 @@ public string BaseUrl ///
1. Choose your authentication method ///
2. Provide method-specific parameters ///
3. Receive challenge data to complete authentication - ///
4. Use the `/complete` endpoint to finish the process + ///
4. Use the /complete endpoint to finish the process ///
- ///
NOTE: for custom authentication (JWT, auth-payload) and for guest authentication, you can skip this step and use the `/complete` endpoint directly. + ///
**OAuth:** + ///
+ ///
The OAuth method uses a dedicated `/auth/social` endpoint instead of this one: + ///
+ ///
`GET /auth/social?provider=google&redirectUrl=...` + ///
+ ///
**Custom (JWT, auth-payload) and Guest:** + ///
+ ///
For custom authentication (JWT, auth-payload) and for guest authentication, you can skip this step and use the `/auth/complete` endpoint directly. ///
///
**Authentication:** Requires `x-client-id` header for frontend usage or `x-secret-key` for backend usage. /// /// Authentication initiated successfully. Use the returned challenge data to complete authentication. - /// A server side error occurred. + /// A server side error occurred. public virtual System.Threading.Tasks.Task InitiateAuthenticationAsync(Body body) { return InitiateAuthenticationAsync(body, System.Threading.CancellationToken.None); @@ -112,7 +119,6 @@ public virtual System.Threading.Tasks.Task InitiateAuthenticationAsync ///
**Supported Methods:** ///
- **SMS** - Send verification code to phone number ///
- **Email** - Send verification code to email address - ///
- **OAuth** - Generate redirect link (Google, Apple, Facebook, Discord, GitHub, X, Coinbase, Farcaster, Telegram, LINE, Twitch, Steam) ///
- **Passkey** - Generate WebAuthn challenge for biometric authentication ///
- **SIWE** - Generate Sign-In with Ethereum payload ///
@@ -120,14 +126,22 @@ public virtual System.Threading.Tasks.Task InitiateAuthenticationAsync ///
1. Choose your authentication method ///
2. Provide method-specific parameters ///
3. Receive challenge data to complete authentication - ///
4. Use the `/complete` endpoint to finish the process + ///
4. Use the /complete endpoint to finish the process + ///
+ ///
**OAuth:** + ///
+ ///
The OAuth method uses a dedicated `/auth/social` endpoint instead of this one: + ///
+ ///
`GET /auth/social?provider=google&redirectUrl=...` + ///
+ ///
**Custom (JWT, auth-payload) and Guest:** ///
- ///
NOTE: for custom authentication (JWT, auth-payload) and for guest authentication, you can skip this step and use the `/complete` endpoint directly. + ///
For custom authentication (JWT, auth-payload) and for guest authentication, you can skip this step and use the `/auth/complete` endpoint directly. ///
///
**Authentication:** Requires `x-client-id` header for frontend usage or `x-secret-key` for backend usage. /// /// Authentication initiated successfully. Use the returned challenge data to complete authentication. - /// A server side error occurred. + /// A server side error occurred. public virtual async System.Threading.Tasks.Task InitiateAuthenticationAsync(Body body, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; @@ -176,7 +190,7 @@ public virtual async System.Threading.Tasks.Task InitiateAuthenticatio var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -184,18 +198,18 @@ public virtual async System.Threading.Tasks.Task InitiateAuthenticatio if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request - Check your method and parameters", status_, responseText_, headers_, null); + throw new ApiException("Invalid request - Check your method and parameters", status_, responseText_, headers_, null); } else if (status_ == 429) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Rate limit exceeded - Please wait before trying again", status_, responseText_, headers_, null); + throw new ApiException("Rate limit exceeded - Please wait before trying again", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -231,10 +245,26 @@ public virtual async System.Threading.Tasks.Task InitiateAuthenticatio ///
- `type` - The authentication method used ///
- `walletAddress` - Your new or existing wallet address ///
+ ///
**Next step - Verify your token:** + ///
```javascript + ///
// Verify the token and get complete wallet details (server-side) + ///
fetch('/v1/wallets/me', { + ///
headers: { + ///
'Authorization': 'Bearer ' + token, + ///
'x-secret-key': 'your-secret-key' + ///
} + ///
}) + ///
.then(response => response.json()) + ///
.then(data => { + ///
console.log('Wallet verified:', data.result.address); + ///
console.log('Auth profiles:', data.result.profiles); + ///
}); + ///
``` + ///
///
**Authentication:** Requires `x-client-id` header for frontend usage or `x-secret-key` for backend usage. /// /// Authentication completed successfully. You now have wallet access. - /// A server side error occurred. + /// A server side error occurred. public virtual System.Threading.Tasks.Task CompleteAuthenticationAsync(Body2 body) { return CompleteAuthenticationAsync(body, System.Threading.CancellationToken.None); @@ -260,10 +290,26 @@ public virtual System.Threading.Tasks.Task CompleteAuthenticationAsyn ///
- `type` - The authentication method used ///
- `walletAddress` - Your new or existing wallet address ///
+ ///
**Next step - Verify your token:** + ///
```javascript + ///
// Verify the token and get complete wallet details (server-side) + ///
fetch('/v1/wallets/me', { + ///
headers: { + ///
'Authorization': 'Bearer ' + token, + ///
'x-secret-key': 'your-secret-key' + ///
} + ///
}) + ///
.then(response => response.json()) + ///
.then(data => { + ///
console.log('Wallet verified:', data.result.address); + ///
console.log('Auth profiles:', data.result.profiles); + ///
}); + ///
``` + ///
///
**Authentication:** Requires `x-client-id` header for frontend usage or `x-secret-key` for backend usage. /// /// Authentication completed successfully. You now have wallet access. - /// A server side error occurred. + /// A server side error occurred. public virtual async System.Threading.Tasks.Task CompleteAuthenticationAsync(Body2 body, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; @@ -312,7 +358,7 @@ public virtual async System.Threading.Tasks.Task CompleteAuthenticati var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -320,18 +366,248 @@ public virtual async System.Threading.Tasks.Task CompleteAuthenticati if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid credentials or request - Check your challenge ID and verification data", status_, responseText_, headers_, null); + throw new ApiException("Invalid credentials or request - Check your challenge ID and verification data", status_, responseText_, headers_, null); } else if (status_ == 429) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Rate limit exceeded - Please wait before trying again", status_, responseText_, headers_, null); + throw new ApiException("Rate limit exceeded - Please wait before trying again", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Social Auth + /// + /// + /// Complete OAuth authentication with social providers in a single step. Unlike other auth methods that require separate initiate/complete calls, OAuth is handled entirely through redirects. + ///
+ ///
**OAuth Flow (Self-Contained):** + ///
1. Redirect your user to this endpoint with provider and redirectUrl + ///
2. User completes OAuth flow with the provider + ///
3. User is redirected back to your redirectUrl with wallet credentials + ///
+ ///
**Why OAuth is different:** OAuth providers handle the challenge/response flow externally, so no separate `/complete` step is needed. + ///
+ ///
**Example:** + ///
Redirect user to: `GET /v1/auth/social?provider=google&redirectUrl=https://myapp.com/auth/callback` + ///
+ ///
**Callback Handling:** + ///
After OAuth completion, user arrives at your redirectUrl with an `authResult` query parameter: + ///
``` + ///
https://myapp.com/auth/callback?authResult=%7B%22storedToken%22%3A%7B%22authDetails%22%3A%7B...%7D%2C%22cookieString%22%3A%22eyJ...%22%7D%7D + ///
``` + ///
+ ///
**Extract JWT token in your callback:** + ///
```javascript + ///
// Parse the authResult from URL + ///
const urlParams = new URLSearchParams(window.location.search); + ///
const authResultString = urlParams.get('authResult'); + ///
const authResult = JSON.parse(authResultString!); + ///
+ ///
// Extract the JWT token + ///
const token = authResult.storedToken.cookieString; + ///
``` + ///
+ ///
**Verify and use the JWT token:** + ///
```javascript + ///
// Use the JWT token for authenticated requests + ///
fetch('/v1/wallets/me', { + ///
headers: { + ///
'Authorization': 'Bearer ' + token, + ///
'x-secret-key': 'your-secret-key' + ///
} + ///
}) + ///
.then(response => response.json()) + ///
.then(data => { + ///
console.log('Wallet verified:', data.result.address); + ///
console.log('Auth profiles:', data.result.profiles); + ///
}); + ///
``` + ///
+ ///
**Authentication Options:** + ///
Choose one of two ways to provide your client credentials: + ///
+ ///
**Option 1: Query Parameter (Recommended for OAuth flows)** + ///
``` + ///
GET /v1/auth/social?provider=google&redirectUrl=https://myapp.com/callback&clientId=your_client_id + ///
``` + ///
+ ///
**Option 2: Header (Alternative)** + ///
``` + ///
GET /v1/auth/social?provider=google&redirectUrl=https://myapp.com/callback + ///
Headers: x-client-id: your_client_id + ///
``` + ///
+ /// The OAuth provider to use + /// URL to redirect the user to after OAuth completion + /// Client ID (alternative to x-client-id header for standard OAuth flows) + /// A server side error occurred. + public virtual System.Threading.Tasks.Task SocialAuthenticationAsync(Provider provider, System.Uri redirectUrl, string clientId) + { + return SocialAuthenticationAsync(provider, redirectUrl, clientId, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Social Auth + /// + /// + /// Complete OAuth authentication with social providers in a single step. Unlike other auth methods that require separate initiate/complete calls, OAuth is handled entirely through redirects. + ///
+ ///
**OAuth Flow (Self-Contained):** + ///
1. Redirect your user to this endpoint with provider and redirectUrl + ///
2. User completes OAuth flow with the provider + ///
3. User is redirected back to your redirectUrl with wallet credentials + ///
+ ///
**Why OAuth is different:** OAuth providers handle the challenge/response flow externally, so no separate `/complete` step is needed. + ///
+ ///
**Example:** + ///
Redirect user to: `GET /v1/auth/social?provider=google&redirectUrl=https://myapp.com/auth/callback` + ///
+ ///
**Callback Handling:** + ///
After OAuth completion, user arrives at your redirectUrl with an `authResult` query parameter: + ///
``` + ///
https://myapp.com/auth/callback?authResult=%7B%22storedToken%22%3A%7B%22authDetails%22%3A%7B...%7D%2C%22cookieString%22%3A%22eyJ...%22%7D%7D + ///
``` + ///
+ ///
**Extract JWT token in your callback:** + ///
```javascript + ///
// Parse the authResult from URL + ///
const urlParams = new URLSearchParams(window.location.search); + ///
const authResultString = urlParams.get('authResult'); + ///
const authResult = JSON.parse(authResultString!); + ///
+ ///
// Extract the JWT token + ///
const token = authResult.storedToken.cookieString; + ///
``` + ///
+ ///
**Verify and use the JWT token:** + ///
```javascript + ///
// Use the JWT token for authenticated requests + ///
fetch('/v1/wallets/me', { + ///
headers: { + ///
'Authorization': 'Bearer ' + token, + ///
'x-secret-key': 'your-secret-key' + ///
} + ///
}) + ///
.then(response => response.json()) + ///
.then(data => { + ///
console.log('Wallet verified:', data.result.address); + ///
console.log('Auth profiles:', data.result.profiles); + ///
}); + ///
``` + ///
+ ///
**Authentication Options:** + ///
Choose one of two ways to provide your client credentials: + ///
+ ///
**Option 1: Query Parameter (Recommended for OAuth flows)** + ///
``` + ///
GET /v1/auth/social?provider=google&redirectUrl=https://myapp.com/callback&clientId=your_client_id + ///
``` + ///
+ ///
**Option 2: Header (Alternative)** + ///
``` + ///
GET /v1/auth/social?provider=google&redirectUrl=https://myapp.com/callback + ///
Headers: x-client-id: your_client_id + ///
``` + ///
+ /// The OAuth provider to use + /// URL to redirect the user to after OAuth completion + /// Client ID (alternative to x-client-id header for standard OAuth flows) + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task SocialAuthenticationAsync(Provider provider, System.Uri redirectUrl, string clientId, System.Threading.CancellationToken cancellationToken) + { + if (provider == null) + throw new System.ArgumentNullException("provider"); + + if (redirectUrl == null) + throw new System.ArgumentNullException("redirectUrl"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + request_.Method = new System.Net.Http.HttpMethod("GET"); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "v1/auth/social" + urlBuilder_.Append("v1/auth/social"); + urlBuilder_.Append('?'); + urlBuilder_.Append(System.Uri.EscapeDataString("provider")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(provider, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + urlBuilder_.Append(System.Uri.EscapeDataString("redirectUrl")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(redirectUrl, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + if (clientId != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("clientId")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(clientId, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 302) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Redirects to OAuth provider for authentication", status_, responseText_, headers_, null); + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Invalid request parameters", status_, responseText_, headers_, null); + } + else + + if (status_ == 200 || status_ == 204) + { + + return; } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -364,7 +640,7 @@ public virtual async System.Threading.Tasks.Task CompleteAuthenticati ///
**Authentication:** Requires `Authorization: Bearer <jwt>` header with a valid user authentication token. /// /// Wallet retrieved successfully. Returns comprehensive user information including wallet addresses, public key, and linked wallets. - /// A server side error occurred. + /// A server side error occurred. public virtual System.Threading.Tasks.Task GetMyWalletAsync() { return GetMyWalletAsync(System.Threading.CancellationToken.None); @@ -387,7 +663,7 @@ public virtual System.Threading.Tasks.Task GetMyWalletAsync() ///
**Authentication:** Requires `Authorization: Bearer <jwt>` header with a valid user authentication token. /// /// Wallet retrieved successfully. Returns comprehensive user information including wallet addresses, public key, and linked wallets. - /// A server side error occurred. + /// A server side error occurred. public virtual async System.Threading.Tasks.Task GetMyWalletAsync(System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; @@ -432,7 +708,7 @@ public virtual async System.Threading.Tasks.Task GetMyWalletAsync(Sys var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -440,24 +716,24 @@ public virtual async System.Threading.Tasks.Task GetMyWalletAsync(Sys if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include a valid `Authorization: Bearer ` header.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. The request must include a valid `Authorization: Bearer ` header.", status_, responseText_, headers_, null); } else if (status_ == 404) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Wallet not found. The authenticated user does not exist in the system.", status_, responseText_, headers_, null); + throw new ApiException("Wallet not found. The authenticated user does not exist in the system.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to service unavailability or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to service unavailability or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -483,7 +759,7 @@ public virtual async System.Threading.Tasks.Task GetMyWalletAsync(Sys ///
**Authentication**: This endpoint requires backend authentication using the `x-secret-key` header. The secret key should never be exposed publicly. /// /// Returns a list of user wallet addresses, smart wallet addresses, and auth details. - /// A server side error occurred. + /// A server side error occurred. public virtual System.Threading.Tasks.Task ListUserWalletsAsync(double? limit, double? page, string email, string phone, string address, string externalWalletAddress, string id) { return ListUserWalletsAsync(limit, page, email, phone, address, externalWalletAddress, id, System.Threading.CancellationToken.None); @@ -499,7 +775,7 @@ public virtual System.Threading.Tasks.Task ListUserWalletsAsync(doubl ///
**Authentication**: This endpoint requires backend authentication using the `x-secret-key` header. The secret key should never be exposed publicly. /// /// Returns a list of user wallet addresses, smart wallet addresses, and auth details. - /// A server side error occurred. + /// A server side error occurred. public virtual async System.Threading.Tasks.Task ListUserWalletsAsync(double? limit, double? page, string email, string phone, string address, string externalWalletAddress, string id, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; @@ -574,7 +850,7 @@ public virtual async System.Threading.Tasks.Task ListUserWalletsAsync var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -582,18 +858,18 @@ public virtual async System.Threading.Tasks.Task ListUserWalletsAsync if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include a valid `x-secret-key` header for backend authentication.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. The request must include a valid `x-secret-key` header for backend authentication.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to service unavailability or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to service unavailability or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -619,7 +895,7 @@ public virtual async System.Threading.Tasks.Task ListUserWalletsAsync ///
**Authentication**: This endpoint requires backend authentication using the `x-secret-key` header. The secret key should never be exposed publicly. /// /// Successfully created a user wallet with wallet. - /// A server side error occurred. + /// A server side error occurred. public virtual System.Threading.Tasks.Task CreateUserWalletAsync(Body3 body) { return CreateUserWalletAsync(body, System.Threading.CancellationToken.None); @@ -635,7 +911,7 @@ public virtual System.Threading.Tasks.Task CreateUserWalletAsync(Body ///
**Authentication**: This endpoint requires backend authentication using the `x-secret-key` header. The secret key should never be exposed publicly. /// /// Successfully created a user wallet with wallet. - /// A server side error occurred. + /// A server side error occurred. public virtual async System.Threading.Tasks.Task CreateUserWalletAsync(Body3 body, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; @@ -684,7 +960,7 @@ public virtual async System.Threading.Tasks.Task CreateUserWalletAsyn var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -692,24 +968,24 @@ public virtual async System.Threading.Tasks.Task CreateUserWalletAsyn if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request. This may occur due to missing required fields based on the authentication strategy, invalid strategy, or malformed request data.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request. This may occur due to missing required fields based on the authentication strategy, invalid strategy, or malformed request data.", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include a valid `x-secret-key` header for backend authentication.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. The request must include a valid `x-secret-key` header for backend authentication.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to service unavailability or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to service unavailability or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -735,7 +1011,7 @@ public virtual async System.Threading.Tasks.Task CreateUserWalletAsyn ///
**Authentication**: This endpoint requires backend authentication using the `x-secret-key` header. The secret key should never be exposed publicly. /// /// Returns a list of server wallet addresses, smart wallet addresses, and auth details. - /// A server side error occurred. + /// A server side error occurred. public virtual System.Threading.Tasks.Task ListServerWalletsAsync(double? limit, double? page) { return ListServerWalletsAsync(limit, page, System.Threading.CancellationToken.None); @@ -751,7 +1027,7 @@ public virtual System.Threading.Tasks.Task ListServerWalletsAsync(dou ///
**Authentication**: This endpoint requires backend authentication using the `x-secret-key` header. The secret key should never be exposed publicly. /// /// Returns a list of server wallet addresses, smart wallet addresses, and auth details. - /// A server side error occurred. + /// A server side error occurred. public virtual async System.Threading.Tasks.Task ListServerWalletsAsync(double? limit, double? page, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; @@ -806,7 +1082,7 @@ public virtual async System.Threading.Tasks.Task ListServerWalletsAsy var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -814,18 +1090,18 @@ public virtual async System.Threading.Tasks.Task ListServerWalletsAsy if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include a valid `x-secret-key` header for backend authentication.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. The request must include a valid `x-secret-key` header for backend authentication.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to service unavailability or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to service unavailability or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -851,7 +1127,7 @@ public virtual async System.Threading.Tasks.Task ListServerWalletsAsy ///
**Authentication**: This endpoint requires backend authentication using the `x-secret-key` header. The secret key should never be exposed publicly. /// /// Server wallet created or connected successfully. Returns wallet addresses for subsequent operations. - /// A server side error occurred. + /// A server side error occurred. public virtual System.Threading.Tasks.Task CreateServerWalletAsync(Body4 body) { return CreateServerWalletAsync(body, System.Threading.CancellationToken.None); @@ -867,7 +1143,7 @@ public virtual System.Threading.Tasks.Task CreateServerWalletAsync(Bo ///
**Authentication**: This endpoint requires backend authentication using the `x-secret-key` header. The secret key should never be exposed publicly. /// /// Server wallet created or connected successfully. Returns wallet addresses for subsequent operations. - /// A server side error occurred. + /// A server side error occurred. public virtual async System.Threading.Tasks.Task CreateServerWalletAsync(Body4 body, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; @@ -916,7 +1192,7 @@ public virtual async System.Threading.Tasks.Task CreateServerWalletAs var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -924,24 +1200,24 @@ public virtual async System.Threading.Tasks.Task CreateServerWalletAs if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters. This occurs when the identifier format is invalid or required parameters are missing.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters. This occurs when the identifier format is invalid or required parameters are missing.", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. For backend usage, include `x-secret-key` header.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. For backend usage, include `x-secret-key` header.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to wallet service unavailability, smart wallet deployment issues, or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to wallet service unavailability, smart wallet deployment issues, or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -970,7 +1246,7 @@ public virtual async System.Threading.Tasks.Task CreateServerWalletAs /// Chain ID(s) to request balance data for. You can specify multiple chain IDs by repeating the parameter, up to a maximum of 50. Example: ?chainId=1&chainId=137 /// The token contract address. Omit for native token (ETH, MATIC, etc.). /// Wallet native balances retrieved successfully. Returns detailed native token balance information for each chain including token metadata and formatted values. - /// A server side error occurred. + /// A server side error occurred. public virtual System.Threading.Tasks.Task GetWalletBalanceAsync(string address, System.Collections.Generic.IEnumerable chainId, string tokenAddress) { return GetWalletBalanceAsync(address, chainId, tokenAddress, System.Threading.CancellationToken.None); @@ -989,7 +1265,7 @@ public virtual System.Threading.Tasks.Task GetWalletBalanceAsync(stri /// Chain ID(s) to request balance data for. You can specify multiple chain IDs by repeating the parameter, up to a maximum of 50. Example: ?chainId=1&chainId=137 /// The token contract address. Omit for native token (ETH, MATIC, etc.). /// Wallet native balances retrieved successfully. Returns detailed native token balance information for each chain including token metadata and formatted values. - /// A server side error occurred. + /// A server side error occurred. public virtual async System.Threading.Tasks.Task GetWalletBalanceAsync(string address, System.Collections.Generic.IEnumerable chainId, string tokenAddress, System.Threading.CancellationToken cancellationToken) { if (address == null) @@ -1055,7 +1331,7 @@ public virtual async System.Threading.Tasks.Task GetWalletBalanceAsyn var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -1063,24 +1339,24 @@ public virtual async System.Threading.Tasks.Task GetWalletBalanceAsyn if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters. This occurs when the wallet address format is invalid, chainId array is empty or exceeds the maximum limit of 50, or chain IDs are invalid.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters. This occurs when the wallet address format is invalid, chainId array is empty or exceeds the maximum limit of 50, or chain IDs are invalid.", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or x-secret-key for backend usage.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or `x-secret-key` for backend usage.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to blockchain connectivity issues, RPC service unavailability, or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to blockchain connectivity issues, RPC service unavailability, or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -1117,7 +1393,7 @@ public virtual async System.Threading.Tasks.Task GetWalletBalanceAsyn /// Sort order: 'asc' for ascending, 'desc' for descending /// Chain ID(s) to request transaction data for. You can specify multiple chain IDs by repeating the parameter, up to a maximum of 50. Example: ?chainId=1&chainId=137 /// Wallet transactions retrieved successfully. Returns transaction data with metadata including pagination information and chain details. Includes decoded function calls when ABI is available. - /// A server side error occurred. + /// A server side error occurred. public virtual System.Threading.Tasks.Task GetWalletTransactionsAsync(string address, int? filterBlockTimestampGte, int? filterBlockTimestampLte, int? filterBlockNumberGte, int? filterBlockNumberLte, string filterValueGt, string filterFunctionSelector, double? page, double? limit, SortOrder? sortOrder, System.Collections.Generic.IEnumerable chainId) { return GetWalletTransactionsAsync(address, filterBlockTimestampGte, filterBlockTimestampLte, filterBlockNumberGte, filterBlockNumberLte, filterValueGt, filterFunctionSelector, page, limit, sortOrder, chainId, System.Threading.CancellationToken.None); @@ -1144,7 +1420,7 @@ public virtual System.Threading.Tasks.Task GetWalletTransactionsAsync /// Sort order: 'asc' for ascending, 'desc' for descending /// Chain ID(s) to request transaction data for. You can specify multiple chain IDs by repeating the parameter, up to a maximum of 50. Example: ?chainId=1&chainId=137 /// Wallet transactions retrieved successfully. Returns transaction data with metadata including pagination information and chain details. Includes decoded function calls when ABI is available. - /// A server side error occurred. + /// A server side error occurred. public virtual async System.Threading.Tasks.Task GetWalletTransactionsAsync(string address, int? filterBlockTimestampGte, int? filterBlockTimestampLte, int? filterBlockNumberGte, int? filterBlockNumberLte, string filterValueGt, string filterFunctionSelector, double? page, double? limit, SortOrder? sortOrder, System.Collections.Generic.IEnumerable chainId, System.Threading.CancellationToken cancellationToken) { if (address == null) @@ -1242,7 +1518,7 @@ public virtual async System.Threading.Tasks.Task GetWalletTransaction var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -1250,30 +1526,30 @@ public virtual async System.Threading.Tasks.Task GetWalletTransaction if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters. This occurs when the wallet address format is invalid, chainId array is empty or exceeds the maximum limit of 50, or pagination parameters are out of range.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters. This occurs when the wallet address format is invalid, chainId array is empty or exceeds the maximum limit of 50, or pagination parameters are out of range.", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or x-secret-key for backend usage.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or `x-secret-key` for backend usage.", status_, responseText_, headers_, null); } else if (status_ == 404) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Wallet not found or no transactions available for the specified wallet address on the given blockchain networks.", status_, responseText_, headers_, null); + throw new ApiException("Wallet not found or no transactions available for the specified wallet address on the given blockchain networks.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to network connectivity issues, external service unavailability, or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to network connectivity issues, external service unavailability, or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -1294,7 +1570,7 @@ public virtual async System.Threading.Tasks.Task GetWalletTransaction /// Get Tokens /// /// - /// Retrieves token balances for a specific wallet address across one or more blockchain networks. This endpoint provides comprehensive token data including ERC-20 tokens with their balances, metadata, and price information. Results can be filtered by chain and paginated to meet specific requirements. + /// Retrieves token balances for a specific wallet address across one or more blockchain networks. This endpoint provides comprehensive token data including ERC-20 tokens with their balances, metadata, and price information. Results can be filtered by chain, sorted by balance or USD value, and customized to include/exclude spam tokens, native tokens, and tokens without price data. Supports pagination and metadata resolution options. ///
///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. ///
@@ -1303,11 +1579,18 @@ public virtual async System.Threading.Tasks.Task GetWalletTransaction /// Token addresses to filter by. If provided, only tokens with these addresses will be returned. /// The number of tokens to return per chain (default: 20, max: 500). /// The page number for pagination (default: 1, max: 20). - /// Wallet tokens retrieved successfully. Returns token data with metadata including pagination information and chain details. Includes token balances, metadata, and price information when available. - /// A server side error occurred. - public virtual System.Threading.Tasks.Task GetWalletTokensAsync(string address, System.Collections.Generic.IEnumerable chainId, System.Collections.Generic.IEnumerable tokenAddresses, int? limit, int? page) + /// Whether to include token metadata (default: true). + /// Whether to resolve metadata links to fetch additional token information (default: true). + /// Whether to include tokens marked as spam (default: false). + /// Whether to include native tokens (e.g., ETH, MATIC) in the results (default: true). + /// Field to sort tokens by: 'balance' for token balance, 'token_address' for token address, 'token_price' for token price, 'usd_value' for USD value (default: usd_value). + /// Sort order: 'asc' for ascending, 'desc' for descending (default: desc). + /// Whether to include tokens without price data (default: true). + /// Wallet tokens retrieved successfully. Returns token data with metadata including pagination information and chain details. Includes token balances, metadata, and price information when available. Results are sorted by the specified criteria (default: USD value descending) and filtered according to the provided parameters. + /// A server side error occurred. + public virtual System.Threading.Tasks.Task GetWalletTokensAsync(string address, System.Collections.Generic.IEnumerable chainId, System.Collections.Generic.IEnumerable tokenAddresses, int? limit, int? page, Metadata? metadata, ResolveMetadataLinks? resolveMetadataLinks, IncludeSpam? includeSpam, IncludeNative? includeNative, SortBy? sortBy, SortOrder2? sortOrder, IncludeWithoutPrice? includeWithoutPrice) { - return GetWalletTokensAsync(address, chainId, tokenAddresses, limit, page, System.Threading.CancellationToken.None); + return GetWalletTokensAsync(address, chainId, tokenAddresses, limit, page, metadata, resolveMetadataLinks, includeSpam, includeNative, sortBy, sortOrder, includeWithoutPrice, System.Threading.CancellationToken.None); } /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. @@ -1315,7 +1598,7 @@ public virtual System.Threading.Tasks.Task GetWalletTokensAsync(stri /// Get Tokens /// /// - /// Retrieves token balances for a specific wallet address across one or more blockchain networks. This endpoint provides comprehensive token data including ERC-20 tokens with their balances, metadata, and price information. Results can be filtered by chain and paginated to meet specific requirements. + /// Retrieves token balances for a specific wallet address across one or more blockchain networks. This endpoint provides comprehensive token data including ERC-20 tokens with their balances, metadata, and price information. Results can be filtered by chain, sorted by balance or USD value, and customized to include/exclude spam tokens, native tokens, and tokens without price data. Supports pagination and metadata resolution options. ///
///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. ///
@@ -1324,9 +1607,16 @@ public virtual System.Threading.Tasks.Task GetWalletTokensAsync(stri /// Token addresses to filter by. If provided, only tokens with these addresses will be returned. /// The number of tokens to return per chain (default: 20, max: 500). /// The page number for pagination (default: 1, max: 20). - /// Wallet tokens retrieved successfully. Returns token data with metadata including pagination information and chain details. Includes token balances, metadata, and price information when available. - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task GetWalletTokensAsync(string address, System.Collections.Generic.IEnumerable chainId, System.Collections.Generic.IEnumerable tokenAddresses, int? limit, int? page, System.Threading.CancellationToken cancellationToken) + /// Whether to include token metadata (default: true). + /// Whether to resolve metadata links to fetch additional token information (default: true). + /// Whether to include tokens marked as spam (default: false). + /// Whether to include native tokens (e.g., ETH, MATIC) in the results (default: true). + /// Field to sort tokens by: 'balance' for token balance, 'token_address' for token address, 'token_price' for token price, 'usd_value' for USD value (default: usd_value). + /// Sort order: 'asc' for ascending, 'desc' for descending (default: desc). + /// Whether to include tokens without price data (default: true). + /// Wallet tokens retrieved successfully. Returns token data with metadata including pagination information and chain details. Includes token balances, metadata, and price information when available. Results are sorted by the specified criteria (default: USD value descending) and filtered according to the provided parameters. + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task GetWalletTokensAsync(string address, System.Collections.Generic.IEnumerable chainId, System.Collections.Generic.IEnumerable tokenAddresses, int? limit, int? page, Metadata? metadata, ResolveMetadataLinks? resolveMetadataLinks, IncludeSpam? includeSpam, IncludeNative? includeNative, SortBy? sortBy, SortOrder2? sortOrder, IncludeWithoutPrice? includeWithoutPrice, System.Threading.CancellationToken cancellationToken) { if (address == null) throw new System.ArgumentNullException("address"); @@ -1375,6 +1665,34 @@ public virtual async System.Threading.Tasks.Task GetWalletTokensAsyn { urlBuilder_.Append(System.Uri.EscapeDataString("page")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(page, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); } + if (metadata != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("metadata")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(metadata, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (resolveMetadataLinks != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("resolveMetadataLinks")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(resolveMetadataLinks, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (includeSpam != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("includeSpam")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(includeSpam, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (includeNative != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("includeNative")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(includeNative, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (sortBy != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("sortBy")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(sortBy, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (sortOrder != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("sortOrder")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(sortOrder, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (includeWithoutPrice != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("includeWithoutPrice")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(includeWithoutPrice, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } urlBuilder_.Length--; PrepareRequest(client_, request_, urlBuilder_); @@ -1405,7 +1723,7 @@ public virtual async System.Threading.Tasks.Task GetWalletTokensAsyn var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -1413,30 +1731,30 @@ public virtual async System.Threading.Tasks.Task GetWalletTokensAsyn if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters. This occurs when the wallet address format is invalid, chainId array is empty or exceeds the maximum limit of 50, or pagination parameters are out of range.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters. This occurs when the wallet address format is invalid, chainId array is empty or exceeds the maximum limit of 50, or pagination parameters are out of range.", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or x-secret-key for backend usage.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or `x-secret-key` for backend usage.", status_, responseText_, headers_, null); } else if (status_ == 404) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Wallet not found or no tokens available for the specified wallet address on the given blockchain networks.", status_, responseText_, headers_, null); + throw new ApiException("Wallet not found or no tokens available for the specified wallet address on the given blockchain networks.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to network connectivity issues, external service unavailability, or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to network connectivity issues, external service unavailability, or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -1467,7 +1785,7 @@ public virtual async System.Threading.Tasks.Task GetWalletTokensAsyn /// The number of NFTs to return per chain (default: 20, max: 500). /// The page number for pagination (default: 1, max: 20). /// Wallet NFTs retrieved successfully. Returns NFT data with metadata including pagination information and chain details. Includes NFT metadata, attributes, and collection information when available. - /// A server side error occurred. + /// A server side error occurred. public virtual System.Threading.Tasks.Task GetWalletNFTsAsync(string address, System.Collections.Generic.IEnumerable chainId, System.Collections.Generic.IEnumerable contractAddresses, int? limit, int? page) { return GetWalletNFTsAsync(address, chainId, contractAddresses, limit, page, System.Threading.CancellationToken.None); @@ -1488,7 +1806,7 @@ public virtual System.Threading.Tasks.Task GetWalletNFTsAsync(string /// The number of NFTs to return per chain (default: 20, max: 500). /// The page number for pagination (default: 1, max: 20). /// Wallet NFTs retrieved successfully. Returns NFT data with metadata including pagination information and chain details. Includes NFT metadata, attributes, and collection information when available. - /// A server side error occurred. + /// A server side error occurred. public virtual async System.Threading.Tasks.Task GetWalletNFTsAsync(string address, System.Collections.Generic.IEnumerable chainId, System.Collections.Generic.IEnumerable contractAddresses, int? limit, int? page, System.Threading.CancellationToken cancellationToken) { if (address == null) @@ -1568,7 +1886,7 @@ public virtual async System.Threading.Tasks.Task GetWalletNFTsAsync( var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -1576,30 +1894,30 @@ public virtual async System.Threading.Tasks.Task GetWalletNFTsAsync( if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters. This occurs when the wallet address format is invalid, chainId array is empty or exceeds the maximum limit of 50, or pagination parameters are out of range.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters. This occurs when the wallet address format is invalid, chainId array is empty or exceeds the maximum limit of 50, or pagination parameters are out of range.", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or x-secret-key for backend usage.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or `x-secret-key` for backend usage.", status_, responseText_, headers_, null); } else if (status_ == 404) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Wallet not found or no NFTs available for the specified wallet address on the given blockchain networks.", status_, responseText_, headers_, null); + throw new ApiException("Wallet not found or no NFTs available for the specified wallet address on the given blockchain networks.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to network connectivity issues, external service unavailability, or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to network connectivity issues, external service unavailability, or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -1625,7 +1943,7 @@ public virtual async System.Threading.Tasks.Task GetWalletNFTsAsync( ///
**Authentication**: This endpoint requires project authentication and wallet authentication. For backend usage, use `x-secret-key` header. For frontend usage, use `x-client-id` + `Authorization: Bearer <jwt>` headers. /// /// Message signed successfully. Returns the cryptographic signature that can be used for verification. - /// A server side error occurred. + /// A server side error occurred. public virtual System.Threading.Tasks.Task SignMessageAsync(Body5 body) { return SignMessageAsync(body, System.Threading.CancellationToken.None); @@ -1641,7 +1959,7 @@ public virtual System.Threading.Tasks.Task SignMessageAsync(Body5 bo ///
**Authentication**: This endpoint requires project authentication and wallet authentication. For backend usage, use `x-secret-key` header. For frontend usage, use `x-client-id` + `Authorization: Bearer <jwt>` headers. /// /// Message signed successfully. Returns the cryptographic signature that can be used for verification. - /// A server side error occurred. + /// A server side error occurred. public virtual async System.Threading.Tasks.Task SignMessageAsync(Body5 body, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; @@ -1690,7 +2008,7 @@ public virtual async System.Threading.Tasks.Task SignMessageAsync(Bo var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -1698,24 +2016,24 @@ public virtual async System.Threading.Tasks.Task SignMessageAsync(Bo if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters. This occurs when the wallet address format is invalid, chainId is not supported, or the message format is incorrect.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters. This occurs when the wallet address format is invalid, chainId is not supported, or the message format is incorrect.", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` + `Authorization: Bearer ` headers.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` + `Authorization: Bearer ` headers.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to wallet connectivity issues, signing service unavailability, or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to wallet connectivity issues, signing service unavailability, or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -1741,7 +2059,7 @@ public virtual async System.Threading.Tasks.Task SignMessageAsync(Bo ///
**Authentication**: This endpoint requires project authentication and wallet authentication. For backend usage, use `x-secret-key` header. For frontend usage, use `x-client-id` + `Authorization: Bearer <jwt>` headers. /// /// Typed data signed successfully. Returns the EIP-712 compliant signature that can be used for on-chain verification. - /// A server side error occurred. + /// A server side error occurred. public virtual System.Threading.Tasks.Task SignTypedDataAsync(Body6 body) { return SignTypedDataAsync(body, System.Threading.CancellationToken.None); @@ -1757,7 +2075,7 @@ public virtual System.Threading.Tasks.Task SignTypedDataAsync(Body6 ///
**Authentication**: This endpoint requires project authentication and wallet authentication. For backend usage, use `x-secret-key` header. For frontend usage, use `x-client-id` + `Authorization: Bearer <jwt>` headers. /// /// Typed data signed successfully. Returns the EIP-712 compliant signature that can be used for on-chain verification. - /// A server side error occurred. + /// A server side error occurred. public virtual async System.Threading.Tasks.Task SignTypedDataAsync(Body6 body, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; @@ -1806,7 +2124,7 @@ public virtual async System.Threading.Tasks.Task SignTypedDataAsync( var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -1814,24 +2132,24 @@ public virtual async System.Threading.Tasks.Task SignTypedDataAsync( if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters. This occurs when the typed data structure is malformed, domain parameters are incorrect, or wallet address format is invalid.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters. This occurs when the typed data structure is malformed, domain parameters are incorrect, or wallet address format is invalid.", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include valid `x-wallet-access-token` headers for accessing the wallet, as well as a x-client-id (frontend) or x-secret-key (backend) for project authentication.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. The request must include valid `x-wallet-access-token` headers for accessing the wallet, as well as a x-client-id (frontend) or x-secret-key (backend) for project authentication.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to wallet connectivity issues, signing service unavailability, or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to wallet connectivity issues, signing service unavailability, or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -1863,7 +2181,7 @@ public virtual async System.Threading.Tasks.Task SignTypedDataAsync( ///
**Authentication**: This endpoint requires project authentication and wallet authentication. For backend usage, use `x-secret-key` header. For frontend usage, use `x-client-id` + `Authorization: Bearer <jwt>` headers. /// /// Tokens sent successfully. Returns transaction IDs for tracking and monitoring. - /// A server side error occurred. + /// A server side error occurred. public virtual System.Threading.Tasks.Task SendTokensAsync(Body7 body) { return SendTokensAsync(body, System.Threading.CancellationToken.None); @@ -1885,7 +2203,7 @@ public virtual System.Threading.Tasks.Task SendTokensAsync(Body7 bod ///
**Authentication**: This endpoint requires project authentication and wallet authentication. For backend usage, use `x-secret-key` header. For frontend usage, use `x-client-id` + `Authorization: Bearer <jwt>` headers. /// /// Tokens sent successfully. Returns transaction IDs for tracking and monitoring. - /// A server side error occurred. + /// A server side error occurred. public virtual async System.Threading.Tasks.Task SendTokensAsync(Body7 body, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; @@ -1934,7 +2252,7 @@ public virtual async System.Threading.Tasks.Task SendTokensAsync(Bod var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -1942,24 +2260,24 @@ public virtual async System.Threading.Tasks.Task SendTokensAsync(Bod if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters. This occurs when token parameters are malformed, insufficient balance, invalid contract data, or unsupported token type.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters. This occurs when token parameters are malformed, insufficient balance, invalid contract data, or unsupported token type.", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` + `Authorization: Bearer ` headers.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` + `Authorization: Bearer ` headers.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to blockchain connectivity issues, gas estimation failures, contract execution errors, or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to blockchain connectivity issues, gas estimation failures, contract execution errors, or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -1989,7 +2307,7 @@ public virtual async System.Threading.Tasks.Task SendTokensAsync(Bod /// The number of contracts to return (default: 20, max: 100). /// The page number for pagination (default: 1). /// Successfully retrieved list of contracts - /// A server side error occurred. + /// A server side error occurred. public virtual System.Threading.Tasks.Task ListContractsAsync(int? limit, int? page) { return ListContractsAsync(limit, page, System.Threading.CancellationToken.None); @@ -2009,7 +2327,7 @@ public virtual System.Threading.Tasks.Task ListContractsAsync(int? l /// The number of contracts to return (default: 20, max: 100). /// The page number for pagination (default: 1). /// Successfully retrieved list of contracts - /// A server side error occurred. + /// A server side error occurred. public virtual async System.Threading.Tasks.Task ListContractsAsync(int? limit, int? page, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; @@ -2064,7 +2382,7 @@ public virtual async System.Threading.Tasks.Task ListContractsAsync( var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -2072,30 +2390,30 @@ public virtual async System.Threading.Tasks.Task ListContractsAsync( if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include a valid `x-secret-key` header for backend authentication.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. The request must include a valid `x-secret-key` header for backend authentication.", status_, responseText_, headers_, null); } else if (status_ == 429) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Rate limit exceeded", status_, responseText_, headers_, null); + throw new ApiException("Rate limit exceeded", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error", status_, responseText_, headers_, null); + throw new ApiException("Internal server error", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -2121,7 +2439,7 @@ public virtual async System.Threading.Tasks.Task ListContractsAsync( ///
**Authentication**: This endpoint requires backend authentication using the `x-secret-key` header. The secret key should never be exposed publicly. /// /// Contract deployed successfully - /// A server side error occurred. + /// A server side error occurred. public virtual System.Threading.Tasks.Task DeployContractAsync(Body8 body) { return DeployContractAsync(body, System.Threading.CancellationToken.None); @@ -2137,7 +2455,7 @@ public virtual System.Threading.Tasks.Task DeployContractAsync(Body8 ///
**Authentication**: This endpoint requires backend authentication using the `x-secret-key` header. The secret key should never be exposed publicly. /// /// Contract deployed successfully - /// A server side error occurred. + /// A server side error occurred. public virtual async System.Threading.Tasks.Task DeployContractAsync(Body8 body, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; @@ -2186,7 +2504,7 @@ public virtual async System.Threading.Tasks.Task DeployContractAsync var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -2194,30 +2512,30 @@ public virtual async System.Threading.Tasks.Task DeployContractAsync if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include a valid `x-secret-key` header for backend authentication.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. The request must include a valid `x-secret-key` header for backend authentication.", status_, responseText_, headers_, null); } else if (status_ == 429) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Rate limit exceeded", status_, responseText_, headers_, null); + throw new ApiException("Rate limit exceeded", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error", status_, responseText_, headers_, null); + throw new ApiException("Internal server error", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -2243,7 +2561,7 @@ public virtual async System.Threading.Tasks.Task DeployContractAsync ///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. /// /// Contract read operations completed successfully. Returns an array of results corresponding to each input call, including both successful and failed operations. - /// A server side error occurred. + /// A server side error occurred. public virtual System.Threading.Tasks.Task ReadContractAsync(Body9 body) { return ReadContractAsync(body, System.Threading.CancellationToken.None); @@ -2259,7 +2577,7 @@ public virtual System.Threading.Tasks.Task ReadContractAsync(Body9 b ///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. /// /// Contract read operations completed successfully. Returns an array of results corresponding to each input call, including both successful and failed operations. - /// A server side error occurred. + /// A server side error occurred. public virtual async System.Threading.Tasks.Task ReadContractAsync(Body9 body, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; @@ -2308,7 +2626,7 @@ public virtual async System.Threading.Tasks.Task ReadContractAsync(B var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -2316,24 +2634,24 @@ public virtual async System.Threading.Tasks.Task ReadContractAsync(B if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters. This occurs when the chainId is not supported, contract addresses are invalid, function signatures are malformed, or the calls array is empty.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters. This occurs when the chainId is not supported, contract addresses are invalid, function signatures are malformed, or the calls array is empty.", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or x-secret-key for backend usage.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or `x-secret-key` for backend usage.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to engine connectivity issues, RPC node unavailability, or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to engine connectivity issues, RPC node unavailability, or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -2359,7 +2677,7 @@ public virtual async System.Threading.Tasks.Task ReadContractAsync(B ///
**Authentication**: This endpoint requires project authentication and wallet authentication. For backend usage, use `x-secret-key` header. For frontend usage, use `x-client-id` + `Authorization: Bearer <jwt>` headers. /// /// Contract write operations submitted successfully. Returns transaction IDs for tracking and monitoring. - /// A server side error occurred. + /// A server side error occurred. public virtual System.Threading.Tasks.Task WriteContractAsync(Body10 body) { return WriteContractAsync(body, System.Threading.CancellationToken.None); @@ -2375,7 +2693,7 @@ public virtual System.Threading.Tasks.Task WriteContractAsync(Body10 ///
**Authentication**: This endpoint requires project authentication and wallet authentication. For backend usage, use `x-secret-key` header. For frontend usage, use `x-client-id` + `Authorization: Bearer <jwt>` headers. /// /// Contract write operations submitted successfully. Returns transaction IDs for tracking and monitoring. - /// A server side error occurred. + /// A server side error occurred. public virtual async System.Threading.Tasks.Task WriteContractAsync(Body10 body, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; @@ -2424,7 +2742,7 @@ public virtual async System.Threading.Tasks.Task WriteContractAsync( var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -2432,30 +2750,40 @@ public virtual async System.Threading.Tasks.Task WriteContractAsync( if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters. This occurs when contract parameters are malformed, method signatures are invalid, insufficient balance, or unsupported contract methods.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters. This occurs when contract parameters are malformed, method signatures are invalid, insufficient balance, or unsupported contract methods.", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` + `Authorization: Bearer ` headers.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` + `Authorization: Bearer ` headers.", status_, responseText_, headers_, null); + } + else + if (status_ == 402) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new ApiException("Payment required. Insufficient wallet balance to complete the purchase.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else if (status_ == 404) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Contract not found. The specified contract address does not exist on the given blockchain network or is not accessible.", status_, responseText_, headers_, null); + throw new ApiException("Contract not found. The specified contract address does not exist on the given blockchain network or is not accessible.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to blockchain connectivity issues, gas estimation failures, contract execution errors, or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to blockchain connectivity issues, gas estimation failures, contract execution errors, or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -2494,8 +2822,8 @@ public virtual async System.Threading.Tasks.Task WriteContractAsync( /// Number of items per page /// Sort order: 'asc' for ascending, 'desc' for descending /// Contract transactions retrieved successfully. Returns transaction data with metadata including pagination information. Includes decoded function calls when ABI is available. - /// A server side error occurred. - public virtual System.Threading.Tasks.Task GetContractTransactionsAsync(int chainId, string address, string filterFromAddress, string filterToAddress, int? filterBlockTimestampGte, int? filterBlockTimestampLte, int? filterBlockNumberGte, int? filterBlockNumberLte, string filterValueGt, string filterFunctionSelector, double? page, double? limit, SortOrder2? sortOrder) + /// A server side error occurred. + public virtual System.Threading.Tasks.Task GetContractTransactionsAsync(int chainId, string address, string filterFromAddress, string filterToAddress, int? filterBlockTimestampGte, int? filterBlockTimestampLte, int? filterBlockNumberGte, int? filterBlockNumberLte, string filterValueGt, string filterFunctionSelector, double? page, double? limit, SortOrder3? sortOrder) { return GetContractTransactionsAsync(chainId, address, filterFromAddress, filterToAddress, filterBlockTimestampGte, filterBlockTimestampLte, filterBlockNumberGte, filterBlockNumberLte, filterValueGt, filterFunctionSelector, page, limit, sortOrder, System.Threading.CancellationToken.None); } @@ -2523,8 +2851,8 @@ public virtual System.Threading.Tasks.Task GetContractTransactionsAs /// Number of items per page /// Sort order: 'asc' for ascending, 'desc' for descending /// Contract transactions retrieved successfully. Returns transaction data with metadata including pagination information. Includes decoded function calls when ABI is available. - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task GetContractTransactionsAsync(int chainId, string address, string filterFromAddress, string filterToAddress, int? filterBlockTimestampGte, int? filterBlockTimestampLte, int? filterBlockNumberGte, int? filterBlockNumberLte, string filterValueGt, string filterFunctionSelector, double? page, double? limit, SortOrder2? sortOrder, System.Threading.CancellationToken cancellationToken) + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task GetContractTransactionsAsync(int chainId, string address, string filterFromAddress, string filterToAddress, int? filterBlockTimestampGte, int? filterBlockTimestampLte, int? filterBlockNumberGte, int? filterBlockNumberLte, string filterValueGt, string filterFunctionSelector, double? page, double? limit, SortOrder3? sortOrder, System.Threading.CancellationToken cancellationToken) { if (chainId == null) throw new System.ArgumentNullException("chainId"); @@ -2621,10 +2949,10 @@ public virtual async System.Threading.Tasks.Task GetContractTransact var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -2632,30 +2960,30 @@ public virtual async System.Threading.Tasks.Task GetContractTransact if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters. This occurs when the contract address or chainId format is invalid, or pagination parameters are out of range.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters. This occurs when the contract address or chainId format is invalid, or pagination parameters are out of range.", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or x-secret-key for backend usage.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or `x-secret-key` for backend usage.", status_, responseText_, headers_, null); } else if (status_ == 404) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Contract not found or no transactions available for the specified contract address on the given blockchain network.", status_, responseText_, headers_, null); + throw new ApiException("Contract not found or no transactions available for the specified contract address on the given blockchain network.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to network connectivity issues, external service unavailability, or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to network connectivity issues, external service unavailability, or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -2695,8 +3023,8 @@ public virtual async System.Threading.Tasks.Task GetContractTransact /// Number of items per page /// Sort order: 'asc' for ascending, 'desc' for descending /// Contract events retrieved successfully. Returns event data with metadata including pagination information. Includes decoded event parameters when ABI is available. - /// A server side error occurred. - public virtual System.Threading.Tasks.Task GetContractEventsAsync(int chainId, string address, string signature, string filterTopic0, string filterTopic1, string filterTopic2, string filterTopic3, int? filterBlockTimestampGte, int? filterBlockTimestampLte, int? filterBlockNumberGte, int? filterBlockNumberLte, double? page, double? limit, SortOrder3? sortOrder) + /// A server side error occurred. + public virtual System.Threading.Tasks.Task GetContractEventsAsync(int chainId, string address, string signature, string filterTopic0, string filterTopic1, string filterTopic2, string filterTopic3, int? filterBlockTimestampGte, int? filterBlockTimestampLte, int? filterBlockNumberGte, int? filterBlockNumberLte, double? page, double? limit, SortOrder4? sortOrder) { return GetContractEventsAsync(chainId, address, signature, filterTopic0, filterTopic1, filterTopic2, filterTopic3, filterBlockTimestampGte, filterBlockTimestampLte, filterBlockNumberGte, filterBlockNumberLte, page, limit, sortOrder, System.Threading.CancellationToken.None); } @@ -2725,8 +3053,8 @@ public virtual System.Threading.Tasks.Task GetContractEventsAsync(in /// Number of items per page /// Sort order: 'asc' for ascending, 'desc' for descending /// Contract events retrieved successfully. Returns event data with metadata including pagination information. Includes decoded event parameters when ABI is available. - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task GetContractEventsAsync(int chainId, string address, string signature, string filterTopic0, string filterTopic1, string filterTopic2, string filterTopic3, int? filterBlockTimestampGte, int? filterBlockTimestampLte, int? filterBlockNumberGte, int? filterBlockNumberLte, double? page, double? limit, SortOrder3? sortOrder, System.Threading.CancellationToken cancellationToken) + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task GetContractEventsAsync(int chainId, string address, string signature, string filterTopic0, string filterTopic1, string filterTopic2, string filterTopic3, int? filterBlockTimestampGte, int? filterBlockTimestampLte, int? filterBlockNumberGte, int? filterBlockNumberLte, double? page, double? limit, SortOrder4? sortOrder, System.Threading.CancellationToken cancellationToken) { if (chainId == null) throw new System.ArgumentNullException("chainId"); @@ -2827,10 +3155,10 @@ public virtual async System.Threading.Tasks.Task GetContractEventsAs var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -2838,30 +3166,30 @@ public virtual async System.Threading.Tasks.Task GetContractEventsAs if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters. This occurs when the contract address or chainId format is invalid, or pagination parameters are out of range.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters. This occurs when the contract address or chainId format is invalid, or pagination parameters are out of range.", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or x-secret-key for backend usage.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or `x-secret-key` for backend usage.", status_, responseText_, headers_, null); } else if (status_ == 404) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Contract not found or no events available for the specified contract address on the given blockchain network.", status_, responseText_, headers_, null); + throw new ApiException("Contract not found or no events available for the specified contract address on the given blockchain network.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to network connectivity issues, external service unavailability, or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to network connectivity issues, external service unavailability, or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -2891,8 +3219,8 @@ public virtual async System.Threading.Tasks.Task GetContractEventsAs /// The blockchain network identifier where the contract is deployed. /// The smart contract address or ENS name. /// Successfully retrieved contract metadata - /// A server side error occurred. - public virtual System.Threading.Tasks.Task GetContractMetadataAsync(int chainId, string address) + /// A server side error occurred. + public virtual System.Threading.Tasks.Task GetContractMetadataAsync(int chainId, string address) { return GetContractMetadataAsync(chainId, address, System.Threading.CancellationToken.None); } @@ -2911,8 +3239,8 @@ public virtual System.Threading.Tasks.Task GetContractMetadataAsync( /// The blockchain network identifier where the contract is deployed. /// The smart contract address or ENS name. /// Successfully retrieved contract metadata - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task GetContractMetadataAsync(int chainId, string address, System.Threading.CancellationToken cancellationToken) + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task GetContractMetadataAsync(int chainId, string address, System.Threading.CancellationToken cancellationToken) { if (chainId == null) throw new System.ArgumentNullException("chainId"); @@ -2963,10 +3291,10 @@ public virtual async System.Threading.Tasks.Task GetContractMetadata var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -2974,36 +3302,36 @@ public virtual async System.Threading.Tasks.Task GetContractMetadata if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include a valid `x-secret-key` header for backend authentication.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. The request must include a valid `x-secret-key` header for backend authentication.", status_, responseText_, headers_, null); } else if (status_ == 404) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Contract metadata not found", status_, responseText_, headers_, null); + throw new ApiException("Contract metadata not found", status_, responseText_, headers_, null); } else if (status_ == 429) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Rate limit exceeded", status_, responseText_, headers_, null); + throw new ApiException("Rate limit exceeded", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error", status_, responseText_, headers_, null); + throw new ApiException("Internal server error", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -3033,8 +3361,8 @@ public virtual async System.Threading.Tasks.Task GetContractMetadata /// The blockchain network identifier where the contract is deployed. /// The smart contract address or ENS name. /// Successfully retrieved contract signatures - /// A server side error occurred. - public virtual System.Threading.Tasks.Task GetContractSignaturesAsync(int chainId, string address) + /// A server side error occurred. + public virtual System.Threading.Tasks.Task GetContractSignaturesAsync(int chainId, string address) { return GetContractSignaturesAsync(chainId, address, System.Threading.CancellationToken.None); } @@ -3053,8 +3381,8 @@ public virtual System.Threading.Tasks.Task GetContractSignaturesAsyn /// The blockchain network identifier where the contract is deployed. /// The smart contract address or ENS name. /// Successfully retrieved contract signatures - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task GetContractSignaturesAsync(int chainId, string address, System.Threading.CancellationToken cancellationToken) + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task GetContractSignaturesAsync(int chainId, string address, System.Threading.CancellationToken cancellationToken) { if (chainId == null) throw new System.ArgumentNullException("chainId"); @@ -3105,10 +3433,10 @@ public virtual async System.Threading.Tasks.Task GetContractSignatur var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -3116,36 +3444,36 @@ public virtual async System.Threading.Tasks.Task GetContractSignatur if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include a valid `x-secret-key` header for backend authentication.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. The request must include a valid `x-secret-key` header for backend authentication.", status_, responseText_, headers_, null); } else if (status_ == 404) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Contract metadata not found or ABI is not available", status_, responseText_, headers_, null); + throw new ApiException("Contract metadata not found or ABI is not available", status_, responseText_, headers_, null); } else if (status_ == 429) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Rate limit exceeded", status_, responseText_, headers_, null); + throw new ApiException("Rate limit exceeded", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error", status_, responseText_, headers_, null); + throw new ApiException("Internal server error", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -3172,8 +3500,8 @@ public virtual async System.Threading.Tasks.Task GetContractSignatur /// /// Unique identifier of the transaction to retrieve. /// Transaction details retrieved successfully. Returns comprehensive transaction information including status, blockchain details, and execution metadata. - /// A server side error occurred. - public virtual System.Threading.Tasks.Task GetTransactionByIdAsync(string transactionId) + /// A server side error occurred. + public virtual System.Threading.Tasks.Task GetTransactionByIdAsync(string transactionId) { return GetTransactionByIdAsync(transactionId, System.Threading.CancellationToken.None); } @@ -3189,8 +3517,8 @@ public virtual System.Threading.Tasks.Task GetTransactionByIdAsync(s /// /// Unique identifier of the transaction to retrieve. /// Transaction details retrieved successfully. Returns comprehensive transaction information including status, blockchain details, and execution metadata. - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task GetTransactionByIdAsync(string transactionId, System.Threading.CancellationToken cancellationToken) + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task GetTransactionByIdAsync(string transactionId, System.Threading.CancellationToken cancellationToken) { if (transactionId == null) throw new System.ArgumentNullException("transactionId"); @@ -3235,10 +3563,10 @@ public virtual async System.Threading.Tasks.Task GetTransactionByIdA var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -3246,30 +3574,30 @@ public virtual async System.Threading.Tasks.Task GetTransactionByIdA if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters. This occurs when the transaction ID format is invalid or malformed.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters. This occurs when the transaction ID format is invalid or malformed.", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or x-secret-key for backend usage.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or `x-secret-key` for backend usage.", status_, responseText_, headers_, null); } else if (status_ == 404) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Transaction not found. The specified transaction ID does not exist or is not associated with the authenticated client.", status_, responseText_, headers_, null); + throw new ApiException("Transaction not found. The specified transaction ID does not exist or is not associated with the authenticated client.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to engine connectivity issues, database unavailability, or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to engine connectivity issues, database unavailability, or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -3298,8 +3626,8 @@ public virtual async System.Threading.Tasks.Task GetTransactionByIdA /// Number of transactions to return per page (1-100). /// Page number for pagination, starting from 1. /// Transactions retrieved successfully. Returns a paginated list of transactions with metadata including creation and confirmation timestamps. - /// A server side error occurred. - public virtual System.Threading.Tasks.Task ListTransactionsAsync(string from, int? limit, int? page) + /// A server side error occurred. + public virtual System.Threading.Tasks.Task ListTransactionsAsync(string from, int? limit, int? page) { return ListTransactionsAsync(from, limit, page, System.Threading.CancellationToken.None); } @@ -3317,8 +3645,8 @@ public virtual System.Threading.Tasks.Task ListTransactionsAsync(str /// Number of transactions to return per page (1-100). /// Page number for pagination, starting from 1. /// Transactions retrieved successfully. Returns a paginated list of transactions with metadata including creation and confirmation timestamps. - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task ListTransactionsAsync(string from, int? limit, int? page, System.Threading.CancellationToken cancellationToken) + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task ListTransactionsAsync(string from, int? limit, int? page, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; var disposeClient_ = false; @@ -3373,10 +3701,10 @@ public virtual async System.Threading.Tasks.Task ListTransactionsAsy var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -3384,24 +3712,24 @@ public virtual async System.Threading.Tasks.Task ListTransactionsAsy if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters. This occurs when pagination parameters are out of range or wallet address format is invalid.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters. This occurs when pagination parameters are out of range or wallet address format is invalid.", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or x-secret-key for backend usage.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or `x-secret-key` for backend usage.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to engine connectivity issues, database unavailability, or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to engine connectivity issues, database unavailability, or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -3427,8 +3755,8 @@ public virtual async System.Threading.Tasks.Task ListTransactionsAsy ///
**Authentication**: This endpoint requires project authentication and wallet authentication. For backend usage, use `x-secret-key` header. For frontend usage, use `x-client-id` + `Authorization: Bearer <jwt>` headers. /// /// Encoded transactions submitted successfully. Returns the transaction IDs for tracking and monitoring. - /// A server side error occurred. - public virtual System.Threading.Tasks.Task SendTransactionsAsync(Body11 body) + /// A server side error occurred. + public virtual System.Threading.Tasks.Task SendTransactionsAsync(Body11 body) { return SendTransactionsAsync(body, System.Threading.CancellationToken.None); } @@ -3443,8 +3771,8 @@ public virtual System.Threading.Tasks.Task SendTransactionsAsync(Bod ///
**Authentication**: This endpoint requires project authentication and wallet authentication. For backend usage, use `x-secret-key` header. For frontend usage, use `x-client-id` + `Authorization: Bearer <jwt>` headers. /// /// Encoded transactions submitted successfully. Returns the transaction IDs for tracking and monitoring. - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task SendTransactionsAsync(Body11 body, System.Threading.CancellationToken cancellationToken) + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task SendTransactionsAsync(Body11 body, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; var disposeClient_ = false; @@ -3489,10 +3817,10 @@ public virtual async System.Threading.Tasks.Task SendTransactionsAsy var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -3500,24 +3828,34 @@ public virtual async System.Threading.Tasks.Task SendTransactionsAsy if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters. This occurs when transaction data is malformed, insufficient balance, or invalid encoded data.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters. This occurs when transaction data is malformed, insufficient balance, or invalid encoded data.", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` + `Authorization: Bearer ` headers.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` + `Authorization: Bearer ` headers.", status_, responseText_, headers_, null); + } + else + if (status_ == 402) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new ApiException("Payment required. Insufficient wallet balance to complete the purchase.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to blockchain connectivity issues, gas estimation failures, or unexpected server errors.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to blockchain connectivity issues, gas estimation failures, or unexpected server errors.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -3535,32 +3873,32 @@ public virtual async System.Threading.Tasks.Task SendTransactionsAsy } /// - /// Swap Tokens + /// Create Payment /// /// - /// Swap one token for another using the optimal route available. You can specify a tokenIn amount (if exact='input') or tokenOut amount (if exact='output'), but not both. The corresponding output or input amount will be returned as the quote. + /// Create a payment to be executed. Users can complete the payment via hosted UI (link is returned), a transaction execution referencing the product ID, or embedded widgets with the product ID. ///
- ///
**Authentication**: This endpoint requires project authentication and wallet authentication. For backend usage, use `x-secret-key` header. For frontend usage, use `x-client-id` + `Authorization: Bearer <jwt>` headers. + ///
**Authentication**: This endpoint requires project authentication. ///
- /// Swap completed successfully. Returns the transaction used for the swap. - /// A server side error occurred. - public virtual System.Threading.Tasks.Task PaymentsSwapAsync(Body12 body) + /// Payment created successfully. Returns the ID and link to complete the payment. + /// A server side error occurred. + public virtual System.Threading.Tasks.Task CreatePaymentAsync(Body12 body) { - return PaymentsSwapAsync(body, System.Threading.CancellationToken.None); + return CreatePaymentAsync(body, System.Threading.CancellationToken.None); } /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// - /// Swap Tokens + /// Create Payment /// /// - /// Swap one token for another using the optimal route available. You can specify a tokenIn amount (if exact='input') or tokenOut amount (if exact='output'), but not both. The corresponding output or input amount will be returned as the quote. + /// Create a payment to be executed. Users can complete the payment via hosted UI (link is returned), a transaction execution referencing the product ID, or embedded widgets with the product ID. ///
- ///
**Authentication**: This endpoint requires project authentication and wallet authentication. For backend usage, use `x-secret-key` header. For frontend usage, use `x-client-id` + `Authorization: Bearer <jwt>` headers. + ///
**Authentication**: This endpoint requires project authentication. ///
- /// Swap completed successfully. Returns the transaction used for the swap. - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task PaymentsSwapAsync(Body12 body, System.Threading.CancellationToken cancellationToken) + /// Payment created successfully. Returns the ID and link to complete the payment. + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task CreatePaymentAsync(Body12 body, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; var disposeClient_ = false; @@ -3577,8 +3915,8 @@ public virtual async System.Threading.Tasks.Task PaymentsSwapAsync(B var urlBuilder_ = new System.Text.StringBuilder(); if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); - // Operation Path: "v1/payments/swap" - urlBuilder_.Append("v1/payments/swap"); + // Operation Path: "v1/payments" + urlBuilder_.Append("v1/payments"); PrepareRequest(client_, request_, urlBuilder_); @@ -3605,10 +3943,10 @@ public virtual async System.Threading.Tasks.Task PaymentsSwapAsync(B var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -3616,30 +3954,24 @@ public virtual async System.Threading.Tasks.Task PaymentsSwapAsync(B if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters.", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` + `Authorization: Bearer ` headers.", status_, responseText_, headers_, null); - } - else - if (status_ == 402) - { - string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Payment required. Insufficient wallet balance to complete the purchase.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` + `Authorization: Bearer ` headers.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to network connectivity issues, wallet creation failures, or transaction execution failures.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to network connectivity issues, wallet creation failures, or transaction execution failures.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -3657,33 +3989,36 @@ public virtual async System.Threading.Tasks.Task PaymentsSwapAsync(B } /// - /// Create Payment + /// Complete Payment /// /// - /// Create a payment to be executed. Users can complete the payment via hosted UI (link is returned), a transaction execution referencing the product ID, or embedded widgets with the product ID. + /// Completes a payment using its default token and amount. If the user does not have sufficient funds in the product's default payment token a 402 status will be returned containing a link and raw quote for purchase fulfillment. ///
///
**Authentication**: This endpoint requires project authentication. ///
- /// Payment created successfully. Returns the ID and link to complete the payment. - /// A server side error occurred. - public virtual System.Threading.Tasks.Task CreatePaymentAsync(Body13 body) + /// Product purchased successfully. Returns the transaction used for the purchase. + /// A server side error occurred. + public virtual System.Threading.Tasks.Task PaymentsPurchaseAsync(string id, Body13 body) { - return CreatePaymentAsync(body, System.Threading.CancellationToken.None); + return PaymentsPurchaseAsync(id, body, System.Threading.CancellationToken.None); } /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// - /// Create Payment + /// Complete Payment /// /// - /// Create a payment to be executed. Users can complete the payment via hosted UI (link is returned), a transaction execution referencing the product ID, or embedded widgets with the product ID. + /// Completes a payment using its default token and amount. If the user does not have sufficient funds in the product's default payment token a 402 status will be returned containing a link and raw quote for purchase fulfillment. ///
///
**Authentication**: This endpoint requires project authentication. ///
- /// Payment created successfully. Returns the ID and link to complete the payment. - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task CreatePaymentAsync(Body13 body, System.Threading.CancellationToken cancellationToken) + /// Product purchased successfully. Returns the transaction used for the purchase. + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task PaymentsPurchaseAsync(string id, Body13 body, System.Threading.CancellationToken cancellationToken) { + if (id == null) + throw new System.ArgumentNullException("id"); + var client_ = _httpClient; var disposeClient_ = false; try @@ -3699,8 +4034,9 @@ public virtual async System.Threading.Tasks.Task CreatePaymentAsync( var urlBuilder_ = new System.Text.StringBuilder(); if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); - // Operation Path: "v1/payments" - urlBuilder_.Append("v1/payments"); + // Operation Path: "v1/payments/{id}" + urlBuilder_.Append("v1/payments/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(id, System.Globalization.CultureInfo.InvariantCulture))); PrepareRequest(client_, request_, urlBuilder_); @@ -3727,10 +4063,10 @@ public virtual async System.Threading.Tasks.Task CreatePaymentAsync( var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -3738,30 +4074,34 @@ public virtual async System.Threading.Tasks.Task CreatePaymentAsync( if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters.", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` + `Authorization: Bearer ` headers.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` + `Authorization: Bearer ` headers.", status_, responseText_, headers_, null); } else if (status_ == 402) { - string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Payment required. Insufficient wallet balance to complete the purchase.", status_, responseText_, headers_, null); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new ApiException("Payment required. Insufficient wallet balance to complete the purchase.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to network connectivity issues, wallet creation failures, or transaction execution failures.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error. This may occur due to network connectivity issues, wallet creation failures, or transaction execution failures.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -3779,32 +4119,28 @@ public virtual async System.Threading.Tasks.Task CreatePaymentAsync( } /// - /// Complete Payment + /// Get Payment History /// /// - /// Completes a payment using its default token and amount. If the user does not have sufficient funds in the product's default payment token a 402 status will be returned containing a link and raw quote for purchase fulfillment. - ///
- ///
**Authentication**: This endpoint requires project authentication. + /// Get payment history for a specific payment link ///
- /// Product purchased successfully. Returns the transaction used for the purchase. - /// A server side error occurred. - public virtual System.Threading.Tasks.Task PaymentsPurchaseAsync(string id, Body14 body) + /// Payment history retrieved successfully + /// A server side error occurred. + public virtual System.Threading.Tasks.Task GetPaymentHistoryAsync(string id) { - return PaymentsPurchaseAsync(id, body, System.Threading.CancellationToken.None); + return GetPaymentHistoryAsync(id, System.Threading.CancellationToken.None); } /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// - /// Complete Payment + /// Get Payment History /// /// - /// Completes a payment using its default token and amount. If the user does not have sufficient funds in the product's default payment token a 402 status will be returned containing a link and raw quote for purchase fulfillment. - ///
- ///
**Authentication**: This endpoint requires project authentication. + /// Get payment history for a specific payment link ///
- /// Product purchased successfully. Returns the transaction used for the purchase. - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task PaymentsPurchaseAsync(string id, Body14 body, System.Threading.CancellationToken cancellationToken) + /// Payment history retrieved successfully + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task GetPaymentHistoryAsync(string id, System.Threading.CancellationToken cancellationToken) { if (id == null) throw new System.ArgumentNullException("id"); @@ -3815,11 +4151,7 @@ public virtual async System.Threading.Tasks.Task PaymentsPurchaseAsy { using (var request_ = new System.Net.Http.HttpRequestMessage()) { - var json_ = Newtonsoft.Json.JsonConvert.SerializeObject(body, JsonSerializerSettings); - var content_ = new System.Net.Http.StringContent(json_); - content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); - request_.Content = content_; - request_.Method = new System.Net.Http.HttpMethod("POST"); + request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); var urlBuilder_ = new System.Text.StringBuilder(); @@ -3853,41 +4185,37 @@ public virtual async System.Threading.Tasks.Task PaymentsPurchaseAsy var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } else if (status_ == 400) { - string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters.", status_, responseText_, headers_, null); - } - else - if (status_ == 401) - { - string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` + `Authorization: Bearer ` headers.", status_, responseText_, headers_, null); - } - else - if (status_ == 402) - { - string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Payment required. Insufficient wallet balance to complete the purchase.", status_, responseText_, headers_, null); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new ApiException("Bad request", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else - if (status_ == 500) + if (status_ == 404) { - string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to network connectivity issues, wallet creation failures, or transaction execution failures.", status_, responseText_, headers_, null); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new ApiException("Payment link not found", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -3905,32 +4233,28 @@ public virtual async System.Threading.Tasks.Task PaymentsPurchaseAsy } /// - /// Create Token + /// x402 - Verify payment /// /// - /// Create a new ERC20 token with the provided metadata and starting price. The token is immediately available for purchase using thirdweb Payments. - ///
- ///
**Authentication**: This endpoint requires project authentication and wallet authentication. For backend usage, use `x-secret-key` header. For frontend usage, use `x-client-id` + `Authorization: Bearer <jwt>` headers. + /// Verify an x402 payment payload against the provided payment requirements. Compatible with any standard x402 middleware. ///
- /// Token deployed successfully. The chain ID and contract address are returned. - /// A server side error occurred. - public virtual System.Threading.Tasks.Task CreateTokenAsync(Body15 body) + /// Verification successful + /// A server side error occurred. + public virtual System.Threading.Tasks.Task FacilitatorVerifyAsync(Body14 body) { - return CreateTokenAsync(body, System.Threading.CancellationToken.None); + return FacilitatorVerifyAsync(body, System.Threading.CancellationToken.None); } /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// - /// Create Token + /// x402 - Verify payment /// /// - /// Create a new ERC20 token with the provided metadata and starting price. The token is immediately available for purchase using thirdweb Payments. - ///
- ///
**Authentication**: This endpoint requires project authentication and wallet authentication. For backend usage, use `x-secret-key` header. For frontend usage, use `x-client-id` + `Authorization: Bearer <jwt>` headers. + /// Verify an x402 payment payload against the provided payment requirements. Compatible with any standard x402 middleware. ///
- /// Token deployed successfully. The chain ID and contract address are returned. - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task CreateTokenAsync(Body15 body, System.Threading.CancellationToken cancellationToken) + /// Verification successful + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task FacilitatorVerifyAsync(Body14 body, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; var disposeClient_ = false; @@ -3947,8 +4271,8 @@ public virtual async System.Threading.Tasks.Task CreateTokenAsync(Bo var urlBuilder_ = new System.Text.StringBuilder(); if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); - // Operation Path: "v1/tokens" - urlBuilder_.Append("v1/tokens"); + // Operation Path: "v1/payments/x402/verify" + urlBuilder_.Append("v1/payments/x402/verify"); PrepareRequest(client_, request_, urlBuilder_); @@ -3975,10 +4299,10 @@ public virtual async System.Threading.Tasks.Task CreateTokenAsync(Bo var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -3986,30 +4310,24 @@ public virtual async System.Threading.Tasks.Task CreateTokenAsync(Bo if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` + `Authorization: Bearer ` headers.", status_, responseText_, headers_, null); - } - else - if (status_ == 402) - { - string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Payment required. Insufficient wallet balance to deploy the contract.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. For backend usage, include `x-secret-key` header.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to network connectivity issues, wallet creation failures, or transaction execution failures.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -4027,48 +4345,28 @@ public virtual async System.Threading.Tasks.Task CreateTokenAsync(Bo } /// - /// List Tokens + /// x402 - Settle payment /// /// - /// Lists or search existing tokens based on the provided filters. Supports querying by chain ID, token address, symbol, and/or name. - ///
- ///
- ///
- ///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. + /// Settle an x402 payment. Compatible with any standard x402 middleware. ///
- /// Number of tokens to return per page (1-100). - /// Page number for pagination, starting from 1. - /// Limit tokens to a specific chain. - /// Get a specific token by contract address - /// Limit tokens to a specific symbol. - /// Limit tokens to a specific name. - /// Tokens returned successfully. - /// A server side error occurred. - public virtual System.Threading.Tasks.Task ListTokensAsync(int? limit, int? page, int? chainId, string tokenAddress, string symbol, string name) + /// Settlement successful + /// A server side error occurred. + public virtual System.Threading.Tasks.Task FacilitatorSettleAsync(Body15 body) { - return ListTokensAsync(limit, page, chainId, tokenAddress, symbol, name, System.Threading.CancellationToken.None); + return FacilitatorSettleAsync(body, System.Threading.CancellationToken.None); } /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// - /// List Tokens + /// x402 - Settle payment /// /// - /// Lists or search existing tokens based on the provided filters. Supports querying by chain ID, token address, symbol, and/or name. - ///
- ///
- ///
- ///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. + /// Settle an x402 payment. Compatible with any standard x402 middleware. ///
- /// Number of tokens to return per page (1-100). - /// Page number for pagination, starting from 1. - /// Limit tokens to a specific chain. - /// Get a specific token by contract address - /// Limit tokens to a specific symbol. - /// Limit tokens to a specific name. - /// Tokens returned successfully. - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task ListTokensAsync(int? limit, int? page, int? chainId, string tokenAddress, string symbol, string name, System.Threading.CancellationToken cancellationToken) + /// Settlement successful + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task FacilitatorSettleAsync(Body15 body, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; var disposeClient_ = false; @@ -4076,39 +4374,17 @@ public virtual async System.Threading.Tasks.Task ListTokensAsync(int { using (var request_ = new System.Net.Http.HttpRequestMessage()) { - request_.Method = new System.Net.Http.HttpMethod("GET"); + var json_ = Newtonsoft.Json.JsonConvert.SerializeObject(body, JsonSerializerSettings); + var content_ = new System.Net.Http.StringContent(json_); + content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + request_.Content = content_; + request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); var urlBuilder_ = new System.Text.StringBuilder(); if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); - // Operation Path: "v1/tokens" - urlBuilder_.Append("v1/tokens"); - urlBuilder_.Append('?'); - if (limit != null) - { - urlBuilder_.Append(System.Uri.EscapeDataString("limit")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(limit, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); - } - if (page != null) - { - urlBuilder_.Append(System.Uri.EscapeDataString("page")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(page, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); - } - if (chainId != null) - { - urlBuilder_.Append(System.Uri.EscapeDataString("chainId")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(chainId, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); - } - if (tokenAddress != null) - { - urlBuilder_.Append(System.Uri.EscapeDataString("tokenAddress")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(tokenAddress, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); - } - if (symbol != null) - { - urlBuilder_.Append(System.Uri.EscapeDataString("symbol")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(symbol, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); - } - if (name != null) - { - urlBuilder_.Append(System.Uri.EscapeDataString("name")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(name, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); - } - urlBuilder_.Length--; + // Operation Path: "v1/payments/x402/settle" + urlBuilder_.Append("v1/payments/x402/settle"); PrepareRequest(client_, request_, urlBuilder_); @@ -4135,10 +4411,10 @@ public virtual async System.Threading.Tasks.Task ListTokensAsync(int var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } @@ -4146,24 +4422,24 @@ public virtual async System.Threading.Tasks.Task ListTokensAsync(int if (status_ == 400) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters.", status_, responseText_, headers_, null); + throw new ApiException("Invalid request parameters", status_, responseText_, headers_, null); } else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` + `Authorization: Bearer ` headers.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. For backend usage, include `x-secret-key` header.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error. This may occur due to network connectivity issues, wallet creation failures, or transaction execution failures.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -4181,47 +4457,29 @@ public virtual async System.Threading.Tasks.Task ListTokensAsync(int } /// - /// Get Owners + /// x402 - Supported payment methods /// /// - /// Retrieves a paginated list of owners for a given ERC-20 token contract on a specific chain. - ///
- ///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. + /// List supported x402 payment methods. Compatible with any standard x402 middleware. ///
- /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). - /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). - /// Number of owners to return per page (1-100). - /// Page number for pagination, starting from 1. - /// Token owners retrieved successfully. Returns owners with pagination information. - /// A server side error occurred. - public virtual System.Threading.Tasks.Task GetTokenOwnersAsync(int chainId, string address, int? limit, int? page) + /// Supported payment kinds + /// A server side error occurred. + public virtual System.Threading.Tasks.Task FacilitatorSupportedAsync() { - return GetTokenOwnersAsync(chainId, address, limit, page, System.Threading.CancellationToken.None); + return FacilitatorSupportedAsync(System.Threading.CancellationToken.None); } /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// - /// Get Owners + /// x402 - Supported payment methods /// /// - /// Retrieves a paginated list of owners for a given ERC-20 token contract on a specific chain. - ///
- ///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. + /// List supported x402 payment methods. Compatible with any standard x402 middleware. ///
- /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). - /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). - /// Number of owners to return per page (1-100). - /// Page number for pagination, starting from 1. - /// Token owners retrieved successfully. Returns owners with pagination information. - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task GetTokenOwnersAsync(int chainId, string address, int? limit, int? page, System.Threading.CancellationToken cancellationToken) + /// Supported payment kinds + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task FacilitatorSupportedAsync(System.Threading.CancellationToken cancellationToken) { - if (chainId == null) - throw new System.ArgumentNullException("chainId"); - - if (address == null) - throw new System.ArgumentNullException("address"); - var client_ = _httpClient; var disposeClient_ = false; try @@ -4233,22 +4491,8 @@ public virtual async System.Threading.Tasks.Task GetTokenOwnersAsync var urlBuilder_ = new System.Text.StringBuilder(); if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); - // Operation Path: "v1/tokens/{chainId}/{address}/owners" - urlBuilder_.Append("v1/tokens/"); - urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(chainId, System.Globalization.CultureInfo.InvariantCulture))); - urlBuilder_.Append('/'); - urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(address, System.Globalization.CultureInfo.InvariantCulture))); - urlBuilder_.Append("/owners"); - urlBuilder_.Append('?'); - if (limit != null) - { - urlBuilder_.Append(System.Uri.EscapeDataString("limit")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(limit, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); - } - if (page != null) - { - urlBuilder_.Append(System.Uri.EscapeDataString("page")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(page, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); - } - urlBuilder_.Length--; + // Operation Path: "v1/payments/x402/supported" + urlBuilder_.Append("v1/payments/x402/supported"); PrepareRequest(client_, request_, urlBuilder_); @@ -4275,41 +4519,29 @@ public virtual async System.Threading.Tasks.Task GetTokenOwnersAsync var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } else - if (status_ == 400) - { - string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Invalid request parameters.", status_, responseText_, headers_, null); - } - else if (status_ == 401) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or x-secret-key for backend usage.", status_, responseText_, headers_, null); - } - else - if (status_ == 404) - { - string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Token not found or no owners available.", status_, responseText_, headers_, null); + throw new ApiException("Authentication required. For backend usage, include `x-secret-key` header.", status_, responseText_, headers_, null); } else if (status_ == 500) { string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("Internal server error.", status_, responseText_, headers_, null); + throw new ApiException("Internal server error", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -4327,40 +4559,32 @@ public virtual async System.Threading.Tasks.Task GetTokenOwnersAsync } /// - /// Chat + /// Create Token /// /// - /// Thirdweb AI chat completion API (BETA). - ///
- ///
Send natural language queries to interact with any EVM chain, read data, prepare transactions, swap tokens, deploy contracts, payments and more. - ///
- ///
+ /// Create a new ERC20 token with the provided metadata and starting price. The token is immediately available for purchase using thirdweb Payments. ///
- ///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. + ///
**Authentication**: This endpoint requires project authentication and wallet authentication. For backend usage, use `x-secret-key` header. For frontend usage, use `x-client-id` + `Authorization: Bearer <jwt>` headers. ///
- /// AI assistant response or SSE stream when stream=true - /// A server side error occurred. - public virtual System.Threading.Tasks.Task ChatAsync(Body16 body) + /// The token is being deployed. Returns the predicted token address. + /// A server side error occurred. + public virtual System.Threading.Tasks.Task CreateTokenAsync(Body16 body) { - return ChatAsync(body, System.Threading.CancellationToken.None); + return CreateTokenAsync(body, System.Threading.CancellationToken.None); } /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// - /// Chat + /// Create Token /// /// - /// Thirdweb AI chat completion API (BETA). - ///
- ///
Send natural language queries to interact with any EVM chain, read data, prepare transactions, swap tokens, deploy contracts, payments and more. - ///
- ///
+ /// Create a new ERC20 token with the provided metadata and starting price. The token is immediately available for purchase using thirdweb Payments. ///
- ///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. + ///
**Authentication**: This endpoint requires project authentication and wallet authentication. For backend usage, use `x-secret-key` header. For frontend usage, use `x-client-id` + `Authorization: Bearer <jwt>` headers. ///
- /// AI assistant response or SSE stream when stream=true - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task ChatAsync(Body16 body, System.Threading.CancellationToken cancellationToken) + /// The token is being deployed. Returns the predicted token address. + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task CreateTokenAsync(Body16 body, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; var disposeClient_ = false; @@ -4377,8 +4601,8 @@ public virtual async System.Threading.Tasks.Task ChatAsync(Body16 bo var urlBuilder_ = new System.Text.StringBuilder(); if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); - // Operation Path: "ai/chat" - urlBuilder_.Append("ai/chat"); + // Operation Path: "v1/tokens" + urlBuilder_.Append("v1/tokens"); PrepareRequest(client_, request_, urlBuilder_); @@ -4403,19 +4627,43 @@ public virtual async System.Threading.Tasks.Task ChatAsync(Body16 bo ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; - if (status_ == 200) + if (status_ == 202) { - var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { - throw new ThirdwebApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Invalid request parameters.", status_, responseText_, headers_, null); + } + else + if (status_ == 401) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` + `Authorization: Bearer ` headers.", status_, responseText_, headers_, null); + } + else + if (status_ == 402) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Payment required. Insufficient wallet balance to deploy the contract.", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Internal server error. This may occur due to network connectivity issues, wallet creation failures, or transaction execution failures.", status_, responseText_, headers_, null); + } + else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -4433,32 +4681,48 @@ public virtual async System.Threading.Tasks.Task ChatAsync(Body16 bo } /// - /// MCP Server + /// List Tokens /// /// - /// Model Context Protocol (MCP) server endpoint that exposes all thirdweb API endpoints as MCP tools. This allows LLMs and AI assistants to interact with the thirdweb API through the standardized MCP protocol. + /// Lists or search existing tokens based on the provided filters. Supports querying by chain ID, token address, symbol, and/or name. + ///
+ ///
///
- ///
Authentication via x-secret-key is required for all requests. + ///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. ///
- /// MCP response - /// A server side error occurred. - public virtual System.Threading.Tasks.Task McpServerAsync(object body) + /// Number of tokens to return per page (1-100). + /// Page number for pagination, starting from 1. + /// Limit tokens to a specific chain. + /// Get a specific token by contract address + /// Limit tokens to a specific symbol. + /// Limit tokens to a specific name. + /// Tokens returned successfully. + /// A server side error occurred. + public virtual System.Threading.Tasks.Task ListTokensAsync(int? limit, int? page, int? chainId, string tokenAddress, string symbol, string name) { - return McpServerAsync(body, System.Threading.CancellationToken.None); + return ListTokensAsync(limit, page, chainId, tokenAddress, symbol, name, System.Threading.CancellationToken.None); } /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// - /// MCP Server + /// List Tokens /// /// - /// Model Context Protocol (MCP) server endpoint that exposes all thirdweb API endpoints as MCP tools. This allows LLMs and AI assistants to interact with the thirdweb API through the standardized MCP protocol. + /// Lists or search existing tokens based on the provided filters. Supports querying by chain ID, token address, symbol, and/or name. ///
- ///
Authentication via x-secret-key is required for all requests. + ///
+ ///
+ ///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. ///
- /// MCP response - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task McpServerAsync(object body, System.Threading.CancellationToken cancellationToken) + /// Number of tokens to return per page (1-100). + /// Page number for pagination, starting from 1. + /// Limit tokens to a specific chain. + /// Get a specific token by contract address + /// Limit tokens to a specific symbol. + /// Limit tokens to a specific name. + /// Tokens returned successfully. + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task ListTokensAsync(int? limit, int? page, int? chainId, string tokenAddress, string symbol, string name, System.Threading.CancellationToken cancellationToken) { var client_ = _httpClient; var disposeClient_ = false; @@ -4466,17 +4730,39 @@ public virtual async System.Threading.Tasks.Task McpServerAsync(object b { using (var request_ = new System.Net.Http.HttpRequestMessage()) { - var json_ = Newtonsoft.Json.JsonConvert.SerializeObject(body, JsonSerializerSettings); - var content_ = new System.Net.Http.StringContent(json_); - content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); - request_.Content = content_; - request_.Method = new System.Net.Http.HttpMethod("POST"); + request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); var urlBuilder_ = new System.Text.StringBuilder(); if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); - // Operation Path: "mcp" - urlBuilder_.Append("mcp"); + // Operation Path: "v1/tokens" + urlBuilder_.Append("v1/tokens"); + urlBuilder_.Append('?'); + if (limit != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("limit")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(limit, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (page != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("page")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(page, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (chainId != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("chainId")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(chainId, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (tokenAddress != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("tokenAddress")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(tokenAddress, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (symbol != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("symbol")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(symbol, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (name != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("name")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(name, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; PrepareRequest(client_, request_, urlBuilder_); @@ -4503,19 +4789,41 @@ public virtual async System.Threading.Tasks.Task McpServerAsync(object b var status_ = (int)response_.StatusCode; if (status_ == 200) { - var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } return objectResponse_.Object; } else + if (status_ == 400) { - var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Invalid request parameters.", status_, responseText_, headers_, null); } - } - finally - { - if (disposeResponse_) - response_.Dispose(); + else + if (status_ == 401) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` + `Authorization: Bearer ` headers.", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Internal server error. This may occur due to network connectivity issues, wallet creation failures, or transaction execution failures.", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); } } } @@ -4527,29 +4835,61 @@ public virtual async System.Threading.Tasks.Task McpServerAsync(object b } /// - /// llms.txt + /// Get Owners /// /// - /// The full openAPI reference for the thirdweb API in LLMs.txt format. Useful for AI assistants to understand the API and its capabilities. No authentication is required. + /// Retrieves a paginated list of owners for a given token contract on a specific chain. Supports ERC-20 tokens, ERC-721 NFTs, and ERC-1155 tokens: + ///
+ ///
- **ERC-20**: No `tokenId` provided - returns token holders with balances + ///
- **NFT Collection**: No `tokenId` provided - returns all owners of any token in the collection + ///
- **Specific NFT**: `tokenId` provided - returns owner(s) of that specific token ID + ///
+ ///
The token standard is automatically detected using ERC165 interface detection when needed. + ///
+ ///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. ///
- /// LLMs.txt - /// A server side error occurred. - public virtual System.Threading.Tasks.Task LlmsTxtAsync() + /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). + /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). + /// Optional token ID for NFT owners. If provided, returns owners of the specific NFT token. + /// Number of owners to return per page (1-100). + /// Page number for pagination, starting from 1. + /// Token owners retrieved successfully. Returns owners with pagination information. For ERC-20 tokens, `amount` represents token balance. For NFTs, `amount` represents quantity owned (usually '1' for ERC-721, can be >1 for ERC-1155). + /// A server side error occurred. + public virtual System.Threading.Tasks.Task GetTokenOwnersAsync(int chainId, string address, string tokenId, int? limit, int? page) { - return LlmsTxtAsync(System.Threading.CancellationToken.None); + return GetTokenOwnersAsync(chainId, address, tokenId, limit, page, System.Threading.CancellationToken.None); } /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// - /// llms.txt + /// Get Owners /// /// - /// The full openAPI reference for the thirdweb API in LLMs.txt format. Useful for AI assistants to understand the API and its capabilities. No authentication is required. + /// Retrieves a paginated list of owners for a given token contract on a specific chain. Supports ERC-20 tokens, ERC-721 NFTs, and ERC-1155 tokens: + ///
+ ///
- **ERC-20**: No `tokenId` provided - returns token holders with balances + ///
- **NFT Collection**: No `tokenId` provided - returns all owners of any token in the collection + ///
- **Specific NFT**: `tokenId` provided - returns owner(s) of that specific token ID + ///
+ ///
The token standard is automatically detected using ERC165 interface detection when needed. + ///
+ ///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. ///
- /// LLMs.txt - /// A server side error occurred. - public virtual async System.Threading.Tasks.Task LlmsTxtAsync(System.Threading.CancellationToken cancellationToken) + /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). + /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). + /// Optional token ID for NFT owners. If provided, returns owners of the specific NFT token. + /// Number of owners to return per page (1-100). + /// Page number for pagination, starting from 1. + /// Token owners retrieved successfully. Returns owners with pagination information. For ERC-20 tokens, `amount` represents token balance. For NFTs, `amount` represents quantity owned (usually '1' for ERC-721, can be >1 for ERC-1155). + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task GetTokenOwnersAsync(int chainId, string address, string tokenId, int? limit, int? page, System.Threading.CancellationToken cancellationToken) { + if (chainId == null) + throw new System.ArgumentNullException("chainId"); + + if (address == null) + throw new System.ArgumentNullException("address"); + var client_ = _httpClient; var disposeClient_ = false; try @@ -4557,12 +4897,30 @@ public virtual async System.Threading.Tasks.Task LlmsTxtAsync(System.Thr using (var request_ = new System.Net.Http.HttpRequestMessage()) { request_.Method = new System.Net.Http.HttpMethod("GET"); - request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("text/plain")); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); var urlBuilder_ = new System.Text.StringBuilder(); if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); - // Operation Path: "llms.txt" - urlBuilder_.Append("llms.txt"); + // Operation Path: "v1/tokens/{chainId}/{address}/owners" + urlBuilder_.Append("v1/tokens/"); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(chainId, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append('/'); + urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(address, System.Globalization.CultureInfo.InvariantCulture))); + urlBuilder_.Append("/owners"); + urlBuilder_.Append('?'); + if (tokenId != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("tokenId")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(tokenId, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (limit != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("limit")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(limit, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + if (page != null) + { + urlBuilder_.Append(System.Uri.EscapeDataString("page")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(page, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + } + urlBuilder_.Length--; PrepareRequest(client_, request_, urlBuilder_); @@ -4589,14 +4947,41 @@ public virtual async System.Threading.Tasks.Task LlmsTxtAsync(System.Thr var status_ = (int)response_.StatusCode; if (status_ == 200) { - var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - var result_ = (string)System.Convert.ChangeType(responseData_, typeof(string)); - return result_; + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Invalid request parameters.", status_, responseText_, headers_, null); + } + else + if (status_ == 401) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Authentication required. The request must include a valid `x-client-id` header for frontend usage or `x-secret-key` for backend usage.", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Token not found or no owners available.", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Internal server error.", status_, responseText_, headers_, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new ThirdwebApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally @@ -4613,111 +4998,804 @@ public virtual async System.Threading.Tasks.Task LlmsTxtAsync(System.Thr } } - protected struct ObjectResponseResult + /// + /// List Supported Chains + /// + /// + /// List all blockchain networks available for cross-chain bridging. Each chain includes metadata and native currency details. + ///
+ ///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. + ///
+ /// Successfully retrieved supported bridge chains. + /// A server side error occurred. + public virtual System.Threading.Tasks.Task GetBridgeChainsAsync() { - public ObjectResponseResult(T responseObject, string responseText) + return GetBridgeChainsAsync(System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// List Supported Chains + /// + /// + /// List all blockchain networks available for cross-chain bridging. Each chain includes metadata and native currency details. + ///
+ ///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. + ///
+ /// Successfully retrieved supported bridge chains. + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task GetBridgeChainsAsync(System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try { - this.Object = responseObject; - this.Text = responseText; - } + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + request_.Method = new System.Net.Http.HttpMethod("GET"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); - public T Object { get; } + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "v1/bridge/chains" + urlBuilder_.Append("v1/bridge/chains"); - public string Text { get; } - } + PrepareRequest(client_, request_, urlBuilder_); - public bool ReadResponseAsString { get; set; } + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); - protected virtual async System.Threading.Tasks.Task> ReadObjectResponseAsync(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Threading.CancellationToken cancellationToken) - { - if (response == null || response.Content == null) - { - return new ObjectResponseResult(default(T), string.Empty); - } + PrepareRequest(client_, request_, url_); - if (ReadResponseAsString) - { - var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - try - { - var typedBody = Newtonsoft.Json.JsonConvert.DeserializeObject(responseText, JsonSerializerSettings); - return new ObjectResponseResult(typedBody, responseText); - } - catch (Newtonsoft.Json.JsonException exception) - { - var message = "Could not deserialize the response body string as " + typeof(T).FullName + "."; - throw new ThirdwebApiException(message, (int)response.StatusCode, responseText, headers, exception); - } - } - else - { - try - { - using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) - using (var streamReader = new System.IO.StreamReader(responseStream)) - using (var jsonTextReader = new Newtonsoft.Json.JsonTextReader(streamReader)) + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try { - var serializer = Newtonsoft.Json.JsonSerializer.Create(JsonSerializerSettings); - var typedBody = serializer.Deserialize(jsonTextReader); - return new ObjectResponseResult(typedBody, string.Empty); - } - } - catch (Newtonsoft.Json.JsonException exception) - { - var message = "Could not deserialize the response body stream as " + typeof(T).FullName + "."; - throw new ThirdwebApiException(message, (int)response.StatusCode, string.Empty, headers, exception); - } - } - } + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } - private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo) - { - if (value == null) - { - return ""; - } + ProcessResponse(client_, response_); - if (value is System.Enum) - { - var name = System.Enum.GetName(value.GetType(), value); - if (name != null) - { - var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(value.GetType()).GetDeclaredField(name); - if (field != null) - { - var attribute = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(field, typeof(System.Runtime.Serialization.EnumMemberAttribute)) - as System.Runtime.Serialization.EnumMemberAttribute; - if (attribute != null) + var status_ = (int)response_.StatusCode; + if (status_ == 200) { - return attribute.Value != null ? attribute.Value : name; + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 401) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` header.", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Internal server error occurred while fetching bridge chains.", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } - - var converted = System.Convert.ToString(System.Convert.ChangeType(value, System.Enum.GetUnderlyingType(value.GetType()), cultureInfo)); - return converted == null ? string.Empty : converted; + finally + { + if (disposeResponse_) + response_.Dispose(); + } } } - else if (value is bool) - { - return System.Convert.ToString((bool)value, cultureInfo).ToLowerInvariant(); - } - else if (value is byte[]) - { - return System.Convert.ToBase64String((byte[]) value); - } - else if (value is string[]) - { - return string.Join(",", (string[])value); - } - else if (value.GetType().IsArray) + finally { - var valueArray = (System.Array)value; - var valueTextArray = new string[valueArray.Length]; - for (var i = 0; i < valueArray.Length; i++) - { - valueTextArray[i] = ConvertToString(valueArray.GetValue(i), cultureInfo); - } - return string.Join(",", valueTextArray); + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Convert Fiat to Crypto + /// + /// + /// Convert fiat currency amount to cryptocurrency token amount. Supports multiple fiat currencies based on available price data for the specific token. Returns the equivalent amount of crypto tokens for the specified fiat amount based on current market prices. If price data is not available for the requested currency, the API will return a 404 error. + ///
+ ///
**Native Tokens**: To get the price of native tokens (like ETH on Ethereum), use the address `0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE`. For example, to get the price of ETH on Ethereum Mainnet (chainId: 1), pass `to=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE`. + ///
+ ///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. + ///
+ /// The fiat currency symbol + /// The amount of fiat currency to convert + /// The blockchain network identifier + /// The token address on the specified chain to convert to + /// Conversion completed successfully. Returns the amount of crypto tokens equivalent to the specified fiat amount. + /// A server side error occurred. + public virtual System.Threading.Tasks.Task ConvertFiatToCryptoAsync(From from, string fromAmount, int chainId, string to) + { + return ConvertFiatToCryptoAsync(from, fromAmount, chainId, to, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Convert Fiat to Crypto + /// + /// + /// Convert fiat currency amount to cryptocurrency token amount. Supports multiple fiat currencies based on available price data for the specific token. Returns the equivalent amount of crypto tokens for the specified fiat amount based on current market prices. If price data is not available for the requested currency, the API will return a 404 error. + ///
+ ///
**Native Tokens**: To get the price of native tokens (like ETH on Ethereum), use the address `0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE`. For example, to get the price of ETH on Ethereum Mainnet (chainId: 1), pass `to=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE`. + ///
+ ///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. + ///
+ /// The fiat currency symbol + /// The amount of fiat currency to convert + /// The blockchain network identifier + /// The token address on the specified chain to convert to + /// Conversion completed successfully. Returns the amount of crypto tokens equivalent to the specified fiat amount. + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task ConvertFiatToCryptoAsync(From from, string fromAmount, int chainId, string to, System.Threading.CancellationToken cancellationToken) + { + if (from == null) + throw new System.ArgumentNullException("from"); + + if (fromAmount == null) + throw new System.ArgumentNullException("fromAmount"); + + if (chainId == null) + throw new System.ArgumentNullException("chainId"); + + if (to == null) + throw new System.ArgumentNullException("to"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + request_.Method = new System.Net.Http.HttpMethod("GET"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "v1/bridge/convert" + urlBuilder_.Append("v1/bridge/convert"); + urlBuilder_.Append('?'); + urlBuilder_.Append(System.Uri.EscapeDataString("from")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(from, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + urlBuilder_.Append(System.Uri.EscapeDataString("fromAmount")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(fromAmount, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + urlBuilder_.Append(System.Uri.EscapeDataString("chainId")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(chainId, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + urlBuilder_.Append(System.Uri.EscapeDataString("to")).Append('=').Append(System.Uri.EscapeDataString(ConvertToString(to, System.Globalization.CultureInfo.InvariantCulture))).Append('&'); + urlBuilder_.Length--; + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Bad request. Invalid parameters such as invalid amounts, malformed token address, or invalid currency code.", status_, responseText_, headers_, null); + } + else + if (status_ == 401) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Authentication required. Include `x-client-id` header for frontend usage or `x-secret-key` for backend usage.", status_, responseText_, headers_, null); + } + else + if (status_ == 404) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Token not found, price data unavailable for the specified token on the given chain, or price data not available for the requested currency.", status_, responseText_, headers_, null); + } + else + if (status_ == 429) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Too many requests. Rate limit exceeded.", status_, responseText_, headers_, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Internal server error. This may occur due to network connectivity issues or external service failures.", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Swap or Bridge Tokens + /// + /// + /// Swap one token for another using the optimal route available. You can specify a tokenIn amount (if exact='input') or tokenOut amount (if exact='output'), but not both. The corresponding output or input amount will be returned as the quote. + ///
+ ///
**Authentication**: This endpoint requires project authentication and wallet authentication. For backend usage, use `x-secret-key` header. For frontend usage, use `x-client-id` + `Authorization: Bearer <jwt>` headers. + ///
+ /// Swap completed successfully. Returns the transaction used for the swap. + /// A server side error occurred. + public virtual System.Threading.Tasks.Task BridgeSwapAsync(Body17 body) + { + return BridgeSwapAsync(body, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Swap or Bridge Tokens + /// + /// + /// Swap one token for another using the optimal route available. You can specify a tokenIn amount (if exact='input') or tokenOut amount (if exact='output'), but not both. The corresponding output or input amount will be returned as the quote. + ///
+ ///
**Authentication**: This endpoint requires project authentication and wallet authentication. For backend usage, use `x-secret-key` header. For frontend usage, use `x-client-id` + `Authorization: Bearer <jwt>` headers. + ///
+ /// Swap completed successfully. Returns the transaction used for the swap. + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task BridgeSwapAsync(Body17 body, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + var json_ = Newtonsoft.Json.JsonConvert.SerializeObject(body, JsonSerializerSettings); + var content_ = new System.Net.Http.StringContent(json_); + content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + request_.Content = content_; + request_.Method = new System.Net.Http.HttpMethod("POST"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "v1/bridge/swap" + urlBuilder_.Append("v1/bridge/swap"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + if (status_ == 400) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Invalid request parameters.", status_, responseText_, headers_, null); + } + else + if (status_ == 401) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Authentication required. For backend usage, include `x-secret-key` header. For frontend usage, include `x-client-id` + `Authorization: Bearer ` headers.", status_, responseText_, headers_, null); + } + else + if (status_ == 402) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + throw new ApiException("Payment required. Insufficient wallet balance to complete the purchase.", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); + } + else + if (status_ == 500) + { + string responseText_ = ( response_.Content == null ) ? string.Empty : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("Internal server error. This may occur due to network connectivity issues, wallet creation failures, or transaction execution failures.", status_, responseText_, headers_, null); + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// Chat + /// + /// + /// Thirdweb AI chat completion API (BETA). + ///
+ ///
Send natural language queries to interact with any EVM chain, read data, prepare transactions, swap tokens, deploy contracts, payments and more. + ///
+ ///
Compatible with standard OpenAI API chat completion format, can be used raw or with any popular AI library. + ///
+ ///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. + ///
+ /// AI assistant response or SSE stream when stream=true + /// A server side error occurred. + public virtual System.Threading.Tasks.Task ChatAsync(Body18 body) + { + return ChatAsync(body, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// Chat + /// + /// + /// Thirdweb AI chat completion API (BETA). + ///
+ ///
Send natural language queries to interact with any EVM chain, read data, prepare transactions, swap tokens, deploy contracts, payments and more. + ///
+ ///
Compatible with standard OpenAI API chat completion format, can be used raw or with any popular AI library. + ///
+ ///
**Authentication**: Pass `x-client-id` header for frontend usage from allowlisted origins or `x-secret-key` for backend usage. + ///
+ /// AI assistant response or SSE stream when stream=true + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task ChatAsync(Body18 body, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + var json_ = Newtonsoft.Json.JsonConvert.SerializeObject(body, JsonSerializerSettings); + var content_ = new System.Net.Http.StringContent(json_); + content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + request_.Content = content_; + request_.Method = new System.Net.Http.HttpMethod("POST"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "ai/chat" + urlBuilder_.Append("ai/chat"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// MCP Server + /// + /// + /// Model Context Protocol (MCP) server endpoint that exposes all thirdweb API endpoints as MCP tools. This allows LLMs and AI assistants to interact with the thirdweb API through the standardized MCP protocol. + ///
+ ///
Add this MCP server to any MCP client: + ///
+ ///
```json + ///
{ + ///
"mcpServers": { + ///
"thirdweb-api": { + ///
"url": "https://api.thirdweb.com/mcp?secretKey=YOUR_SECRET_KEY_HERE" + ///
} + ///
} + ///
} + ///
``` + ///
+ /// MCP response + /// A server side error occurred. + public virtual System.Threading.Tasks.Task McpServerAsync(object body) + { + return McpServerAsync(body, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// MCP Server + /// + /// + /// Model Context Protocol (MCP) server endpoint that exposes all thirdweb API endpoints as MCP tools. This allows LLMs and AI assistants to interact with the thirdweb API through the standardized MCP protocol. + ///
+ ///
Add this MCP server to any MCP client: + ///
+ ///
```json + ///
{ + ///
"mcpServers": { + ///
"thirdweb-api": { + ///
"url": "https://api.thirdweb.com/mcp?secretKey=YOUR_SECRET_KEY_HERE" + ///
} + ///
} + ///
} + ///
``` + ///
+ /// MCP response + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task McpServerAsync(object body, System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + var json_ = Newtonsoft.Json.JsonConvert.SerializeObject(body, JsonSerializerSettings); + var content_ = new System.Net.Http.StringContent(json_); + content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + request_.Content = content_; + request_.Method = new System.Net.Http.HttpMethod("POST"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "mcp" + urlBuilder_.Append("mcp"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + return objectResponse_.Object; + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + /// + /// llms.txt + /// + /// + /// The full openAPI reference for the thirdweb API in LLMs.txt format. Useful for AI assistants to understand the API and its capabilities. No authentication is required. Copy paste the contents of [https://api.thirdweb.com/llms.txt](https://api.thirdweb.com/llms.txt) into your source code to make your AI assistant understand the API and its capabilities. + /// + /// LLMs.txt + /// A server side error occurred. + public virtual System.Threading.Tasks.Task LlmsTxtAsync() + { + return LlmsTxtAsync(System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// + /// llms.txt + /// + /// + /// The full openAPI reference for the thirdweb API in LLMs.txt format. Useful for AI assistants to understand the API and its capabilities. No authentication is required. Copy paste the contents of [https://api.thirdweb.com/llms.txt](https://api.thirdweb.com/llms.txt) into your source code to make your AI assistant understand the API and its capabilities. + /// + /// LLMs.txt + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task LlmsTxtAsync(System.Threading.CancellationToken cancellationToken) + { + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + request_.Method = new System.Net.Http.HttpMethod("GET"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("text/plain")); + + var urlBuilder_ = new System.Text.StringBuilder(); + if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl); + // Operation Path: "llms.txt" + urlBuilder_.Append("llms.txt"); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = new System.Collections.Generic.Dictionary>(); + foreach (var item_ in response_.Headers) + headers_[item_.Key] = item_.Value; + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + var result_ = (string)System.Convert.ChangeType(responseData_, typeof(string)); + return result_; + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + + protected struct ObjectResponseResult + { + public ObjectResponseResult(T responseObject, string responseText) + { + this.Object = responseObject; + this.Text = responseText; + } + + public T Object { get; } + + public string Text { get; } + } + + public bool ReadResponseAsString { get; set; } + + protected virtual async System.Threading.Tasks.Task> ReadObjectResponseAsync(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Threading.CancellationToken cancellationToken) + { + if (response == null || response.Content == null) + { + return new ObjectResponseResult(default(T), string.Empty); + } + + if (ReadResponseAsString) + { + var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + var typedBody = Newtonsoft.Json.JsonConvert.DeserializeObject(responseText, JsonSerializerSettings); + return new ObjectResponseResult(typedBody, responseText); + } + catch (Newtonsoft.Json.JsonException exception) + { + var message = "Could not deserialize the response body string as " + typeof(T).FullName + "."; + throw new ApiException(message, (int)response.StatusCode, responseText, headers, exception); + } + } + else + { + try + { + using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) + using (var streamReader = new System.IO.StreamReader(responseStream)) + using (var jsonTextReader = new Newtonsoft.Json.JsonTextReader(streamReader)) + { + var serializer = Newtonsoft.Json.JsonSerializer.Create(JsonSerializerSettings); + var typedBody = serializer.Deserialize(jsonTextReader); + return new ObjectResponseResult(typedBody, string.Empty); + } + } + catch (Newtonsoft.Json.JsonException exception) + { + var message = "Could not deserialize the response body stream as " + typeof(T).FullName + "."; + throw new ApiException(message, (int)response.StatusCode, string.Empty, headers, exception); + } + } + } + + private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo) + { + if (value == null) + { + return ""; + } + + if (value is System.Enum) + { + var name = System.Enum.GetName(value.GetType(), value); + if (name != null) + { + var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(value.GetType()).GetDeclaredField(name); + if (field != null) + { + var attribute = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(field, typeof(System.Runtime.Serialization.EnumMemberAttribute)) + as System.Runtime.Serialization.EnumMemberAttribute; + if (attribute != null) + { + return attribute.Value != null ? attribute.Value : name; + } + } + + var converted = System.Convert.ToString(System.Convert.ChangeType(value, System.Enum.GetUnderlyingType(value.GetType()), cultureInfo)); + return converted == null ? string.Empty : converted; + } + } + else if (value is bool) + { + return System.Convert.ToString((bool)value, cultureInfo).ToLowerInvariant(); + } + else if (value is byte[]) + { + return System.Convert.ToBase64String((byte[]) value); + } + else if (value is string[]) + { + return string.Join(",", (string[])value); + } + else if (value.GetType().IsArray) + { + var valueArray = (System.Array)value; + var valueTextArray = new string[valueArray.Length]; + for (var i = 0; i < valueArray.Length; i++) + { + valueTextArray[i] = ConvertToString(valueArray.GetValue(i), cultureInfo); + } + return string.Join(",", valueTextArray); } var result = System.Convert.ToString(value, cultureInfo); @@ -4726,22 +5804,2611 @@ private string ConvertToString(object value, System.Globalization.CultureInfo cu } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Body + public partial class Body + { + /// + /// Authentication method: SMS + /// + [Newtonsoft.Json.JsonProperty("method", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public BodyMethod Method { get; set; } + + /// + /// Phone number in E.164 format (e.g., +1234567890) + /// + [Newtonsoft.Json.JsonProperty("phone", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Phone { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Body2 + { + /// + /// Authentication method: SMS + /// + [Newtonsoft.Json.JsonProperty("method", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public Body2Method Method { get; set; } + + /// + /// Phone number that received the code + /// + [Newtonsoft.Json.JsonProperty("phone", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Phone { get; set; } + + /// + /// Verification code received via SMS + /// + [Newtonsoft.Json.JsonProperty("code", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Code { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// The OAuth provider to use + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Provider + { + + [System.Runtime.Serialization.EnumMember(Value = @"google")] + Google = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"apple")] + Apple = 1, + + [System.Runtime.Serialization.EnumMember(Value = @"facebook")] + Facebook = 2, + + [System.Runtime.Serialization.EnumMember(Value = @"discord")] + Discord = 3, + + [System.Runtime.Serialization.EnumMember(Value = @"farcaster")] + Farcaster = 4, + + [System.Runtime.Serialization.EnumMember(Value = @"telegram")] + Telegram = 5, + + [System.Runtime.Serialization.EnumMember(Value = @"line")] + Line = 6, + + [System.Runtime.Serialization.EnumMember(Value = @"x")] + X = 7, + + [System.Runtime.Serialization.EnumMember(Value = @"coinbase")] + Coinbase = 8, + + [System.Runtime.Serialization.EnumMember(Value = @"github")] + Github = 9, + + [System.Runtime.Serialization.EnumMember(Value = @"twitch")] + Twitch = 10, + + [System.Runtime.Serialization.EnumMember(Value = @"steam")] + Steam = 11, + + [System.Runtime.Serialization.EnumMember(Value = @"tiktok")] + Tiktok = 12, + + } + + /// + /// Request body for pre-generating a wallet + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Body3 + { + [Newtonsoft.Json.JsonProperty("type", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public Body3Type Type { get; set; } + + /// + /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). + /// + [Newtonsoft.Json.JsonProperty("walletAddress", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string WalletAddress { get; set; } + + [Newtonsoft.Json.JsonProperty("email", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Email { get; set; } + + [Newtonsoft.Json.JsonProperty("phone", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Phone { get; set; } + + [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string UserId { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Request body for creating a wallet + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Body4 + { + /// + /// Unique identifier for wallet creation or retrieval. Can be user ID, email, or any unique string. The same identifier will always return the same wallet. + /// + [Newtonsoft.Json.JsonProperty("identifier", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public string Identifier { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Sort order: 'asc' for ascending, 'desc' for descending + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum SortOrder + { + + [System.Runtime.Serialization.EnumMember(Value = @"asc")] + Asc = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"desc")] + Desc = 1, + + } + + /// + /// Whether to include token metadata (default: true). + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Metadata + { + + [System.Runtime.Serialization.EnumMember(Value = @"true")] + True = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"false")] + False = 1, + + } + + /// + /// Whether to resolve metadata links to fetch additional token information (default: true). + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum ResolveMetadataLinks + { + + [System.Runtime.Serialization.EnumMember(Value = @"true")] + True = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"false")] + False = 1, + + } + + /// + /// Whether to include tokens marked as spam (default: false). + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum IncludeSpam + { + + [System.Runtime.Serialization.EnumMember(Value = @"true")] + True = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"false")] + False = 1, + + } + + /// + /// Whether to include native tokens (e.g., ETH, MATIC) in the results (default: true). + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum IncludeNative + { + + [System.Runtime.Serialization.EnumMember(Value = @"true")] + True = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"false")] + False = 1, + + } + + /// + /// Field to sort tokens by: 'balance' for token balance, 'token_address' for token address, 'token_price' for token price, 'usd_value' for USD value (default: usd_value). + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum SortBy + { + + [System.Runtime.Serialization.EnumMember(Value = @"balance")] + Balance = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"token_address")] + Token_address = 1, + + [System.Runtime.Serialization.EnumMember(Value = @"token_price")] + Token_price = 2, + + [System.Runtime.Serialization.EnumMember(Value = @"usd_value")] + Usd_value = 3, + + } + + /// + /// Sort order: 'asc' for ascending, 'desc' for descending (default: desc). + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum SortOrder2 + { + + [System.Runtime.Serialization.EnumMember(Value = @"asc")] + Asc = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"desc")] + Desc = 1, + + } + + /// + /// Whether to include tokens without price data (default: true). + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum IncludeWithoutPrice + { + + [System.Runtime.Serialization.EnumMember(Value = @"true")] + True = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"false")] + False = 1, + + } + + /// + /// Request body for signing a message + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Body5 + { + /// + /// The wallet address or ENS name that will sign the message. + /// + [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string From { get; set; } + + /// + /// The blockchain network identifier where the signing will occur. Common values include: 1 (Ethereum), 137 (Polygon), 56 (BSC). + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } + + /// + /// The message to be signed. Can be plain text or hexadecimal format (starting with 0x). The format is automatically detected. + /// + [Newtonsoft.Json.JsonProperty("message", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Message { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Request body for signing typed data + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Body6 + { + /// + /// The wallet address or ENS name that will sign the typed data. + /// + [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string From { get; set; } + + /// + /// The blockchain network identifier for EIP-712 domain separation. + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } + + /// + /// EIP-712 domain separator containing contract and chain information for signature verification. + /// + [Newtonsoft.Json.JsonProperty("domain", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Domain Domain { get; set; } = new Domain(); + + /// + /// The structured data to be signed, matching the defined types schema. + /// + [Newtonsoft.Json.JsonProperty("message", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.IDictionary Message { get; set; } = new System.Collections.Generic.Dictionary(); + + /// + /// The primary type name from the types object that defines the main structure being signed. + /// + [Newtonsoft.Json.JsonProperty("primaryType", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string PrimaryType { get; set; } + + /// + /// Type definitions for the structured data, following EIP-712 specifications. + /// + [Newtonsoft.Json.JsonProperty("types", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.IDictionary> Types { get; set; } = new System.Collections.Generic.Dictionary>(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Request body for sending tokens to multiple recipients. Supports native tokens, ERC20, ERC721, and ERC1155 transfers based on the provided parameters. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Body7 + { + /// + /// The wallet address or ENS name that will send the tokens. + /// + [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string From { get; set; } + + /// + /// The blockchain network identifier where the transfer will be executed. + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } + + /// + /// Array of recipients and quantities. Maximum 100 recipients per request. + /// + [Newtonsoft.Json.JsonProperty("recipients", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + [System.ComponentModel.DataAnnotations.MinLength(1)] + [System.ComponentModel.DataAnnotations.MaxLength(100)] + public System.Collections.Generic.ICollection Recipients { get; set; } = new System.Collections.ObjectModel.Collection(); + + /// + /// The token contract address. Omit for native token (ETH, MATIC, etc.) transfers. + /// + [Newtonsoft.Json.JsonProperty("tokenAddress", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string TokenAddress { get; set; } + + /// + /// The token ID for NFT transfers (ERC721/ERC1155). Required for NFT transfers. + /// + [Newtonsoft.Json.JsonProperty("tokenId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string TokenId { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Contract deployment specification for raw bytecode deployment. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Body8 + { + /// + /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } + + /// + /// The wallet address or ENS name that will deploy the contract. + /// + [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string From { get; set; } + + /// + /// The contract bytecode as a hex string. + /// + [Newtonsoft.Json.JsonProperty("bytecode", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Bytecode { get; set; } + + /// + /// The contract ABI array. + /// + [Newtonsoft.Json.JsonProperty("abi", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Abi { get; set; } = new System.Collections.ObjectModel.Collection(); + + /// + /// Object containing constructor parameters for the contract deployment (e.g., { param1: 'value1', param2: 123 }). + /// + [Newtonsoft.Json.JsonProperty("constructorParams", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.IDictionary ConstructorParams { get; set; } + + /// + /// Optional salt value for deterministic contract deployment. + /// + [Newtonsoft.Json.JsonProperty("salt", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Salt { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Body9 + { + /// + /// Array of contract method calls to execute. Each call specifies a contract address, method signature, and optional parameters. + /// + [Newtonsoft.Json.JsonProperty("calls", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + [System.ComponentModel.DataAnnotations.MinLength(1)] + public System.Collections.Generic.ICollection Calls { get; set; } = new System.Collections.ObjectModel.Collection(); + + /// + /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Body10 + { + /// + /// Array of contract method calls to execute. Each call specifies a contract address, method signature, and optional parameters. + /// + [Newtonsoft.Json.JsonProperty("calls", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + [System.ComponentModel.DataAnnotations.MinLength(1)] + public System.Collections.Generic.ICollection Calls { get; set; } = new System.Collections.ObjectModel.Collection(); + + /// + /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } + + /// + /// The wallet address or ENS name that will send the transaction. + /// + [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string From { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Sort order: 'asc' for ascending, 'desc' for descending + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum SortOrder3 + { + + [System.Runtime.Serialization.EnumMember(Value = @"asc")] + Asc = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"desc")] + Desc = 1, + + } + + /// + /// Sort order: 'asc' for ascending, 'desc' for descending + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum SortOrder4 + { + + [System.Runtime.Serialization.EnumMember(Value = @"asc")] + Asc = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"desc")] + Desc = 1, + + } + + /// + /// Request object containing an array of encoded blockchain transactions to execute. All transactions must use the same from address and chainId. For contract calls, use /v1/contracts/write. For native token transfers, use /v1/wallets/send. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Body11 + { + /// + /// The blockchain network identifier where all transactions will be executed. + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } + + /// + /// The wallet address or ENS name that will send the transaction. + /// + [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string From { get; set; } + + /// + /// Array of encoded blockchain transactions to execute. All transactions will use the same from address and chainId. + /// + [Newtonsoft.Json.JsonProperty("transactions", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + [System.ComponentModel.DataAnnotations.MinLength(1)] + public System.Collections.Generic.ICollection Transactions { get; set; } = new System.Collections.ObjectModel.Collection(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Request to create a product to be purchased. Users can purchase the product via hosted UI (link is returned), a transaction execution referencing the product ID, or embedded widgets with the product ID. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Body12 + { + /// + /// The name of the product + /// + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Name { get; set; } + + /// + /// The description of the product + /// + [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Description { get; set; } + + /// + /// The URL of the product image + /// + [Newtonsoft.Json.JsonProperty("imageUrl", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string ImageUrl { get; set; } + + /// + /// The token to purchase + /// + [Newtonsoft.Json.JsonProperty("token", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Token Token { get; set; } = new Token(); + + /// + /// The wallet address or ENS name that will receive the payment for the product + /// + [Newtonsoft.Json.JsonProperty("recipient", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Recipient { get; set; } + + /// + /// App specific purchase data for this payment + /// + [Newtonsoft.Json.JsonProperty("purchaseData", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public object PurchaseData { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Request to purchase a product. The system will automatically use your wallet balance to purchase the specified product. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Body13 + { + /// + /// The wallet address or ENS name that will purchase the product. + /// + [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string From { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Request body for x402 facilitator 'verify' + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Body14 + { + [Newtonsoft.Json.JsonProperty("paymentPayload", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public PaymentPayload PaymentPayload { get; set; } = new PaymentPayload(); + + [Newtonsoft.Json.JsonProperty("paymentRequirements", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public PaymentRequirements PaymentRequirements { get; set; } = new PaymentRequirements(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Request body for x402 facilitator 'settle' + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Body15 + { + [Newtonsoft.Json.JsonProperty("paymentPayload", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public PaymentPayload2 PaymentPayload { get; set; } = new PaymentPayload2(); + + [Newtonsoft.Json.JsonProperty("paymentRequirements", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public PaymentRequirements2 PaymentRequirements { get; set; } = new PaymentRequirements2(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Request schema for creating a new ERC20 token + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Body16 + { + /// + /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } + + /// + /// Token name + /// + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength = 1)] + public string Name { get; set; } + + /// + /// Token symbol + /// + [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + [System.ComponentModel.DataAnnotations.StringLength(20, MinimumLength = 1)] + public string Symbol { get; set; } + + /// + /// Token description + /// + [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + [System.ComponentModel.DataAnnotations.StringLength(500, MinimumLength = 1)] + public string Description { get; set; } + + /// + /// Token image URL + /// + [Newtonsoft.Json.JsonProperty("imageUrl", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public System.Uri ImageUrl { get; set; } + + /// + /// Wallet address or ENS that will deploy the token. + /// + [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string From { get; set; } + + /// + /// The token owner address, if different from `from`. + /// + [Newtonsoft.Json.JsonProperty("owner", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Owner { get; set; } + + /// + /// A salt to deterministically generate the token address. + /// + [Newtonsoft.Json.JsonProperty("salt", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Salt { get; set; } + + /// + /// The maximum token supply. + /// + [Newtonsoft.Json.JsonProperty("maxSupply", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double MaxSupply { get; set; } = 1000000000D; + + /// + /// Setup this token for a sale. + /// + [Newtonsoft.Json.JsonProperty("sale", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public Sale Sale { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// The fiat currency symbol + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum From + { + + [System.Runtime.Serialization.EnumMember(Value = @"USD")] + USD = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"EUR")] + EUR = 1, + + [System.Runtime.Serialization.EnumMember(Value = @"GBP")] + GBP = 2, + + [System.Runtime.Serialization.EnumMember(Value = @"JPY")] + JPY = 3, + + [System.Runtime.Serialization.EnumMember(Value = @"KRW")] + KRW = 4, + + [System.Runtime.Serialization.EnumMember(Value = @"CNY")] + CNY = 5, + + [System.Runtime.Serialization.EnumMember(Value = @"INR")] + INR = 6, + + [System.Runtime.Serialization.EnumMember(Value = @"NOK")] + NOK = 7, + + [System.Runtime.Serialization.EnumMember(Value = @"SEK")] + SEK = 8, + + [System.Runtime.Serialization.EnumMember(Value = @"CHF")] + CHF = 9, + + [System.Runtime.Serialization.EnumMember(Value = @"AUD")] + AUD = 10, + + [System.Runtime.Serialization.EnumMember(Value = @"CAD")] + CAD = 11, + + [System.Runtime.Serialization.EnumMember(Value = @"NZD")] + NZD = 12, + + [System.Runtime.Serialization.EnumMember(Value = @"MXN")] + MXN = 13, + + [System.Runtime.Serialization.EnumMember(Value = @"BRL")] + BRL = 14, + + [System.Runtime.Serialization.EnumMember(Value = @"CLP")] + CLP = 15, + + [System.Runtime.Serialization.EnumMember(Value = @"CZK")] + CZK = 16, + + [System.Runtime.Serialization.EnumMember(Value = @"DKK")] + DKK = 17, + + [System.Runtime.Serialization.EnumMember(Value = @"HKD")] + HKD = 18, + + [System.Runtime.Serialization.EnumMember(Value = @"HUF")] + HUF = 19, + + [System.Runtime.Serialization.EnumMember(Value = @"IDR")] + IDR = 20, + + [System.Runtime.Serialization.EnumMember(Value = @"ILS")] + ILS = 21, + + [System.Runtime.Serialization.EnumMember(Value = @"ISK")] + ISK = 22, + + } + + /// + /// Request to swap tokens using the optimal route available. You can specify a tokenIn amount (if exact='input') or tokenOut amount (if exact='output'), but not both. The corresponding output or input amount will be returned as the quote. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Body17 + { + /// + /// Whether to swap the exact input or output amount + /// + [Newtonsoft.Json.JsonProperty("exact", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public Body17Exact Exact { get; set; } = Thirdweb.Api.Body17Exact.Input; + + [Newtonsoft.Json.JsonProperty("tokenIn", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public TokenIn TokenIn { get; set; } = new TokenIn(); + + [Newtonsoft.Json.JsonProperty("tokenOut", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public TokenOut TokenOut { get; set; } = new TokenOut(); + + /// + /// The wallet address or ENS name that will execute the swap. + /// + [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string From { get; set; } + + /// + /// The slippage tolerance in basis points. Will be automatically calculated by default. + /// + [Newtonsoft.Json.JsonProperty("slippageToleranceBps", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? SlippageToleranceBps { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Chat request + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Body18 + { + /// + /// Natural language query for the AI assistant + /// + [Newtonsoft.Json.JsonProperty("messages", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + [System.ComponentModel.DataAnnotations.MinLength(1)] + public System.Collections.Generic.ICollection Messages { get; set; } = new System.Collections.ObjectModel.Collection(); + + /// + /// Context for the AI assistant + /// + [Newtonsoft.Json.JsonProperty("context", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public Context Context { get; set; } + + /// + /// Enable server streaming of the AI response + /// + [Newtonsoft.Json.JsonProperty("stream", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public bool Stream { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response + { + /// + /// Authentication method: SMS + /// + [Newtonsoft.Json.JsonProperty("method", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public ResponseMethod Method { get; set; } + + /// + /// Whether the SMS code was sent successfully + /// + [Newtonsoft.Json.JsonProperty("success", Required = Newtonsoft.Json.Required.Always)] + public bool Success { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Successful authentication response. Returns wallet address plus authentication tokens. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response2 + { + /// + /// Whether this is a newly created user/wallet + /// + [Newtonsoft.Json.JsonProperty("isNewUser", Required = Newtonsoft.Json.Required.Always)] + public bool IsNewUser { get; set; } + + /// + /// JWT authentication token for API access + /// + [Newtonsoft.Json.JsonProperty("token", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Token { get; set; } + + /// + /// Type of authentication completed + /// + [Newtonsoft.Json.JsonProperty("type", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Type { get; set; } + + /// + /// The wallet address + /// + [Newtonsoft.Json.JsonProperty("walletAddress", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string WalletAddress { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response3 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result Result { get; set; } = new Result(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response4 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result2 Result { get; set; } = new Result2(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response5 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result3 Result { get; set; } = new Result3(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response6 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result4 Result { get; set; } = new Result4(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response7 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result5 Result { get; set; } = new Result5(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response8 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Result { get; set; } = new System.Collections.ObjectModel.Collection(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response9 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result6 Result { get; set; } = new Result6(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response10 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result7 Result { get; set; } = new Result7(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response11 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result8 Result { get; set; } = new Result8(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response12 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result9 Result { get; set; } = new Result9(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response13 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result10 Result { get; set; } = new Result10(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response14 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result11 Result { get; set; } = new Result11(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response15 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result12 Result { get; set; } = new Result12(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response16 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result13 Result { get; set; } = new Result13(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response17 + { + /// + /// Array of results corresponding to each contract read call. Results are returned in the same order as the input calls. + /// + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Result { get; set; } = new System.Collections.ObjectModel.Collection(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response18 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result15 Result { get; set; } = new Result15(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Payment required response when user has insufficient funds. Contains a quote for completing the purchase. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response19 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result16 Result { get; set; } = new Result16(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response20 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result17 Result { get; set; } = new Result17(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response21 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result18 Result { get; set; } = new Result18(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Contract metadata from the thirdweb contract metadata service. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response22 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result19 Result { get; set; } = new Result19(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Contract ABI signatures in human-readable format. These signatures can be used directly with contract interaction methods. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response23 + { + /// + /// Array of human-readable ABI signatures including functions and events. Each signature is formatted as a string that can be used directly in contract read/write operations or event filtering. + /// + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Result { get; set; } = new System.Collections.ObjectModel.Collection(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response24 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result20 Result { get; set; } = new Result20(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response25 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result21 Result { get; set; } = new Result21(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response26 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result22 Result { get; set; } = new Result22(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Payment required response when user has insufficient funds. Contains a quote for completing the purchase. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response27 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result23 Result { get; set; } = new Result23(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Successful payment creation response containing the payment ID and link to purchase the product + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response28 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result24 Result { get; set; } = new Result24(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response29 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result25 Result { get; set; } = new Result25(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Payment required response when user has insufficient funds. Contains a quote for completing the purchase. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response30 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result26 Result { get; set; } = new Result26(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response31 + { + /// + /// List of payments for the client + /// + [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Data { get; set; } = new System.Collections.ObjectModel.Collection(); + + [Newtonsoft.Json.JsonProperty("meta", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Meta Meta { get; set; } = new Meta(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response32 + { + [Newtonsoft.Json.JsonProperty("error", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Error { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response33 + { + [Newtonsoft.Json.JsonProperty("error", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Error { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Response returned by x402 facilitator 'verify' + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response34 + { + [Newtonsoft.Json.JsonProperty("isValid", Required = Newtonsoft.Json.Required.Always)] + public bool IsValid { get; set; } + + [Newtonsoft.Json.JsonProperty("invalidReason", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public Response34InvalidReason InvalidReason { get; set; } + + [Newtonsoft.Json.JsonProperty("payer", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public Payer Payer { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Response returned by x402 facilitator 'settle' + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response35 + { + [Newtonsoft.Json.JsonProperty("success", Required = Newtonsoft.Json.Required.Always)] + public bool Success { get; set; } + + [Newtonsoft.Json.JsonProperty("errorReason", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public Response35ErrorReason ErrorReason { get; set; } + + [Newtonsoft.Json.JsonProperty("payer", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public Payer2 Payer { get; set; } + + [Newtonsoft.Json.JsonProperty("transaction", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [System.ComponentModel.DataAnnotations.RegularExpression(@"^0x[a-fA-F0-9]{40}|[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$")] + public string Transaction { get; set; } + + [Newtonsoft.Json.JsonProperty("network", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public Response35Network Network { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Supported payment kinds for this facilitator + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response36 + { + [Newtonsoft.Json.JsonProperty("kinds", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Kinds { get; set; } = new System.Collections.ObjectModel.Collection(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response37 + { + /// + /// The in-progress deployment transaction ID. + /// + [Newtonsoft.Json.JsonProperty("transactionId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string TransactionId { get; set; } + + /// + /// The address the token was deployed at + /// + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Address { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response38 + { + [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Pagination Pagination { get; set; } = new Pagination(); + + [Newtonsoft.Json.JsonProperty("tokens", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Tokens { get; set; } = new System.Collections.ObjectModel.Collection(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response39 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result27 Result { get; set; } = new Result27(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response40 + { + /// + /// Blockchain networks that support cross-chain bridging + /// + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Result { get; set; } = new System.Collections.ObjectModel.Collection(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response41 + { + /// + /// The conversion result - amount of crypto tokens for the fiat amount + /// + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + public double Result { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Successful token swap response containing executed transaction ID + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response42 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result29 Result { get; set; } = new Result29(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Payment required response when user has insufficient funds. Contains a quote for completing the purchase. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response43 + { + [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Result30 Result { get; set; } = new Result30(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Chat response + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Response44 + { + /// + /// The AI assistant's response + /// + [Newtonsoft.Json.JsonProperty("message", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Message { get; set; } + + [Newtonsoft.Json.JsonProperty("actions", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Actions { get; set; } = new System.Collections.ObjectModel.Collection(); + + [Newtonsoft.Json.JsonProperty("session_id", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Session_id { get; set; } + + [Newtonsoft.Json.JsonProperty("request_id", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Request_id { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum BodyMethod + { + + [System.Runtime.Serialization.EnumMember(Value = @"sms")] + Sms = 0, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Body2Method + { + + [System.Runtime.Serialization.EnumMember(Value = @"sms")] + Sms = 0, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Body3Type + { + + [System.Runtime.Serialization.EnumMember(Value = @"google")] + Google = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"apple")] + Apple = 1, + + [System.Runtime.Serialization.EnumMember(Value = @"facebook")] + Facebook = 2, + + [System.Runtime.Serialization.EnumMember(Value = @"discord")] + Discord = 3, + + [System.Runtime.Serialization.EnumMember(Value = @"email")] + Email = 4, + + [System.Runtime.Serialization.EnumMember(Value = @"phone")] + Phone = 5, + + [System.Runtime.Serialization.EnumMember(Value = @"custom_auth_endpoint")] + Custom_auth_endpoint = 6, + + [System.Runtime.Serialization.EnumMember(Value = @"custom_jwt")] + Custom_jwt = 7, + + [System.Runtime.Serialization.EnumMember(Value = @"siwe")] + Siwe = 8, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Domain + { + /// + /// Chain ID as string for domain separation + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string ChainId { get; set; } + + /// + /// The domain name (e.g., token name) + /// + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Name { get; set; } + + /// + /// Optional salt for additional entropy + /// + [Newtonsoft.Json.JsonProperty("salt", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Salt { get; set; } + + /// + /// The contract address that will verify this signature + /// + [Newtonsoft.Json.JsonProperty("verifyingContract", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string VerifyingContract { get; set; } + + /// + /// Domain version for signature compatibility + /// + [Newtonsoft.Json.JsonProperty("version", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Version { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Anonymous + { + /// + /// The field name + /// + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Name { get; set; } + + /// + /// The Solidity type (e.g., 'address', 'uint256') + /// + [Newtonsoft.Json.JsonProperty("type", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Type { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Recipients + { + /// + /// The recipient wallet address or ENS name + /// + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Address { get; set; } + + /// + /// The amount to send. For native tokens and ERC20: amount in wei/smallest unit. For ERC721: should be '1'. For ERC1155: the number of tokens to transfer. + /// + [Newtonsoft.Json.JsonProperty("quantity", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Quantity { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Calls + { + /// + /// The smart contract address or ENS name. + /// + [Newtonsoft.Json.JsonProperty("contractAddress", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string ContractAddress { get; set; } + + /// + /// The contract function signature to call (e.g., 'function approve(address spender, uint256 amount)' or `function balanceOf(address)`). Must start with 'function' followed by the function name and parameters as defined in the contract ABI. + /// + [Newtonsoft.Json.JsonProperty("method", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [System.ComponentModel.DataAnnotations.RegularExpression(@"^function\s+\w+")] + public string Method { get; set; } + + /// + /// Array of parameters to pass to the contract method, in the correct order and format. + /// + [Newtonsoft.Json.JsonProperty("params", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.ICollection Params { get; set; } + + /// + /// Amount of native token to send with the transaction in wei. Required for payable methods. + /// + [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Value { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class calls + { + /// + /// The smart contract address or ENS name. + /// + [Newtonsoft.Json.JsonProperty("contractAddress", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string ContractAddress { get; set; } + + /// + /// The contract function signature to call (e.g., 'function approve(address spender, uint256 amount)' or `function balanceOf(address)`). Must start with 'function' followed by the function name and parameters as defined in the contract ABI. + /// + [Newtonsoft.Json.JsonProperty("method", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [System.ComponentModel.DataAnnotations.RegularExpression(@"^function\s+\w+")] + public string Method { get; set; } + + /// + /// Array of parameters to pass to the contract method, in the correct order and format. + /// + [Newtonsoft.Json.JsonProperty("params", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.ICollection Params { get; set; } + + /// + /// Amount of native token to send with the transaction in wei. Required for payable methods. + /// + [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Value { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// A blockchain transaction with pre-encoded data payload. For contract calls, use /v1/contracts/write. For native token transfers, use /v1/wallets/send. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Transactions + { + /// + /// Transaction data in hexadecimal format for contract interactions or custom payloads. + /// + [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Data { get; set; } + + /// + /// The target address or ENS name for the transaction. + /// + [Newtonsoft.Json.JsonProperty("to", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string To { get; set; } + + /// + /// Amount of native token to send in wei (smallest unit). Use '0' or omit for non-value transactions. + /// + [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Value { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Token + { + /// + /// The token address to purchase (use 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for native token) + /// + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Address { get; set; } + + /// + /// The blockchain network where the token is located + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } + + /// + /// The amount of the token to purchase in wei. + /// + [Newtonsoft.Json.JsonProperty("amount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Amount { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class PaymentPayload + { + [Newtonsoft.Json.JsonProperty("x402Version", Required = Newtonsoft.Json.Required.Always)] + public double X402Version { get; set; } + + [Newtonsoft.Json.JsonProperty("scheme", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public PaymentPayloadScheme Scheme { get; set; } + + [Newtonsoft.Json.JsonProperty("network", Required = Newtonsoft.Json.Required.Always)] + public Network Network { get; set; } + + [Newtonsoft.Json.JsonProperty("payload", Required = Newtonsoft.Json.Required.Always)] + public Payload Payload { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class PaymentRequirements + { + [Newtonsoft.Json.JsonProperty("scheme", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public PaymentRequirementsScheme Scheme { get; set; } + + [Newtonsoft.Json.JsonProperty("network", Required = Newtonsoft.Json.Required.Always)] + public Network2 Network { get; set; } + + [Newtonsoft.Json.JsonProperty("maxAmountRequired", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string MaxAmountRequired { get; set; } + + [Newtonsoft.Json.JsonProperty("resource", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public System.Uri Resource { get; set; } + + [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Description { get; set; } + + [Newtonsoft.Json.JsonProperty("mimeType", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string MimeType { get; set; } + + [Newtonsoft.Json.JsonProperty("outputSchema", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.IDictionary OutputSchema { get; set; } + + [Newtonsoft.Json.JsonProperty("payTo", Required = Newtonsoft.Json.Required.Always)] + public PayTo PayTo { get; set; } + + [Newtonsoft.Json.JsonProperty("maxTimeoutSeconds", Required = Newtonsoft.Json.Required.Always)] + public int MaxTimeoutSeconds { get; set; } + + [Newtonsoft.Json.JsonProperty("asset", Required = Newtonsoft.Json.Required.Always)] + public Asset Asset { get; set; } + + [Newtonsoft.Json.JsonProperty("extra", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.IDictionary Extra { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class PaymentPayload2 + { + [Newtonsoft.Json.JsonProperty("x402Version", Required = Newtonsoft.Json.Required.Always)] + public double X402Version { get; set; } + + [Newtonsoft.Json.JsonProperty("scheme", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public PaymentPayload2Scheme Scheme { get; set; } + + [Newtonsoft.Json.JsonProperty("network", Required = Newtonsoft.Json.Required.Always)] + public Network3 Network { get; set; } + + [Newtonsoft.Json.JsonProperty("payload", Required = Newtonsoft.Json.Required.Always)] + public Payload2 Payload { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class PaymentRequirements2 + { + [Newtonsoft.Json.JsonProperty("scheme", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public PaymentRequirements2Scheme Scheme { get; set; } + + [Newtonsoft.Json.JsonProperty("network", Required = Newtonsoft.Json.Required.Always)] + public Network4 Network { get; set; } + + [Newtonsoft.Json.JsonProperty("maxAmountRequired", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string MaxAmountRequired { get; set; } + + [Newtonsoft.Json.JsonProperty("resource", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public System.Uri Resource { get; set; } + + [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Description { get; set; } + + [Newtonsoft.Json.JsonProperty("mimeType", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string MimeType { get; set; } + + [Newtonsoft.Json.JsonProperty("outputSchema", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.IDictionary OutputSchema { get; set; } + + [Newtonsoft.Json.JsonProperty("payTo", Required = Newtonsoft.Json.Required.Always)] + public PayTo2 PayTo { get; set; } + + [Newtonsoft.Json.JsonProperty("maxTimeoutSeconds", Required = Newtonsoft.Json.Required.Always)] + public int MaxTimeoutSeconds { get; set; } + + [Newtonsoft.Json.JsonProperty("asset", Required = Newtonsoft.Json.Required.Always)] + public Asset2 Asset { get; set; } + + [Newtonsoft.Json.JsonProperty("extra", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.IDictionary Extra { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Sale + { + [Newtonsoft.Json.JsonProperty("type", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public SaleType Type { get; set; } = Thirdweb.Api.SaleType.Pool; + + /// + /// The initial token price in wei. This price is in the currency specified by `currency` (or the native token if not specified). + /// + [Newtonsoft.Json.JsonProperty("startingPrice", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string StartingPrice { get; set; } + + /// + /// The number of tokens to allocate to the sale. + /// + [Newtonsoft.Json.JsonProperty("amount", Required = Newtonsoft.Json.Required.Always)] + public double Amount { get; set; } + + /// + /// The bps fee on the token pool. + /// + [Newtonsoft.Json.JsonProperty("developerFeeBps", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double DeveloperFeeBps { get; set; } + + /// + /// The address to send the developer fee to. Defaults to the token owner. + /// + [Newtonsoft.Json.JsonProperty("developerFeeRecipient", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string DeveloperFeeRecipient { get; set; } + + /// + /// The currency to price this token sale in. Defaults to the native token. + /// + [Newtonsoft.Json.JsonProperty("currency", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Currency { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Body17Exact + { + + [System.Runtime.Serialization.EnumMember(Value = @"input")] + Input = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"output")] + Output = 1, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class TokenIn + { + /// + /// The input token address to swap (use 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for native token) + /// + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Address { get; set; } + + /// + /// The blockchain network where the token is located + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } + + /// + /// The amount of the input token to swap in wei. + /// + [Newtonsoft.Json.JsonProperty("amount", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Amount { get; set; } + + /// + /// The maximum amount of the input token to swap in wei. + /// + [Newtonsoft.Json.JsonProperty("maxAmount", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string MaxAmount { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class TokenOut + { + /// + /// The output token address to swap (use 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for native token) + /// + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Address { get; set; } + + /// + /// The blockchain network where the token is located + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } + + /// + /// The amount of the output token to receive in wei. + /// + [Newtonsoft.Json.JsonProperty("amount", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Amount { get; set; } + + /// + /// The minimum amount of the output token to receive in wei. + /// + [Newtonsoft.Json.JsonProperty("minAmount", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string MinAmount { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Messages + { + [Newtonsoft.Json.JsonProperty("role", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public MessagesRole Role { get; set; } + + [Newtonsoft.Json.JsonProperty("content", Required = Newtonsoft.Json.Required.Always)] + public Content Content { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Context { /// - /// Authentication method: SMS + /// Optional wallet address that will execute transactions /// - [Newtonsoft.Json.JsonProperty("method", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] - public BodyMethod Method { get; set; } + [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string From { get; set; } /// - /// Phone number in E.164 format (e.g., +1234567890) + /// Optional chain IDs for context /// - [Newtonsoft.Json.JsonProperty("phone", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Phone { get; set; } + [Newtonsoft.Json.JsonProperty("chain_ids", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.ICollection Chain_ids { get; set; } + + /// + /// Optional session ID for conversation continuity. If not provided, a new session will be created + /// + [Newtonsoft.Json.JsonProperty("session_id", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Session_id { get; set; } + + /// + /// Whether to automatically execute transactions. If not provided, the default is false + /// + [Newtonsoft.Json.JsonProperty("auto_execute_transactions", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public bool Auto_execute_transactions { get; set; } = false; private System.Collections.Generic.IDictionary _additionalProperties; @@ -4755,29 +8422,254 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Body2 + public enum ResponseMethod + { + + [System.Runtime.Serialization.EnumMember(Value = @"sms")] + Sms = 0, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Result { /// - /// Authentication method: SMS + /// The EOA (Externally Owned Wallet) address of the wallet. This is the traditional wallet address. /// - [Newtonsoft.Json.JsonProperty("method", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Address { get; set; } + + /// + /// The date and time the wallet was created + /// + [Newtonsoft.Json.JsonProperty("createdAt", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string CreatedAt { get; set; } + + /// + /// The profiles linked to the wallet, can be email, phone, google etc, or backend for developer created wallets + /// + [Newtonsoft.Json.JsonProperty("profiles", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Profiles { get; set; } = new System.Collections.ObjectModel.Collection(); + + /// + /// The smart wallet address with EIP-4337 support. This address enables gasless transactions and advanced wallet features. + /// + [Newtonsoft.Json.JsonProperty("smartWalletAddress", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string SmartWalletAddress { get; set; } + + /// + /// The wallet's public key in hexadecimal format. Useful for peer-to-peer encryption and cryptographic operations. + /// + [Newtonsoft.Json.JsonProperty("publicKey", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string PublicKey { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Result2 + { + /// + /// Pagination information + /// + [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Pagination2 Pagination { get; set; } = new Pagination2(); + + /// + /// Array of user wallets + /// + [Newtonsoft.Json.JsonProperty("wallets", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Wallets { get; set; } = new System.Collections.ObjectModel.Collection(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Result3 + { + /// + /// The EOA (Externally Owned Wallet) address of the wallet. This is the traditional wallet address. + /// + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Address { get; set; } + + /// + /// The date and time the wallet was created + /// + [Newtonsoft.Json.JsonProperty("createdAt", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string CreatedAt { get; set; } + + /// + /// The profiles linked to the wallet, can be email, phone, google etc, or backend for developer created wallets + /// + [Newtonsoft.Json.JsonProperty("profiles", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Profiles { get; set; } = new System.Collections.ObjectModel.Collection(); + + /// + /// The smart wallet address with EIP-4337 support. This address enables gasless transactions and advanced wallet features. + /// + [Newtonsoft.Json.JsonProperty("smartWalletAddress", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string SmartWalletAddress { get; set; } + + /// + /// The wallet's public key in hexadecimal format. Useful for peer-to-peer encryption and cryptographic operations. + /// + [Newtonsoft.Json.JsonProperty("publicKey", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string PublicKey { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Result4 + { + /// + /// Pagination information + /// + [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Pagination3 Pagination { get; set; } = new Pagination3(); + + /// + /// Array of server wallets + /// + [Newtonsoft.Json.JsonProperty("wallets", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Wallets { get; set; } = new System.Collections.ObjectModel.Collection(); + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Result5 + { + /// + /// The EOA (Externally Owned Wallet) address of the wallet. This is the traditional wallet address. + /// + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Address { get; set; } + + /// + /// The date and time the wallet was created + /// + [Newtonsoft.Json.JsonProperty("createdAt", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string CreatedAt { get; set; } + + /// + /// The profiles linked to the wallet, can be email, phone, google etc, or backend for developer created wallets + /// + [Newtonsoft.Json.JsonProperty("profiles", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Profiles { get; set; } = new System.Collections.ObjectModel.Collection(); + + /// + /// The smart wallet address with EIP-4337 support. This address enables gasless transactions and advanced wallet features. + /// + [Newtonsoft.Json.JsonProperty("smartWalletAddress", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string SmartWalletAddress { get; set; } + + /// + /// The wallet's public key in hexadecimal format. Useful for peer-to-peer encryption and cryptographic operations. + /// + [Newtonsoft.Json.JsonProperty("publicKey", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string PublicKey { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class result + { + /// + /// The blockchain network ID + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + public double ChainId { get; set; } + + /// + /// Number of decimal places for the token + /// + [Newtonsoft.Json.JsonProperty("decimals", Required = Newtonsoft.Json.Required.Always)] + public double Decimals { get; set; } + + /// + /// Human-readable balance formatted with appropriate decimal places + /// + [Newtonsoft.Json.JsonProperty("displayValue", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] - public Body2Method Method { get; set; } + public string DisplayValue { get; set; } /// - /// Phone number that received the code + /// The token name (e.g., 'Ether', 'USD Coin') + /// + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Name { get; set; } + + /// + /// The token symbol (e.g., 'ETH', 'USDC') + /// + [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Symbol { get; set; } + + /// + /// The token contract address. Returns zero address (0x0...0) for native tokens. /// - [Newtonsoft.Json.JsonProperty("phone", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("tokenAddress", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Phone { get; set; } + public string TokenAddress { get; set; } /// - /// Verification code received via SMS + /// Raw balance value as string in smallest unit (wei for ETH, etc.) /// - [Newtonsoft.Json.JsonProperty("code", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Code { get; set; } + public string Value { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -4790,28 +8682,19 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Request body for pre-generating a wallet - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Body3 + public partial class Result6 { - [Newtonsoft.Json.JsonProperty("type", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] - public Body3Type Type { get; set; } - - [Newtonsoft.Json.JsonProperty("walletAddress", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string WalletAddress { get; set; } - - [Newtonsoft.Json.JsonProperty("email", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Email { get; set; } - - [Newtonsoft.Json.JsonProperty("phone", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Phone { get; set; } + [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Pagination4 Pagination { get; set; } = new Pagination4(); - [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string UserId { get; set; } + /// + /// Array of wallet transactions. + /// + [Newtonsoft.Json.JsonProperty("transactions", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Transactions { get; set; } = new System.Collections.ObjectModel.Collection(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -4824,18 +8707,19 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Request body for creating a wallet - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Body4 + public partial class Result7 { + [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Pagination5 Pagination { get; set; } = new Pagination5(); + /// - /// Unique identifier for wallet creation or retrieval. Can be user ID, email, or any unique string. The same identifier will always return the same wallet. + /// Array of wallet tokens. /// - [Newtonsoft.Json.JsonProperty("identifier", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("tokens", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - public string Identifier { get; set; } + public System.Collections.Generic.ICollection Tokens { get; set; } = new System.Collections.ObjectModel.Collection(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -4848,47 +8732,19 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Sort order: 'asc' for ascending, 'desc' for descending - /// - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public enum SortOrder - { - - [System.Runtime.Serialization.EnumMember(Value = @"asc")] - Asc = 0, - - [System.Runtime.Serialization.EnumMember(Value = @"desc")] - Desc = 1, - - } - - /// - /// Request body for signing a message - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Body5 + public partial class Result8 { /// - /// The wallet address or ENS name that will sign the message. - /// - [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string From { get; set; } - - /// - /// The blockchain network identifier where the signing will occur. Common values include: 1 (Ethereum), 137 (Polygon), 56 (BSC). + /// Array of wallet NFTs. /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] - public int ChainId { get; set; } + [Newtonsoft.Json.JsonProperty("nfts", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Nfts { get; set; } = new System.Collections.ObjectModel.Collection(); - /// - /// The message to be signed. Can be plain text or hexadecimal format (starting with 0x). The format is automatically detected. - /// - [Newtonsoft.Json.JsonProperty("message", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Message { get; set; } + [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Pagination6 Pagination { get; set; } = new Pagination6(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -4901,53 +8757,15 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Request body for signing typed data - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Body6 + public partial class Result9 { /// - /// The wallet address or ENS name that will sign the typed data. - /// - [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string From { get; set; } - - /// - /// The blockchain network identifier for EIP-712 domain separation. - /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] - public int ChainId { get; set; } - - /// - /// EIP-712 domain separator containing contract and chain information for signature verification. - /// - [Newtonsoft.Json.JsonProperty("domain", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Domain Domain { get; set; } = new Domain(); - - /// - /// The structured data to be signed, matching the defined types schema. - /// - [Newtonsoft.Json.JsonProperty("message", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.Dictionary Message { get; set; } = new System.Collections.Generic.Dictionary(); - - /// - /// The primary type name from the types object that defines the main structure being signed. + /// The cryptographic signature in hexadecimal format. This can be used for verification and authentication purposes. /// - [Newtonsoft.Json.JsonProperty("primaryType", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("signature", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string PrimaryType { get; set; } - - /// - /// Type definitions for the structured data, following EIP-712 specifications. - /// - [Newtonsoft.Json.JsonProperty("types", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.Dictionary> Types { get; set; } = new System.Collections.Generic.Dictionary>(); + public string Signature { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -4960,46 +8778,15 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Request body for sending tokens to multiple recipients. Supports native tokens, ERC20, ERC721, and ERC1155 transfers based on the provided parameters. - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Body7 + public partial class Result10 { /// - /// The wallet address or ENS name that will send the tokens. + /// The cryptographic signature in hexadecimal format. This can be used for verification and authentication purposes. /// - [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("signature", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string From { get; set; } - - /// - /// The blockchain network identifier where the transfer will be executed. - /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] - public int ChainId { get; set; } - - /// - /// Array of recipients and quantities. Maximum 100 recipients per request. - /// - [Newtonsoft.Json.JsonProperty("recipients", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - [System.ComponentModel.DataAnnotations.MinLength(1)] - [System.ComponentModel.DataAnnotations.MaxLength(100)] - public System.Collections.Generic.List Recipients { get; set; } = new System.Collections.Generic.List(); - - /// - /// The token contract address. Omit for native token (ETH, MATIC, etc.) transfers. - /// - [Newtonsoft.Json.JsonProperty("tokenAddress", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string TokenAddress { get; set; } - - /// - /// The token ID for NFT transfers (ERC721/ERC1155). Required for NFT transfers. - /// - [Newtonsoft.Json.JsonProperty("tokenId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string TokenId { get; set; } + public string Signature { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -5012,51 +8799,15 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Contract deployment specification for raw bytecode deployment. - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Body8 + public partial class Result11 { /// - /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). - /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] - public int ChainId { get; set; } - - /// - /// The wallet address or ENS name that will deploy the contract. - /// - [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string From { get; set; } - - /// - /// The contract bytecode as a hex string. - /// - [Newtonsoft.Json.JsonProperty("bytecode", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Bytecode { get; set; } - - /// - /// The contract ABI array. + /// Array of transaction IDs for the submitted transfers. One ID per recipient. /// - [Newtonsoft.Json.JsonProperty("abi", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("transactionIds", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Abi { get; set; } = new System.Collections.Generic.List(); - - /// - /// Object containing constructor parameters for the contract deployment (e.g., { param1: 'value1', param2: 123 }). - /// - [Newtonsoft.Json.JsonProperty("constructorParams", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.Generic.Dictionary ConstructorParams { get; set; } - - /// - /// Optional salt value for deterministic contract deployment. - /// - [Newtonsoft.Json.JsonProperty("salt", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Salt { get; set; } + public System.Collections.Generic.ICollection TransactionIds { get; set; } = new System.Collections.ObjectModel.Collection(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -5070,22 +8821,18 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Body9 + public partial class Result12 { /// - /// Array of contract method calls to execute. Each call specifies a contract address, method signature, and optional parameters. + /// Array of contracts imported by the client. /// - [Newtonsoft.Json.JsonProperty("calls", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("contracts", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - [System.ComponentModel.DataAnnotations.MinLength(1)] - public System.Collections.Generic.List Calls { get; set; } = new System.Collections.Generic.List(); + public System.Collections.Generic.ICollection Contracts { get; set; } = new System.Collections.ObjectModel.Collection(); - /// - /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). - /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] - public int ChainId { get; set; } + [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Pagination7 Pagination { get; set; } = new Pagination7(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -5099,29 +8846,26 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Body10 + public partial class Result13 { /// - /// Array of contract method calls to execute. Each call specifies a contract address, method signature, and optional parameters. + /// The deployed contract address. /// - [Newtonsoft.Json.JsonProperty("calls", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - [System.ComponentModel.DataAnnotations.MinLength(1)] - public System.Collections.Generic.List Calls { get; set; } = new System.Collections.Generic.List(); + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Address { get; set; } /// - /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). + /// The chain ID where the contract was deployed. /// [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] - public int ChainId { get; set; } + public double ChainId { get; set; } /// - /// The wallet address or ENS name that will send the transaction. + /// The unique identifier for the transaction that deployed the contract. Will not be returned if the contract was already deployed at the predicted address. /// - [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string From { get; set; } + [Newtonsoft.Json.JsonProperty("transactionId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string TransactionId { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -5134,63 +8878,26 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Sort order: 'asc' for ascending, 'desc' for descending - /// - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public enum SortOrder2 - { - - [System.Runtime.Serialization.EnumMember(Value = @"asc")] - Asc = 0, - - [System.Runtime.Serialization.EnumMember(Value = @"desc")] - Desc = 1, - - } - - /// - /// Sort order: 'asc' for ascending, 'desc' for descending - /// - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public enum SortOrder3 - { - - [System.Runtime.Serialization.EnumMember(Value = @"asc")] - Asc = 0, - - [System.Runtime.Serialization.EnumMember(Value = @"desc")] - Desc = 1, - - } - - /// - /// Request object containing an array of encoded blockchain transactions to execute. All transactions must use the same from address and chainId. For contract calls, use /v1/contracts/write. For native token transfers, use /v1/wallets/send. - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Body11 + public partial class Result14 { /// - /// The blockchain network identifier where all transactions will be executed. + /// The result of the contract read operation. The type and format depend on the method's return value as defined in the contract ABI. /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] - public int ChainId { get; set; } + [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public object Data { get; set; } /// - /// The wallet address or ENS name that will send the transaction. + /// Error message if the contract read operation failed. /// - [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string From { get; set; } + [Newtonsoft.Json.JsonProperty("error", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Error { get; set; } /// - /// Array of encoded blockchain transactions to execute. All transactions will use the same from address and chainId. + /// Indicates whether the contract read operation was successful. /// - [Newtonsoft.Json.JsonProperty("transactions", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - [System.ComponentModel.DataAnnotations.MinLength(1)] - public System.Collections.Generic.List Transactions { get; set; } = new System.Collections.Generic.List(); + [Newtonsoft.Json.JsonProperty("success", Required = Newtonsoft.Json.Required.Always)] + public bool Success { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -5203,33 +8910,15 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Request to swap tokens using the optimal route available. You can specify a tokenIn amount (if exact='input') or tokenOut amount (if exact='output'), but not both. The corresponding output or input amount will be returned as the quote. - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Body12 + public partial class Result15 { /// - /// Whether to swap the exact input or output amount + /// Array of unique identifiers for the submitted transactions. Use these to track transaction status. /// - [Newtonsoft.Json.JsonProperty("exact", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] - public Body12Exact Exact { get; set; } = Thirdweb.Api.Body12Exact.Input; - - [Newtonsoft.Json.JsonProperty("tokenIn", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public TokenIn TokenIn { get; set; } = new TokenIn(); - - [Newtonsoft.Json.JsonProperty("tokenOut", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("transactionIds", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - public TokenOut TokenOut { get; set; } = new TokenOut(); - - /// - /// The wallet address or ENS name that will execute the swap. - /// - [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string From { get; set; } + public System.Collections.Generic.ICollection TransactionIds { get; set; } = new System.Collections.ObjectModel.Collection(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -5242,51 +8931,54 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Request to create a product to be purchased. Users can purchase the product via hosted UI (link is returned), a transaction execution referencing the product ID, or embedded widgets with the product ID. - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Body13 + public partial class Result16 { /// - /// The name of the product + /// Link to purchase the product /// - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("link", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Name { get; set; } + public string Link { get; set; } /// - /// The description of the product + /// Payment ID /// - [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Description { get; set; } - - /// - /// The URL of the product image - /// - [Newtonsoft.Json.JsonProperty("imageUrl", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string ImageUrl { get; set; } + public string Id { get; set; } /// - /// The token to purchase + /// Bridge quote for completing the payment /// - [Newtonsoft.Json.JsonProperty("token", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("quote", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - public Token Token { get; set; } = new Token(); + public Quote Quote { get; set; } = new Quote(); - /// - /// The wallet address or ENS name that will receive the payment for the product - /// - [Newtonsoft.Json.JsonProperty("recipient", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Recipient { get; set; } + private System.Collections.Generic.IDictionary _additionalProperties; + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Result17 + { /// - /// App specific purchase data for this payment + /// Array of contract transactions. /// - [Newtonsoft.Json.JsonProperty("purchaseData", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public object PurchaseData { get; set; } + [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Data { get; set; } = new System.Collections.ObjectModel.Collection(); + + [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Pagination8 Pagination { get; set; } = new Pagination8(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -5299,18 +8991,19 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Request to purchase a product. The system will automatically use your wallet balance to purchase the specified product. - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Body14 + public partial class Result18 { /// - /// The wallet address or ENS name that will purchase the product. + /// Array of contract events. /// - [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string From { get; set; } + [Newtonsoft.Json.JsonProperty("events", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Events { get; set; } = new System.Collections.ObjectModel.Collection(); + + [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Pagination9 Pagination { get; set; } = new Pagination9(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -5323,56 +9016,38 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Request schema for creating a new ERC20 token - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Body15 + public partial class Result19 { /// - /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). - /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] - public int ChainId { get; set; } - - /// - /// Token name + /// Compiler information including version. /// - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength = 1)] - public string Name { get; set; } + [Newtonsoft.Json.JsonProperty("compiler", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public Compiler Compiler { get; set; } /// - /// Token symbol + /// Programming language of the contract (e.g., 'Solidity'). /// - [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - [System.ComponentModel.DataAnnotations.StringLength(20, MinimumLength = 1)] - public string Symbol { get; set; } + [Newtonsoft.Json.JsonProperty("language", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Language { get; set; } /// - /// Token description + /// Compilation output including ABI and documentation. /// - [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - [System.ComponentModel.DataAnnotations.StringLength(500, MinimumLength = 1)] - public string Description { get; set; } + [Newtonsoft.Json.JsonProperty("output", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public Output Output { get; set; } /// - /// Token image URL + /// Compilation settings including optimization and target configuration. /// - [Newtonsoft.Json.JsonProperty("imageUrl", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public System.Uri ImageUrl { get; set; } + [Newtonsoft.Json.JsonProperty("settings", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public Settings Settings { get; set; } /// - /// Wallet address or ENS that will deploy the token. + /// Metadata format version. /// - [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string From { get; set; } + [Newtonsoft.Json.JsonProperty("version", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double Version { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -5385,101 +9060,109 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Chat request - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Body16 + public partial class Result20 { /// - /// Natural language query for the AI assistant + /// Index within transaction batch /// - [Newtonsoft.Json.JsonProperty("messages", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - [System.ComponentModel.DataAnnotations.MinLength(1)] - public System.Collections.Generic.List Messages { get; set; } = new System.Collections.Generic.List(); + [Newtonsoft.Json.JsonProperty("batchIndex", Required = Newtonsoft.Json.Required.Always)] + public int BatchIndex { get; set; } - [Newtonsoft.Json.JsonProperty("context", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Context Context { get; set; } = new Context(); + /// + /// ISO timestamp when transaction was cancelled, if applicable + /// + [Newtonsoft.Json.JsonProperty("cancelledAt", Required = Newtonsoft.Json.Required.AllowNull)] + public string CancelledAt { get; set; } /// - /// Enable server streaming of the AI response + /// Blockchain network identifier as string /// - [Newtonsoft.Json.JsonProperty("stream", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public bool Stream { get; set; } + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string ChainId { get; set; } - private System.Collections.Generic.IDictionary _additionalProperties; + /// + /// Client identifier that initiated the transaction + /// + [Newtonsoft.Json.JsonProperty("clientId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string ClientId { get; set; } - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + /// + /// ISO timestamp when transaction was confirmed on-chain + /// + [Newtonsoft.Json.JsonProperty("confirmedAt", Required = Newtonsoft.Json.Required.AllowNull)] + public string ConfirmedAt { get; set; } - } + /// + /// Block number where transaction was confirmed + /// + [Newtonsoft.Json.JsonProperty("confirmedAtBlockNumber", Required = Newtonsoft.Json.Required.AllowNull)] + public string ConfirmedAtBlockNumber { get; set; } - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response - { /// - /// Authentication method: SMS + /// ISO timestamp when transaction was created /// - [Newtonsoft.Json.JsonProperty("method", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("createdAt", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] - public ResponseMethod Method { get; set; } + public string CreatedAt { get; set; } /// - /// Whether the SMS code was sent successfully + /// Additional metadata and enriched transaction information /// - [Newtonsoft.Json.JsonProperty("success", Required = Newtonsoft.Json.Required.Always)] - public bool Success { get; set; } + [Newtonsoft.Json.JsonProperty("enrichedData", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public object EnrichedData { get; set; } - private System.Collections.Generic.IDictionary _additionalProperties; + /// + /// Error message if transaction failed + /// + [Newtonsoft.Json.JsonProperty("errorMessage", Required = Newtonsoft.Json.Required.AllowNull)] + public string ErrorMessage { get; set; } - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + /// + /// Parameters used for transaction execution + /// + [Newtonsoft.Json.JsonProperty("executionParams", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public object ExecutionParams { get; set; } - } + /// + /// Result data from transaction execution + /// + [Newtonsoft.Json.JsonProperty("executionResult", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public object ExecutionResult { get; set; } - /// - /// Successful authentication response. Returns wallet address plus authentication tokens. - /// - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response2 - { /// - /// Whether this is a newly created user/wallet + /// Sender wallet address /// - [Newtonsoft.Json.JsonProperty("isNewUser", Required = Newtonsoft.Json.Required.Always)] - public bool IsNewUser { get; set; } + [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.AllowNull)] + public string From { get; set; } /// - /// JWT authentication token for API access + /// Unique transaction identifier /// - [Newtonsoft.Json.JsonProperty("token", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Token { get; set; } + public string Id { get; set; } /// - /// Type of authentication completed + /// On-chain transaction hash once confirmed /// - [Newtonsoft.Json.JsonProperty("type", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Type { get; set; } + [Newtonsoft.Json.JsonProperty("transactionHash", Required = Newtonsoft.Json.Required.AllowNull)] + public string TransactionHash { get; set; } /// - /// The wallet address + /// Original transaction parameters and data /// - [Newtonsoft.Json.JsonProperty("walletAddress", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string WalletAddress { get; set; } + [Newtonsoft.Json.JsonProperty("transactionParams", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public object TransactionParams { get; set; } + + /// + /// Transaction status + /// + [Newtonsoft.Json.JsonProperty("status", Required = Newtonsoft.Json.Required.AllowNull)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public Result20Status? Status { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -5493,29 +9176,15 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response3 + public partial class Result21 { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - public Result Result { get; set; } = new Result(); - - private System.Collections.Generic.IDictionary _additionalProperties; - - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } - - } + public Pagination10 Pagination { get; set; } = new Pagination10(); - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response4 - { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("transactions", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - public Result2 Result { get; set; } = new Result2(); + public System.Collections.Generic.ICollection Transactions { get; set; } = new System.Collections.ObjectModel.Collection(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -5529,11 +9198,14 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response5 + public partial class Result22 { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + /// + /// Array of unique identifiers for the submitted transactions. Use these to track transaction status. + /// + [Newtonsoft.Json.JsonProperty("transactionIds", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - public Result3 Result { get; set; } = new Result3(); + public System.Collections.Generic.ICollection TransactionIds { get; set; } = new System.Collections.ObjectModel.Collection(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -5547,11 +9219,28 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response6 + public partial class Result23 { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + /// + /// Link to purchase the product + /// + [Newtonsoft.Json.JsonProperty("link", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Link { get; set; } + + /// + /// Payment ID + /// + [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Id { get; set; } + + /// + /// Bridge quote for completing the payment + /// + [Newtonsoft.Json.JsonProperty("quote", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - public Result4 Result { get; set; } = new Result4(); + public Quote2 Quote { get; set; } = new Quote2(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -5565,11 +9254,21 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response7 + public partial class Result24 { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Result5 Result { get; set; } = new Result5(); + /// + /// The payment ID + /// + [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Id { get; set; } + + /// + /// The link to purchase the product + /// + [Newtonsoft.Json.JsonProperty("link", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Link { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -5583,11 +9282,14 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response8 + public partial class Result25 { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Result { get; set; } = new System.Collections.Generic.List(); + /// + /// Transaction ID that was executed for your product purchase + /// + [Newtonsoft.Json.JsonProperty("transactionId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string TransactionId { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -5601,11 +9303,28 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response9 + public partial class Result26 { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + /// + /// Link to purchase the product + /// + [Newtonsoft.Json.JsonProperty("link", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Link { get; set; } + + /// + /// Payment ID + /// + [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Id { get; set; } + + /// + /// Bridge quote for completing the payment + /// + [Newtonsoft.Json.JsonProperty("quote", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - public Result6 Result { get; set; } = new Result6(); + public Quote3 Quote { get; set; } = new Quote3(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -5619,83 +9338,87 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response10 + public partial class Data { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Result7 Result { get; set; } = new Result7(); + [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Id { get; set; } - private System.Collections.Generic.IDictionary _additionalProperties; + [Newtonsoft.Json.JsonProperty("blockNumber", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + [System.ComponentModel.DataAnnotations.RegularExpression(@"^\d+$")] + public string BlockNumber { get; set; } - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + [Newtonsoft.Json.JsonProperty("transactionId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string TransactionId { get; set; } - } + [Newtonsoft.Json.JsonProperty("onrampId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string OnrampId { get; set; } - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response11 - { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Result8 Result { get; set; } = new Result8(); + [Newtonsoft.Json.JsonProperty("clientId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string ClientId { get; set; } - private System.Collections.Generic.IDictionary _additionalProperties; + /// + /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). + /// + [Newtonsoft.Json.JsonProperty("sender", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Sender { get; set; } - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + /// + /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). + /// + [Newtonsoft.Json.JsonProperty("receiver", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Receiver { get; set; } - } + /// + /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). + /// + [Newtonsoft.Json.JsonProperty("developerFeeRecipient", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string DeveloperFeeRecipient { get; set; } - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response12 - { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("developerFeeBps", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double DeveloperFeeBps { get; set; } + + [Newtonsoft.Json.JsonProperty("transactions", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - public Result9 Result { get; set; } = new Result9(); + public System.Collections.Generic.ICollection Transactions { get; set; } = new System.Collections.ObjectModel.Collection(); - private System.Collections.Generic.IDictionary _additionalProperties; + [Newtonsoft.Json.JsonProperty("status", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public DataStatus Status { get; set; } - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + [Newtonsoft.Json.JsonProperty("type", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public DataType Type { get; set; } - } + [Newtonsoft.Json.JsonProperty("originAmount", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + [System.ComponentModel.DataAnnotations.RegularExpression(@"^\d+$")] + public string OriginAmount { get; set; } - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response13 - { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Result10 Result { get; set; } = new Result10(); + [Newtonsoft.Json.JsonProperty("destinationAmount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [System.ComponentModel.DataAnnotations.RegularExpression(@"^\d+$")] + public string DestinationAmount { get; set; } - private System.Collections.Generic.IDictionary _additionalProperties; + [Newtonsoft.Json.JsonProperty("paymentLinkId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string PaymentLinkId { get; set; } - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + [Newtonsoft.Json.JsonProperty("purchaseData", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public object PurchaseData { get; set; } - } + [Newtonsoft.Json.JsonProperty("originToken", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public OriginToken OriginToken { get; set; } - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response14 - { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("destinationToken", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - public Result11 Result { get; set; } = new Result11(); + public DestinationToken DestinationToken { get; set; } = new DestinationToken(); + + [Newtonsoft.Json.JsonProperty("createdAt", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string CreatedAt { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -5709,11 +9432,13 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response15 + public partial class Meta { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Result12 Result { get; set; } = new Result12(); + /// + /// Total number of payments + /// + [Newtonsoft.Json.JsonProperty("totalCount", Required = Newtonsoft.Json.Required.Always)] + public double TotalCount { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -5727,107 +9452,125 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response16 + public enum Response34InvalidReason { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Result13 Result { get; set; } = new Result13(); - private System.Collections.Generic.IDictionary _additionalProperties; + [System.Runtime.Serialization.EnumMember(Value = @"insufficient_funds")] + Insufficient_funds = 0, - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_evm_payload_authorization_valid_after")] + Invalid_exact_evm_payload_authorization_valid_after = 1, - } + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_evm_payload_authorization_valid_before")] + Invalid_exact_evm_payload_authorization_valid_before = 2, - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response17 - { - /// - /// Array of results corresponding to each contract read call. Results are returned in the same order as the input calls. - /// - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Result { get; set; } = new System.Collections.Generic.List(); + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_evm_payload_authorization_value")] + Invalid_exact_evm_payload_authorization_value = 3, - private System.Collections.Generic.IDictionary _additionalProperties; + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_evm_payload_signature")] + Invalid_exact_evm_payload_signature = 4, - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_evm_payload_recipient_mismatch")] + Invalid_exact_evm_payload_recipient_mismatch = 5, - } + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction")] + Invalid_exact_svm_payload_transaction = 6, - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response18 - { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Result15 Result { get; set; } = new Result15(); + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_amount_mismatch")] + Invalid_exact_svm_payload_transaction_amount_mismatch = 7, - private System.Collections.Generic.IDictionary _additionalProperties; + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_create_ata_instruction")] + Invalid_exact_svm_payload_transaction_create_ata_instruction = 8, - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_payee")] + Invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_payee = 9, - } + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_asset")] + Invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_asset = 10, - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response19 - { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Result16 Result { get; set; } = new Result16(); + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_instructions")] + Invalid_exact_svm_payload_transaction_instructions = 11, - private System.Collections.Generic.IDictionary _additionalProperties; + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_instructions_length")] + Invalid_exact_svm_payload_transaction_instructions_length = 12, - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction")] + Invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction = 13, - } + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_instructions_compute_price_instruction")] + Invalid_exact_svm_payload_transaction_instructions_compute_price_instruction = 14, - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response20 - { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Result17 Result { get; set; } = new Result17(); + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_instructions_compute_price_instruction_too_high")] + Invalid_exact_svm_payload_transaction_instructions_compute_price_instruction_too_high = 15, - private System.Collections.Generic.IDictionary _additionalProperties; + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked")] + Invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked = 16, - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked")] + Invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked = 17, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_not_a_transfer_instruction")] + Invalid_exact_svm_payload_transaction_not_a_transfer_instruction = 18, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_cannot_derive_receiver_ata")] + Invalid_exact_svm_payload_transaction_cannot_derive_receiver_ata = 19, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_receiver_ata_not_found")] + Invalid_exact_svm_payload_transaction_receiver_ata_not_found = 20, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_sender_ata_not_found")] + Invalid_exact_svm_payload_transaction_sender_ata_not_found = 21, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_simulation_failed")] + Invalid_exact_svm_payload_transaction_simulation_failed = 22, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_transfer_to_incorrect_ata")] + Invalid_exact_svm_payload_transaction_transfer_to_incorrect_ata = 23, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_network")] + Invalid_network = 24, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_payload")] + Invalid_payload = 25, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_payment_requirements")] + Invalid_payment_requirements = 26, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_scheme")] + Invalid_scheme = 27, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_payment")] + Invalid_payment = 28, + + [System.Runtime.Serialization.EnumMember(Value = @"payment_expired")] + Payment_expired = 29, + + [System.Runtime.Serialization.EnumMember(Value = @"unsupported_scheme")] + Unsupported_scheme = 30, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_x402_version")] + Invalid_x402_version = 31, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_transaction_state")] + Invalid_transaction_state = 32, + + [System.Runtime.Serialization.EnumMember(Value = @"settle_exact_svm_block_height_exceeded")] + Settle_exact_svm_block_height_exceeded = 33, + + [System.Runtime.Serialization.EnumMember(Value = @"settle_exact_svm_transaction_confirmation_timed_out")] + Settle_exact_svm_transaction_confirmation_timed_out = 34, + + [System.Runtime.Serialization.EnumMember(Value = @"unexpected_settle_error")] + Unexpected_settle_error = 35, + + [System.Runtime.Serialization.EnumMember(Value = @"unexpected_verify_error")] + Unexpected_verify_error = 36, } - /// - /// Contract metadata from the thirdweb contract metadata service. - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response21 + public partial class Payer { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Result18 Result { get; set; } = new Result18(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -5840,36 +9583,126 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Contract ABI signatures in human-readable format. These signatures can be used directly with contract interaction methods. - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response22 + public enum Response35ErrorReason { - /// - /// Array of human-readable ABI signatures including functions and events. Each signature is formatted as a string that can be used directly in contract read/write operations or event filtering. - /// - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Result { get; set; } = new System.Collections.Generic.List(); - private System.Collections.Generic.IDictionary _additionalProperties; + [System.Runtime.Serialization.EnumMember(Value = @"insufficient_funds")] + Insufficient_funds = 0, - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_evm_payload_authorization_valid_after")] + Invalid_exact_evm_payload_authorization_valid_after = 1, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_evm_payload_authorization_valid_before")] + Invalid_exact_evm_payload_authorization_valid_before = 2, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_evm_payload_authorization_value")] + Invalid_exact_evm_payload_authorization_value = 3, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_evm_payload_signature")] + Invalid_exact_evm_payload_signature = 4, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_evm_payload_recipient_mismatch")] + Invalid_exact_evm_payload_recipient_mismatch = 5, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction")] + Invalid_exact_svm_payload_transaction = 6, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_amount_mismatch")] + Invalid_exact_svm_payload_transaction_amount_mismatch = 7, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_create_ata_instruction")] + Invalid_exact_svm_payload_transaction_create_ata_instruction = 8, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_payee")] + Invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_payee = 9, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_asset")] + Invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_asset = 10, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_instructions")] + Invalid_exact_svm_payload_transaction_instructions = 11, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_instructions_length")] + Invalid_exact_svm_payload_transaction_instructions_length = 12, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction")] + Invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction = 13, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_instructions_compute_price_instruction")] + Invalid_exact_svm_payload_transaction_instructions_compute_price_instruction = 14, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_instructions_compute_price_instruction_too_high")] + Invalid_exact_svm_payload_transaction_instructions_compute_price_instruction_too_high = 15, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked")] + Invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked = 16, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked")] + Invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked = 17, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_not_a_transfer_instruction")] + Invalid_exact_svm_payload_transaction_not_a_transfer_instruction = 18, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_cannot_derive_receiver_ata")] + Invalid_exact_svm_payload_transaction_cannot_derive_receiver_ata = 19, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_receiver_ata_not_found")] + Invalid_exact_svm_payload_transaction_receiver_ata_not_found = 20, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_sender_ata_not_found")] + Invalid_exact_svm_payload_transaction_sender_ata_not_found = 21, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_simulation_failed")] + Invalid_exact_svm_payload_transaction_simulation_failed = 22, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_exact_svm_payload_transaction_transfer_to_incorrect_ata")] + Invalid_exact_svm_payload_transaction_transfer_to_incorrect_ata = 23, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_network")] + Invalid_network = 24, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_payload")] + Invalid_payload = 25, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_payment_requirements")] + Invalid_payment_requirements = 26, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_scheme")] + Invalid_scheme = 27, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_payment")] + Invalid_payment = 28, + + [System.Runtime.Serialization.EnumMember(Value = @"payment_expired")] + Payment_expired = 29, + + [System.Runtime.Serialization.EnumMember(Value = @"unsupported_scheme")] + Unsupported_scheme = 30, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_x402_version")] + Invalid_x402_version = 31, + + [System.Runtime.Serialization.EnumMember(Value = @"invalid_transaction_state")] + Invalid_transaction_state = 32, + + [System.Runtime.Serialization.EnumMember(Value = @"settle_exact_svm_block_height_exceeded")] + Settle_exact_svm_block_height_exceeded = 33, + + [System.Runtime.Serialization.EnumMember(Value = @"settle_exact_svm_transaction_confirmation_timed_out")] + Settle_exact_svm_transaction_confirmation_timed_out = 34, + + [System.Runtime.Serialization.EnumMember(Value = @"unexpected_settle_error")] + Unexpected_settle_error = 35, + + [System.Runtime.Serialization.EnumMember(Value = @"unexpected_verify_error")] + Unexpected_verify_error = 36, } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response23 + public partial class Payer2 { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Result19 Result { get; set; } = new Result19(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -5883,29 +9716,54 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response24 + public enum Response35Network { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Result20 Result { get; set; } = new Result20(); - private System.Collections.Generic.IDictionary _additionalProperties; + [System.Runtime.Serialization.EnumMember(Value = @"base-sepolia")] + BaseSepolia = 0, - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + [System.Runtime.Serialization.EnumMember(Value = @"base")] + Base = 1, + + [System.Runtime.Serialization.EnumMember(Value = @"avalanche-fuji")] + AvalancheFuji = 2, + + [System.Runtime.Serialization.EnumMember(Value = @"avalanche")] + Avalanche = 3, + + [System.Runtime.Serialization.EnumMember(Value = @"iotex")] + Iotex = 4, + + [System.Runtime.Serialization.EnumMember(Value = @"solana-devnet")] + SolanaDevnet = 5, + + [System.Runtime.Serialization.EnumMember(Value = @"solana")] + Solana = 6, + + [System.Runtime.Serialization.EnumMember(Value = @"sei")] + Sei = 7, + + [System.Runtime.Serialization.EnumMember(Value = @"sei-testnet")] + SeiTestnet = 8, } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response25 + public partial class Kinds { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Result21 Result { get; set; } = new Result21(); + [Newtonsoft.Json.JsonProperty("x402Version", Required = Newtonsoft.Json.Required.Always)] + public double X402Version { get; set; } + + [Newtonsoft.Json.JsonProperty("scheme", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public KindsScheme Scheme { get; set; } + + [Newtonsoft.Json.JsonProperty("network", Required = Newtonsoft.Json.Required.Always)] + public Network5 Network { get; set; } + + [Newtonsoft.Json.JsonProperty("extra", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public Extra Extra { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -5918,15 +9776,32 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Successful token swap response containing executed transaction IDs - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response26 + public partial class Pagination { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Result22 Result { get; set; } = new Result22(); + /// + /// Whether there are more items available + /// + [Newtonsoft.Json.JsonProperty("hasMore", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public bool HasMore { get; set; } + + /// + /// Number of items per page + /// + [Newtonsoft.Json.JsonProperty("limit", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? Limit { get; set; } = 20D; + + /// + /// Current page number + /// + [Newtonsoft.Json.JsonProperty("page", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? Page { get; set; } = 1D; + + /// + /// Total number of items available + /// + [Newtonsoft.Json.JsonProperty("totalCount", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? TotalCount { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -5939,15 +9814,39 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Successful payment creation response containing the payment ID and link to purchase the product - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response27 + public partial class Tokens { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + /// + /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } + + /// + /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). + /// + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Address { get; set; } + + [Newtonsoft.Json.JsonProperty("decimals", Required = Newtonsoft.Json.Required.Always)] + public double Decimals { get; set; } + + [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Symbol { get; set; } + + [Newtonsoft.Json.JsonProperty("iconUri", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string IconUri { get; set; } + + /// + /// Token price in different FIAT currencies. + /// + [Newtonsoft.Json.JsonProperty("prices", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - public Result23 Result { get; set; } = new Result23(); + public System.Collections.Generic.IDictionary Prices { get; set; } = new System.Collections.Generic.Dictionary(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -5960,12 +9859,19 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response28 - { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Result27 + { + /// + /// Array of token owners with amounts. + /// + [Newtonsoft.Json.JsonProperty("owners", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Owners { get; set; } = new System.Collections.ObjectModel.Collection(); + + [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - public Result24 Result { get; set; } = new Result24(); + public Pagination11 Pagination { get; set; } = new Pagination11(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -5979,21 +9885,34 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response29 + public partial class Result28 { /// - /// The chain the token was deployed on. + /// The chain ID of the chain /// [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] - public int ChainId { get; set; } + public double ChainId { get; set; } /// - /// The address the token was deployed at + /// The name of the chain /// - [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Address { get; set; } + public string Name { get; set; } + + /// + /// The URL of the chain's icon + /// + [Newtonsoft.Json.JsonProperty("icon", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Icon { get; set; } + + /// + /// Information about the native currency of the chain + /// + [Newtonsoft.Json.JsonProperty("nativeCurrency", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public NativeCurrency NativeCurrency { get; set; } = new NativeCurrency(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -6007,15 +9926,14 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response30 + public partial class Result29 { - [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Pagination Pagination { get; set; } = new Pagination(); - - [Newtonsoft.Json.JsonProperty("tokens", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Tokens { get; set; } = new System.Collections.Generic.List(); + /// + /// Payment transaction ID that was executed + /// + [Newtonsoft.Json.JsonProperty("transactionId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string TransactionId { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -6029,11 +9947,28 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response31 + public partial class Result30 { - [Newtonsoft.Json.JsonProperty("result", Required = Newtonsoft.Json.Required.Always)] + /// + /// Link to purchase the product + /// + [Newtonsoft.Json.JsonProperty("link", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Link { get; set; } + + /// + /// Payment ID + /// + [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Id { get; set; } + + /// + /// Bridge quote for completing the payment + /// + [Newtonsoft.Json.JsonProperty("quote", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - public Result25 Result { get; set; } = new Result25(); + public Quote4 Quote { get; set; } = new Quote4(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -6047,22 +9982,11 @@ public System.Collections.Generic.IDictionary AdditionalProperti } /// - /// Chat response + /// Sign a transaction /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Response32 + public partial class Actions { - /// - /// The AI assistant's response - /// - [Newtonsoft.Json.JsonProperty("message", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Message { get; set; } - - [Newtonsoft.Json.JsonProperty("actions", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Actions { get; set; } = new System.Collections.Generic.List(); - [Newtonsoft.Json.JsonProperty("session_id", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] public string Session_id { get; set; } @@ -6071,6 +9995,18 @@ public partial class Response32 [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] public string Request_id { get; set; } + [Newtonsoft.Json.JsonProperty("source", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Source { get; set; } = "model"; + + [Newtonsoft.Json.JsonProperty("type", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public ActionsType Type { get; set; } + + [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Data2 Data { get; set; } = new Data2(); + private System.Collections.Generic.IDictionary _additionalProperties; [Newtonsoft.Json.JsonExtensionData] @@ -6083,88 +10019,17 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public enum BodyMethod - { - - [System.Runtime.Serialization.EnumMember(Value = @"sms")] - Sms = 0, - - } - - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public enum Body2Method - { - - [System.Runtime.Serialization.EnumMember(Value = @"sms")] - Sms = 0, - - } - - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public enum Body3Type + public enum PaymentPayloadScheme { - [System.Runtime.Serialization.EnumMember(Value = @"google")] - Google = 0, - - [System.Runtime.Serialization.EnumMember(Value = @"apple")] - Apple = 1, - - [System.Runtime.Serialization.EnumMember(Value = @"facebook")] - Facebook = 2, - - [System.Runtime.Serialization.EnumMember(Value = @"discord")] - Discord = 3, - - [System.Runtime.Serialization.EnumMember(Value = @"email")] - Email = 4, - - [System.Runtime.Serialization.EnumMember(Value = @"phone")] - Phone = 5, - - [System.Runtime.Serialization.EnumMember(Value = @"custom_auth_endpoint")] - Custom_auth_endpoint = 6, - - [System.Runtime.Serialization.EnumMember(Value = @"custom_jwt")] - Custom_jwt = 7, - - [System.Runtime.Serialization.EnumMember(Value = @"siwe")] - Siwe = 8, + [System.Runtime.Serialization.EnumMember(Value = @"exact")] + Exact = 0, } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Domain + public partial class Network { - /// - /// Chain ID as string for domain separation - /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string ChainId { get; set; } - - /// - /// The domain name (e.g., token name) - /// - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Name { get; set; } - - /// - /// Optional salt for additional entropy - /// - [Newtonsoft.Json.JsonProperty("salt", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Salt { get; set; } - - /// - /// The contract address that will verify this signature - /// - [Newtonsoft.Json.JsonProperty("verifyingContract", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string VerifyingContract { get; set; } - - /// - /// Domain version for signature compatibility - /// - [Newtonsoft.Json.JsonProperty("version", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Version { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -6178,21 +10043,8 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Anonymous + public partial class Payload { - /// - /// The field name - /// - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Name { get; set; } - - /// - /// The Solidity type (e.g., 'address', 'uint256') - /// - [Newtonsoft.Json.JsonProperty("type", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Type { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -6206,21 +10058,17 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Recipients + public enum PaymentRequirementsScheme { - /// - /// The recipient wallet address or ENS name - /// - [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Address { get; set; } - /// - /// The amount to send. For native tokens and ERC20: amount in wei/smallest unit. For ERC721: should be '1'. For ERC1155: the number of tokens to transfer. - /// - [Newtonsoft.Json.JsonProperty("quantity", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Quantity { get; set; } + [System.Runtime.Serialization.EnumMember(Value = @"exact")] + Exact = 0, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Network2 + { private System.Collections.Generic.IDictionary _additionalProperties; @@ -6234,34 +10082,8 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Calls + public partial class PayTo { - /// - /// The smart contract address or ENS name. - /// - [Newtonsoft.Json.JsonProperty("contractAddress", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string ContractAddress { get; set; } - - /// - /// The contract function signature to call (e.g., 'function approve(address spender, uint256 amount)' or `function balanceOf(address)`). Must start with 'function' followed by the function name and parameters as defined in the contract ABI. - /// - [Newtonsoft.Json.JsonProperty("method", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - [System.ComponentModel.DataAnnotations.RegularExpression(@"^function\s+\w+")] - public string Method { get; set; } - - /// - /// Array of parameters to pass to the contract method, in the correct order and format. - /// - [Newtonsoft.Json.JsonProperty("params", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.Generic.List Params { get; set; } - - /// - /// Amount of native token to send with the transaction in wei. Required for payable methods. - /// - [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Value { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -6275,34 +10097,8 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class calls + public partial class Asset { - /// - /// The smart contract address or ENS name. - /// - [Newtonsoft.Json.JsonProperty("contractAddress", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string ContractAddress { get; set; } - - /// - /// The contract function signature to call (e.g., 'function approve(address spender, uint256 amount)' or `function balanceOf(address)`). Must start with 'function' followed by the function name and parameters as defined in the contract ABI. - /// - [Newtonsoft.Json.JsonProperty("method", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - [System.ComponentModel.DataAnnotations.RegularExpression(@"^function\s+\w+")] - public string Method { get; set; } - - /// - /// Array of parameters to pass to the contract method, in the correct order and format. - /// - [Newtonsoft.Json.JsonProperty("params", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.Generic.List Params { get; set; } - - /// - /// Amount of native token to send with the transaction in wei. Required for payable methods. - /// - [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Value { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -6315,31 +10111,18 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// A blockchain transaction with pre-encoded data payload. For contract calls, use /v1/contracts/write. For native token transfers, use /v1/wallets/send. - /// - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Transactions - { - /// - /// Transaction data in hexadecimal format for contract interactions or custom payloads. - /// - [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Data { get; set; } - - /// - /// The target address or ENS name for the transaction. - /// - [Newtonsoft.Json.JsonProperty("to", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string To { get; set; } - - /// - /// Amount of native token to send in wei (smallest unit). Use '0' or omit for non-value transactions. - /// - [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Value { get; set; } + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum PaymentPayload2Scheme + { + + [System.Runtime.Serialization.EnumMember(Value = @"exact")] + Exact = 0, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Network3 + { private System.Collections.Generic.IDictionary _additionalProperties; @@ -6353,45 +10136,32 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public enum Body12Exact + public partial class Payload2 { - [System.Runtime.Serialization.EnumMember(Value = @"input")] - Input = 0, + private System.Collections.Generic.IDictionary _additionalProperties; - [System.Runtime.Serialization.EnumMember(Value = @"output")] - Output = 1, + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class TokenIn + public enum PaymentRequirements2Scheme { - /// - /// The input token address to swap (use 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for native token) - /// - [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Address { get; set; } - /// - /// The blockchain network where the token is located - /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] - public int ChainId { get; set; } + [System.Runtime.Serialization.EnumMember(Value = @"exact")] + Exact = 0, - /// - /// The amount of the input token to swap in wei. - /// - [Newtonsoft.Json.JsonProperty("amount", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Amount { get; set; } + } - /// - /// The maximum amount of the input token to swap in wei. - /// - [Newtonsoft.Json.JsonProperty("maxAmount", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string MaxAmount { get; set; } + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Network4 + { private System.Collections.Generic.IDictionary _additionalProperties; @@ -6405,33 +10175,23 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class TokenOut + public partial class PayTo2 { - /// - /// The output token address to swap (use 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for native token) - /// - [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Address { get; set; } - /// - /// The blockchain network where the token is located - /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] - public int ChainId { get; set; } + private System.Collections.Generic.IDictionary _additionalProperties; - /// - /// The amount of the output token to receive in wei. - /// - [Newtonsoft.Json.JsonProperty("amount", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Amount { get; set; } + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } - /// - /// The minimum amount of the output token to receive in wei. - /// - [Newtonsoft.Json.JsonProperty("minAmount", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string MinAmount { get; set; } + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Asset2 + { private System.Collections.Generic.IDictionary _additionalProperties; @@ -6445,28 +10205,35 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Token + public enum SaleType { - /// - /// The token address to purchase (use 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for native token) - /// - [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Address { get; set; } - /// - /// The blockchain network where the token is located - /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] - public int ChainId { get; set; } + [System.Runtime.Serialization.EnumMember(Value = @"pool")] + Pool = 0, - /// - /// The amount of the token to purchase in wei. - /// - [Newtonsoft.Json.JsonProperty("amount", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Amount { get; set; } + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum MessagesRole + { + + [System.Runtime.Serialization.EnumMember(Value = @"user")] + User = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"assistant")] + Assistant = 1, + + [System.Runtime.Serialization.EnumMember(Value = @"system")] + System = 2, + + [System.Runtime.Serialization.EnumMember(Value = @"tool")] + Tool = 3, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Content + { private System.Collections.Generic.IDictionary _additionalProperties; @@ -6479,16 +10246,12 @@ public System.Collections.Generic.IDictionary AdditionalProperti } + /// + /// Authentication provider details with type-based discrimination + /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Messages + public partial class Profiles { - [Newtonsoft.Json.JsonProperty("role", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] - public MessagesRole Role { get; set; } - - [Newtonsoft.Json.JsonProperty("content", Required = Newtonsoft.Json.Required.Always)] - public Content Content { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -6502,25 +10265,31 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Context + public partial class Pagination2 { /// - /// Optional wallet address that will execute transactions + /// Whether there are more items available /// - [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string From { get; set; } + [Newtonsoft.Json.JsonProperty("hasMore", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public bool HasMore { get; set; } /// - /// Optional chain IDs for context + /// Number of items per page /// - [Newtonsoft.Json.JsonProperty("chain_ids", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.Generic.List Chain_ids { get; set; } + [Newtonsoft.Json.JsonProperty("limit", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? Limit { get; set; } = 20D; /// - /// Optional session ID for conversation continuity. If not provided, a new session will be created + /// Current page number /// - [Newtonsoft.Json.JsonProperty("session_id", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Session_id { get; set; } + [Newtonsoft.Json.JsonProperty("page", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? Page { get; set; } = 1D; + + /// + /// Total number of items available + /// + [Newtonsoft.Json.JsonProperty("totalCount", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? TotalCount { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -6534,22 +10303,12 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public enum ResponseMethod - { - - [System.Runtime.Serialization.EnumMember(Value = @"sms")] - Sms = 0, - - } - - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result + public partial class Wallets { /// /// The EOA (Externally Owned Wallet) address of the wallet. This is the traditional wallet address. /// - [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Address { get; set; } /// @@ -6563,7 +10322,7 @@ public partial class Result /// [Newtonsoft.Json.JsonProperty("profiles", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Profiles { get; set; } = new System.Collections.Generic.List(); + public System.Collections.Generic.ICollection Profiles { get; set; } = new System.Collections.ObjectModel.Collection(); /// /// The smart wallet address with EIP-4337 support. This address enables gasless transactions and advanced wallet features. @@ -6588,22 +10347,50 @@ public System.Collections.Generic.IDictionary AdditionalProperti } + /// + /// Authentication provider details with type-based discrimination + /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result2 + public partial class profiles + { + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Pagination3 { /// - /// Pagination information + /// Whether there are more items available /// - [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Pagination2 Pagination { get; set; } = new Pagination2(); + [Newtonsoft.Json.JsonProperty("hasMore", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public bool HasMore { get; set; } /// - /// Array of user wallets + /// Number of items per page /// - [Newtonsoft.Json.JsonProperty("wallets", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Wallets { get; set; } = new System.Collections.Generic.List(); + [Newtonsoft.Json.JsonProperty("limit", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? Limit { get; set; } = 20D; + + /// + /// Current page number + /// + [Newtonsoft.Json.JsonProperty("page", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? Page { get; set; } = 1D; + + /// + /// Total number of items available + /// + [Newtonsoft.Json.JsonProperty("totalCount", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? TotalCount { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -6617,13 +10404,12 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result3 + public partial class wallets { /// /// The EOA (Externally Owned Wallet) address of the wallet. This is the traditional wallet address. /// - [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Address { get; set; } /// @@ -6637,7 +10423,7 @@ public partial class Result3 /// [Newtonsoft.Json.JsonProperty("profiles", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Profiles { get; set; } = new System.Collections.Generic.List(); + public System.Collections.Generic.ICollection Profiles { get; set; } = new System.Collections.ObjectModel.Collection(); /// /// The smart wallet address with EIP-4337 support. This address enables gasless transactions and advanced wallet features. @@ -6662,22 +10448,50 @@ public System.Collections.Generic.IDictionary AdditionalProperti } + /// + /// Authentication provider details with type-based discrimination + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Profiles2 + { + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result4 + public partial class Pagination4 { /// - /// Pagination information + /// Whether there are more items available + /// + [Newtonsoft.Json.JsonProperty("hasMore", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public bool HasMore { get; set; } + + /// + /// Number of items per page + /// + [Newtonsoft.Json.JsonProperty("limit", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? Limit { get; set; } = 20D; + + /// + /// Current page number /// - [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Pagination3 Pagination { get; set; } = new Pagination3(); + [Newtonsoft.Json.JsonProperty("page", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? Page { get; set; } = 1D; /// - /// Array of server wallets + /// Total number of items available /// - [Newtonsoft.Json.JsonProperty("wallets", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Wallets { get; set; } = new System.Collections.Generic.List(); + [Newtonsoft.Json.JsonProperty("totalCount", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? TotalCount { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -6691,96 +10505,150 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result5 + public partial class transactions { /// - /// The EOA (Externally Owned Wallet) address of the wallet. This is the traditional wallet address. + /// The hash of the block containing this transaction. /// - [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("blockHash", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Address { get; set; } + public string BlockHash { get; set; } /// - /// The date and time the wallet was created + /// The block number containing this transaction. /// - [Newtonsoft.Json.JsonProperty("createdAt", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string CreatedAt { get; set; } + [Newtonsoft.Json.JsonProperty("blockNumber", Required = Newtonsoft.Json.Required.Always)] + public double BlockNumber { get; set; } /// - /// The profiles linked to the wallet, can be email, phone, google etc, or backend for developer created wallets + /// The timestamp of the block (Unix timestamp). /// - [Newtonsoft.Json.JsonProperty("profiles", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Profiles { get; set; } = new System.Collections.Generic.List(); + [Newtonsoft.Json.JsonProperty("blockTimestamp", Required = Newtonsoft.Json.Required.Always)] + public double BlockTimestamp { get; set; } /// - /// The smart wallet address with EIP-4337 support. This address enables gasless transactions and advanced wallet features. + /// The chain ID where the transaction occurred. /// - [Newtonsoft.Json.JsonProperty("smartWalletAddress", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string SmartWalletAddress { get; set; } + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string ChainId { get; set; } /// - /// The wallet's public key in hexadecimal format. Useful for peer-to-peer encryption and cryptographic operations. + /// Contract address created if this was a contract creation transaction. /// - [Newtonsoft.Json.JsonProperty("publicKey", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string PublicKey { get; set; } + [Newtonsoft.Json.JsonProperty("contractAddress", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string ContractAddress { get; set; } - private System.Collections.Generic.IDictionary _additionalProperties; + /// + /// Total gas used by all transactions in this block up to and including this one. + /// + [Newtonsoft.Json.JsonProperty("cumulativeGasUsed", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double CumulativeGasUsed { get; set; } - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + /// + /// The transaction input data. + /// + [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Data { get; set; } - } + /// + /// Decoded transaction data (included when ABI is available). + /// + [Newtonsoft.Json.JsonProperty("decoded", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public Decoded Decoded { get; set; } - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class result - { /// - /// The blockchain network ID + /// The effective gas price paid (in wei as string). /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] - public double ChainId { get; set; } + [Newtonsoft.Json.JsonProperty("effectiveGasPrice", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string EffectiveGasPrice { get; set; } /// - /// Number of decimal places for the token + /// The address that initiated the transaction. /// - [Newtonsoft.Json.JsonProperty("decimals", Required = Newtonsoft.Json.Required.Always)] - public double Decimals { get; set; } + [Newtonsoft.Json.JsonProperty("fromAddress", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string FromAddress { get; set; } /// - /// Human-readable balance formatted with appropriate decimal places + /// The function selector (first 4 bytes of the transaction data). /// - [Newtonsoft.Json.JsonProperty("displayValue", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("functionSelector", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string DisplayValue { get; set; } + public string FunctionSelector { get; set; } /// - /// The token name (e.g., 'Ether', 'USD Coin') + /// The gas limit for the transaction. /// - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("gas", Required = Newtonsoft.Json.Required.Always)] + public double Gas { get; set; } + + /// + /// The gas price used for the transaction (in wei as string). + /// + [Newtonsoft.Json.JsonProperty("gasPrice", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Name { get; set; } + public string GasPrice { get; set; } /// - /// The token symbol (e.g., 'ETH', 'USDC') + /// The amount of gas used by the transaction. /// - [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("gasUsed", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double GasUsed { get; set; } + + /// + /// The transaction hash. + /// + [Newtonsoft.Json.JsonProperty("hash", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Symbol { get; set; } + public string Hash { get; set; } /// - /// The token contract address. Returns zero address (0x0...0) for native tokens. + /// Maximum fee per gas (EIP-1559). /// - [Newtonsoft.Json.JsonProperty("tokenAddress", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("maxFeePerGas", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string MaxFeePerGas { get; set; } + + /// + /// Maximum priority fee per gas (EIP-1559). + /// + [Newtonsoft.Json.JsonProperty("maxPriorityFeePerGas", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string MaxPriorityFeePerGas { get; set; } + + /// + /// The transaction nonce. + /// + [Newtonsoft.Json.JsonProperty("nonce", Required = Newtonsoft.Json.Required.Always)] + public double Nonce { get; set; } + + /// + /// The transaction status (1 for success, 0 for failure). + /// + [Newtonsoft.Json.JsonProperty("status", Required = Newtonsoft.Json.Required.Always)] + public double Status { get; set; } + + /// + /// The address that received the transaction. + /// + [Newtonsoft.Json.JsonProperty("toAddress", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string TokenAddress { get; set; } + public string ToAddress { get; set; } /// - /// Raw balance value as string in smallest unit (wei for ETH, etc.) + /// The index of the transaction within the block. + /// + [Newtonsoft.Json.JsonProperty("transactionIndex", Required = Newtonsoft.Json.Required.Always)] + public double TransactionIndex { get; set; } + + /// + /// The transaction type (0=legacy, 1=EIP-2930, 2=EIP-1559). + /// + [Newtonsoft.Json.JsonProperty("transactionType", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double TransactionType { get; set; } + + /// + /// The value transferred in the transaction (in wei as string). /// [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] @@ -6798,18 +10666,31 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result6 + public partial class Pagination5 { - [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Pagination4 Pagination { get; set; } = new Pagination4(); + /// + /// Whether there are more items available + /// + [Newtonsoft.Json.JsonProperty("hasMore", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public bool HasMore { get; set; } /// - /// Array of wallet transactions. + /// Number of items per page /// - [Newtonsoft.Json.JsonProperty("transactions", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Transactions { get; set; } = new System.Collections.Generic.List(); + [Newtonsoft.Json.JsonProperty("limit", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? Limit { get; set; } = 20D; + + /// + /// Current page number + /// + [Newtonsoft.Json.JsonProperty("page", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? Page { get; set; } = 1D; + + /// + /// Total number of items available + /// + [Newtonsoft.Json.JsonProperty("totalCount", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? TotalCount { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -6823,64 +10704,63 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result7 + public partial class tokens { - [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Pagination5 Pagination { get; set; } = new Pagination5(); - /// - /// Array of wallet tokens. + /// The token balance as a string /// - [Newtonsoft.Json.JsonProperty("tokens", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Tokens { get; set; } = new System.Collections.Generic.List(); - - private System.Collections.Generic.IDictionary _additionalProperties; + [Newtonsoft.Json.JsonProperty("balance", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Balance { get; set; } - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + /// + /// The chain ID of the token + /// + [Newtonsoft.Json.JsonProperty("chain_id", Required = Newtonsoft.Json.Required.Always)] + public double Chain_id { get; set; } - } + /// + /// The number of decimal places + /// + [Newtonsoft.Json.JsonProperty("decimals", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double Decimals { get; set; } - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result8 - { /// - /// Array of wallet NFTs. + /// The token name /// - [Newtonsoft.Json.JsonProperty("nfts", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Nfts { get; set; } = new System.Collections.Generic.List(); + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Name { get; set; } - [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Pagination6 Pagination { get; set; } = new Pagination6(); + /// + /// The token icon URI + /// + [Newtonsoft.Json.JsonProperty("icon_uri", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Icon_uri { get; set; } - private System.Collections.Generic.IDictionary _additionalProperties; + /// + /// Price data + /// + [Newtonsoft.Json.JsonProperty("prices", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.IDictionary Prices { get; set; } - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + /// + /// Price data for the token + /// + [Newtonsoft.Json.JsonProperty("price_data", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public Price_data Price_data { get; set; } - } + /// + /// The token symbol + /// + [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Symbol { get; set; } - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result9 - { /// - /// The cryptographic signature in hexadecimal format. This can be used for verification and authentication purposes. + /// The contract address of the token /// - [Newtonsoft.Json.JsonProperty("signature", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("token_address", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Signature { get; set; } + public string Token_address { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -6894,35 +10774,75 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result10 + public partial class Nfts { /// - /// The cryptographic signature in hexadecimal format. This can be used for verification and authentication purposes. + /// The animation URL of the NFT /// - [Newtonsoft.Json.JsonProperty("signature", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Signature { get; set; } + [Newtonsoft.Json.JsonProperty("animation_url", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Animation_url { get; set; } - private System.Collections.Generic.IDictionary _additionalProperties; + /// + /// The attributes/traits of the NFT + /// + [Newtonsoft.Json.JsonProperty("attributes", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.ICollection Attributes { get; set; } - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + /// + /// The chain ID of the NFT + /// + [Newtonsoft.Json.JsonProperty("chain_id", Required = Newtonsoft.Json.Required.Always)] + public double Chain_id { get; set; } - } + /// + /// Collection information + /// + [Newtonsoft.Json.JsonProperty("collection", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public Collection Collection { get; set; } - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result11 - { /// - /// Array of transaction IDs for the submitted transfers. One ID per recipient. + /// The description of the NFT /// - [Newtonsoft.Json.JsonProperty("transactionIds", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List TransactionIds { get; set; } = new System.Collections.Generic.List(); + [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Description { get; set; } + + /// + /// The external URL of the NFT + /// + [Newtonsoft.Json.JsonProperty("external_url", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string External_url { get; set; } + + /// + /// The image URL of the NFT + /// + [Newtonsoft.Json.JsonProperty("image_url", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Image_url { get; set; } + + /// + /// Additional metadata for the NFT + /// + [Newtonsoft.Json.JsonProperty("metadata", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.IDictionary Metadata { get; set; } + + /// + /// The name of the NFT + /// + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Name { get; set; } + + /// + /// The contract address of the NFT collection + /// + [Newtonsoft.Json.JsonProperty("token_address", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Token_address { get; set; } + + /// + /// The token ID of the NFT + /// + [Newtonsoft.Json.JsonProperty("token_id", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Token_id { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -6936,18 +10856,31 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result12 + public partial class Pagination6 { /// - /// Array of contracts imported by the client. + /// Whether there are more items available /// - [Newtonsoft.Json.JsonProperty("contracts", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Contracts { get; set; } = new System.Collections.Generic.List(); + [Newtonsoft.Json.JsonProperty("hasMore", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public bool HasMore { get; set; } - [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Pagination7 Pagination { get; set; } = new Pagination7(); + /// + /// Number of items per page + /// + [Newtonsoft.Json.JsonProperty("limit", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? Limit { get; set; } = 20D; + + /// + /// Current page number + /// + [Newtonsoft.Json.JsonProperty("page", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? Page { get; set; } = 1D; + + /// + /// Total number of items available + /// + [Newtonsoft.Json.JsonProperty("totalCount", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? TotalCount { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -6960,59 +10893,62 @@ public System.Collections.Generic.IDictionary AdditionalProperti } + /// + /// Contract details enriched with additional project information from the API server. + /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result13 + public partial class Contracts { /// - /// The deployed contract address. + /// The contract address. /// [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] public string Address { get; set; } /// - /// The chain ID where the contract was deployed. + /// The chain ID where the contract is deployed. /// [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] - public double ChainId { get; set; } + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string ChainId { get; set; } /// - /// The unique identifier for the transaction that deployed the contract. Will not be returned if the contract was already deployed at the predicted address. + /// The date when the contract was deployed. /// - [Newtonsoft.Json.JsonProperty("transactionId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string TransactionId { get; set; } - - private System.Collections.Generic.IDictionary _additionalProperties; + [Newtonsoft.Json.JsonProperty("deployedAt", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string DeployedAt { get; set; } - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + /// + /// The contract ID. + /// + [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Id { get; set; } - } + /// + /// The date when the contract was imported to the dashboard. + /// + [Newtonsoft.Json.JsonProperty("importedAt", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string ImportedAt { get; set; } - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result14 - { /// - /// The result of the contract read operation. The type and format depend on the method's return value as defined in the contract ABI. + /// The contract name, if available. /// - [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public object Data { get; set; } + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Name { get; set; } /// - /// Error message if the contract read operation failed. + /// The contract symbol, if available. /// - [Newtonsoft.Json.JsonProperty("error", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Error { get; set; } + [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Symbol { get; set; } /// - /// Indicates whether the contract read operation was successful. + /// The contract type (e.g., ERC20, ERC721, etc.). /// - [Newtonsoft.Json.JsonProperty("success", Required = Newtonsoft.Json.Required.Always)] - public bool Success { get; set; } + [Newtonsoft.Json.JsonProperty("type", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Type { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -7026,14 +10962,31 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result15 + public partial class Pagination7 { /// - /// Array of unique identifiers for the submitted transactions. Use these to track transaction status. + /// Whether there are more items available /// - [Newtonsoft.Json.JsonProperty("transactionIds", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List TransactionIds { get; set; } = new System.Collections.Generic.List(); + [Newtonsoft.Json.JsonProperty("hasMore", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public bool HasMore { get; set; } + + /// + /// Number of items per page + /// + [Newtonsoft.Json.JsonProperty("limit", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? Limit { get; set; } = 20D; + + /// + /// Current page number + /// + [Newtonsoft.Json.JsonProperty("page", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? Page { get; set; } = 1D; + + /// + /// Total number of items available + /// + [Newtonsoft.Json.JsonProperty("totalCount", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? TotalCount { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -7047,43 +11000,53 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result16 + public partial class Quote { /// - /// Array of contract transactions. + /// Block number when quote was generated /// - [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Data { get; set; } = new System.Collections.Generic.List(); + [Newtonsoft.Json.JsonProperty("blockNumber", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string BlockNumber { get; set; } - [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Pagination8 Pagination { get; set; } = new Pagination8(); + /// + /// Destination amount in wei + /// + [Newtonsoft.Json.JsonProperty("destinationAmount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string DestinationAmount { get; set; } - private System.Collections.Generic.IDictionary _additionalProperties; + /// + /// Estimated execution time in milliseconds + /// + [Newtonsoft.Json.JsonProperty("estimatedExecutionTimeMs", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double EstimatedExecutionTimeMs { get; set; } - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + /// + /// Quote intent details + /// + [Newtonsoft.Json.JsonProperty("intent", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Intent Intent { get; set; } = new Intent(); - } + /// + /// Origin amount in wei + /// + [Newtonsoft.Json.JsonProperty("originAmount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string OriginAmount { get; set; } - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result17 - { /// - /// Array of contract events. + /// Array of steps to complete the bridge operation /// - [Newtonsoft.Json.JsonProperty("events", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("steps", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Events { get; set; } = new System.Collections.Generic.List(); + public System.Collections.Generic.ICollection Steps { get; set; } = new System.Collections.ObjectModel.Collection(); - [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Pagination9 Pagination { get; set; } = new Pagination9(); + /// + /// Quote timestamp + /// + [Newtonsoft.Json.JsonProperty("timestamp", Required = Newtonsoft.Json.Required.Always)] + public double Timestamp { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -7097,152 +11060,154 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result18 + public partial class data { /// - /// Compiler information including version. + /// The hash of the block containing this transaction. /// - [Newtonsoft.Json.JsonProperty("compiler", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public Compiler Compiler { get; set; } + [Newtonsoft.Json.JsonProperty("blockHash", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string BlockHash { get; set; } /// - /// Programming language of the contract (e.g., 'Solidity'). + /// The block number containing this transaction. /// - [Newtonsoft.Json.JsonProperty("language", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Language { get; set; } + [Newtonsoft.Json.JsonProperty("blockNumber", Required = Newtonsoft.Json.Required.Always)] + public double BlockNumber { get; set; } + + /// + /// The timestamp of the block (Unix timestamp). + /// + [Newtonsoft.Json.JsonProperty("blockTimestamp", Required = Newtonsoft.Json.Required.Always)] + public double BlockTimestamp { get; set; } + + /// + /// The chain ID where the transaction occurred. + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string ChainId { get; set; } /// - /// Compilation output including ABI and documentation. + /// Contract address created if this was a contract creation transaction. /// - [Newtonsoft.Json.JsonProperty("output", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public Output Output { get; set; } + [Newtonsoft.Json.JsonProperty("contractAddress", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string ContractAddress { get; set; } /// - /// Compilation settings including optimization and target configuration. + /// Total gas used by all transactions in this block up to and including this one. /// - [Newtonsoft.Json.JsonProperty("settings", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public Settings Settings { get; set; } + [Newtonsoft.Json.JsonProperty("cumulativeGasUsed", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double CumulativeGasUsed { get; set; } /// - /// Metadata format version. + /// The transaction input data. /// - [Newtonsoft.Json.JsonProperty("version", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double Version { get; set; } - - private System.Collections.Generic.IDictionary _additionalProperties; - - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } - - } + [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Data { get; set; } - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result19 - { /// - /// Index within transaction batch + /// Decoded transaction data (included when ABI is available). /// - [Newtonsoft.Json.JsonProperty("batchIndex", Required = Newtonsoft.Json.Required.Always)] - public int BatchIndex { get; set; } + [Newtonsoft.Json.JsonProperty("decoded", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public Decoded2 Decoded { get; set; } /// - /// ISO timestamp when transaction was cancelled, if applicable + /// The effective gas price paid (in wei as string). /// - [Newtonsoft.Json.JsonProperty("cancelledAt", Required = Newtonsoft.Json.Required.AllowNull)] - public string CancelledAt { get; set; } + [Newtonsoft.Json.JsonProperty("effectiveGasPrice", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string EffectiveGasPrice { get; set; } /// - /// Blockchain network identifier as string + /// The address that initiated the transaction. /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("fromAddress", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string ChainId { get; set; } + public string FromAddress { get; set; } /// - /// Client identifier that initiated the transaction + /// The function selector (first 4 bytes of the transaction data). /// - [Newtonsoft.Json.JsonProperty("clientId", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("functionSelector", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string ClientId { get; set; } + public string FunctionSelector { get; set; } /// - /// ISO timestamp when transaction was confirmed on-chain + /// The gas limit for the transaction. /// - [Newtonsoft.Json.JsonProperty("confirmedAt", Required = Newtonsoft.Json.Required.AllowNull)] - public string ConfirmedAt { get; set; } + [Newtonsoft.Json.JsonProperty("gas", Required = Newtonsoft.Json.Required.Always)] + public double Gas { get; set; } /// - /// Block number where transaction was confirmed + /// The gas price used for the transaction (in wei as string). /// - [Newtonsoft.Json.JsonProperty("confirmedAtBlockNumber", Required = Newtonsoft.Json.Required.AllowNull)] - public string ConfirmedAtBlockNumber { get; set; } + [Newtonsoft.Json.JsonProperty("gasPrice", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string GasPrice { get; set; } /// - /// ISO timestamp when transaction was created + /// The amount of gas used by the transaction. /// - [Newtonsoft.Json.JsonProperty("createdAt", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string CreatedAt { get; set; } + [Newtonsoft.Json.JsonProperty("gasUsed", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double GasUsed { get; set; } /// - /// Additional metadata and enriched transaction information + /// The transaction hash. /// - [Newtonsoft.Json.JsonProperty("enrichedData", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public object EnrichedData { get; set; } + [Newtonsoft.Json.JsonProperty("hash", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Hash { get; set; } /// - /// Error message if transaction failed + /// Maximum fee per gas (EIP-1559). /// - [Newtonsoft.Json.JsonProperty("errorMessage", Required = Newtonsoft.Json.Required.AllowNull)] - public string ErrorMessage { get; set; } + [Newtonsoft.Json.JsonProperty("maxFeePerGas", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string MaxFeePerGas { get; set; } /// - /// Parameters used for transaction execution + /// Maximum priority fee per gas (EIP-1559). /// - [Newtonsoft.Json.JsonProperty("executionParams", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public object ExecutionParams { get; set; } + [Newtonsoft.Json.JsonProperty("maxPriorityFeePerGas", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string MaxPriorityFeePerGas { get; set; } /// - /// Result data from transaction execution + /// The transaction nonce. /// - [Newtonsoft.Json.JsonProperty("executionResult", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public object ExecutionResult { get; set; } + [Newtonsoft.Json.JsonProperty("nonce", Required = Newtonsoft.Json.Required.Always)] + public double Nonce { get; set; } /// - /// Sender wallet address + /// The transaction status (1 for success, 0 for failure). /// - [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.AllowNull)] - public string From { get; set; } + [Newtonsoft.Json.JsonProperty("status", Required = Newtonsoft.Json.Required.Always)] + public double Status { get; set; } /// - /// Unique transaction identifier + /// The address that received the transaction. /// - [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("toAddress", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Id { get; set; } + public string ToAddress { get; set; } /// - /// On-chain transaction hash once confirmed + /// The index of the transaction within the block. /// - [Newtonsoft.Json.JsonProperty("transactionHash", Required = Newtonsoft.Json.Required.AllowNull)] - public string TransactionHash { get; set; } + [Newtonsoft.Json.JsonProperty("transactionIndex", Required = Newtonsoft.Json.Required.Always)] + public double TransactionIndex { get; set; } /// - /// Original transaction parameters and data + /// The transaction type (0=legacy, 1=EIP-2930, 2=EIP-1559). /// - [Newtonsoft.Json.JsonProperty("transactionParams", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public object TransactionParams { get; set; } + [Newtonsoft.Json.JsonProperty("transactionType", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double TransactionType { get; set; } /// - /// Transaction status + /// The value transferred in the transaction (in wei as string). /// - [Newtonsoft.Json.JsonProperty("status", Required = Newtonsoft.Json.Required.AllowNull)] - [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] - public Result19Status? Status { get; set; } + [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Value { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -7256,36 +11221,31 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result20 + public partial class Pagination8 { - [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Pagination10 Pagination { get; set; } = new Pagination10(); - - [Newtonsoft.Json.JsonProperty("transactions", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Transactions { get; set; } = new System.Collections.Generic.List(); - - private System.Collections.Generic.IDictionary _additionalProperties; + /// + /// Whether there are more items available + /// + [Newtonsoft.Json.JsonProperty("hasMore", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public bool HasMore { get; set; } - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + /// + /// Number of items per page + /// + [Newtonsoft.Json.JsonProperty("limit", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? Limit { get; set; } = 20D; - } + /// + /// Current page number + /// + [Newtonsoft.Json.JsonProperty("page", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? Page { get; set; } = 1D; - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result21 - { /// - /// Array of unique identifiers for the submitted transactions. Use these to track transaction status. + /// Total number of items available /// - [Newtonsoft.Json.JsonProperty("transactionIds", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List TransactionIds { get; set; } = new System.Collections.Generic.List(); + [Newtonsoft.Json.JsonProperty("totalCount", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double? TotalCount { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -7299,63 +11259,79 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result22 + public partial class Events { /// - /// Payment transaction IDs that were executed + /// The contract address that emitted the event. /// - [Newtonsoft.Json.JsonProperty("transactionIds", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List TransactionIds { get; set; } = new System.Collections.Generic.List(); + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Address { get; set; } - private System.Collections.Generic.IDictionary _additionalProperties; + /// + /// The hash of the block containing this event. + /// + [Newtonsoft.Json.JsonProperty("blockHash", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string BlockHash { get; set; } - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + /// + /// The block number where the event was emitted. + /// + [Newtonsoft.Json.JsonProperty("blockNumber", Required = Newtonsoft.Json.Required.Always)] + public double BlockNumber { get; set; } - } + /// + /// The timestamp of the block (Unix timestamp). + /// + [Newtonsoft.Json.JsonProperty("blockTimestamp", Required = Newtonsoft.Json.Required.Always)] + public double BlockTimestamp { get; set; } - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result23 - { /// - /// The payment ID + /// The chain ID where the event occurred. /// - [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Id { get; set; } + public string ChainId { get; set; } /// - /// The link to purchase the product + /// The non-indexed event data as a hex string. /// - [Newtonsoft.Json.JsonProperty("link", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Link { get; set; } + public string Data { get; set; } - private System.Collections.Generic.IDictionary _additionalProperties; + /// + /// Decoded event data (included when ABI is available). + /// + [Newtonsoft.Json.JsonProperty("decoded", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public Decoded3 Decoded { get; set; } - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + /// + /// The index of the log within the transaction. + /// + [Newtonsoft.Json.JsonProperty("logIndex", Required = Newtonsoft.Json.Required.Always)] + public double LogIndex { get; set; } - } + /// + /// Array of indexed event topics (including event signature). + /// + [Newtonsoft.Json.JsonProperty("topics", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Topics { get; set; } = new System.Collections.ObjectModel.Collection(); + + /// + /// The hash of the transaction containing this event. + /// + [Newtonsoft.Json.JsonProperty("transactionHash", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string TransactionHash { get; set; } - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result24 - { /// - /// Transaction ID that was executed for your product purchase + /// The index of the transaction within the block. /// - [Newtonsoft.Json.JsonProperty("transactionId", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string TransactionId { get; set; } + [Newtonsoft.Json.JsonProperty("transactionIndex", Required = Newtonsoft.Json.Required.Always)] + public double TransactionIndex { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -7369,7 +11345,7 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Pagination + public partial class Pagination9 { /// /// Whether there are more items available @@ -7407,38 +11383,14 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Tokens + public partial class Compiler { /// - /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). - /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] - public int ChainId { get; set; } - - /// - /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). + /// Solidity compiler version used to compile the contract. /// - [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Address { get; set; } - - [Newtonsoft.Json.JsonProperty("decimals", Required = Newtonsoft.Json.Required.Always)] - public double Decimals { get; set; } - - [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("version", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Symbol { get; set; } - - [Newtonsoft.Json.JsonProperty("iconUri", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string IconUri { get; set; } - - /// - /// Token price in different FIAT currencies. - /// - [Newtonsoft.Json.JsonProperty("prices", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.Dictionary Prices { get; set; } = new System.Collections.Generic.Dictionary(); + public string Version { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -7452,18 +11404,25 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Result25 + public partial class Output { /// - /// Array of token owners with amounts. + /// Contract ABI (Application Binary Interface) as an array of function/event/error definitions. /// - [Newtonsoft.Json.JsonProperty("owners", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Owners { get; set; } = new System.Collections.Generic.List(); + [Newtonsoft.Json.JsonProperty("abi", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.ICollection Abi { get; set; } - [Newtonsoft.Json.JsonProperty("pagination", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public Pagination11 Pagination { get; set; } = new Pagination11(); + /// + /// Developer documentation extracted from contract comments. + /// + [Newtonsoft.Json.JsonProperty("devdoc", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.IDictionary Devdoc { get; set; } + + /// + /// User documentation extracted from contract comments. + /// + [Newtonsoft.Json.JsonProperty("userdoc", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.IDictionary Userdoc { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -7476,39 +11435,44 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Initialize the agent - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Actions + public partial class Settings { - [Newtonsoft.Json.JsonProperty("session_id", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Session_id { get; set; } - - [Newtonsoft.Json.JsonProperty("request_id", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Request_id { get; set; } - - [Newtonsoft.Json.JsonProperty("source", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Source { get; set; } = "model"; + /// + /// Compilation target mapping source file names to contract names. + /// + [Newtonsoft.Json.JsonProperty("compilationTarget", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.IDictionary CompilationTarget { get; set; } - [Newtonsoft.Json.JsonProperty("tool_name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Tool_name { get; set; } + /// + /// EVM version target for compilation. + /// + [Newtonsoft.Json.JsonProperty("evmVersion", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string EvmVersion { get; set; } - [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Description { get; set; } + /// + /// Library addresses for linking. + /// + [Newtonsoft.Json.JsonProperty("libraries", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.IDictionary Libraries { get; set; } - [Newtonsoft.Json.JsonProperty("kwargs", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.Generic.Dictionary Kwargs { get; set; } + /// + /// Metadata settings for compilation. + /// + [Newtonsoft.Json.JsonProperty("metadata", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public Metadata2 Metadata { get; set; } - [Newtonsoft.Json.JsonProperty("type", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] - public ActionsType Type { get; set; } + /// + /// Optimizer settings used during compilation. + /// + [Newtonsoft.Json.JsonProperty("optimizer", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public Optimizer Optimizer { get; set; } - [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.AllowNull)] - public object Data { get; set; } + /// + /// Import remappings used during compilation. + /// + [Newtonsoft.Json.JsonProperty("remappings", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.ICollection Remappings { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -7522,55 +11486,25 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public enum MessagesRole - { - - [System.Runtime.Serialization.EnumMember(Value = @"user")] - User = 0, - - [System.Runtime.Serialization.EnumMember(Value = @"assistant")] - Assistant = 1, - - [System.Runtime.Serialization.EnumMember(Value = @"system")] - System = 2, - - } - - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Content + public enum Result20Status { - private System.Collections.Generic.IDictionary _additionalProperties; - - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } - - } + [System.Runtime.Serialization.EnumMember(Value = @"QUEUED")] + QUEUED = 0, - /// - /// Authentication provider details with type-based discrimination - /// - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Profiles - { + [System.Runtime.Serialization.EnumMember(Value = @"SUBMITTED")] + SUBMITTED = 1, - private System.Collections.Generic.IDictionary _additionalProperties; + [System.Runtime.Serialization.EnumMember(Value = @"CONFIRMED")] + CONFIRMED = 2, - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + [System.Runtime.Serialization.EnumMember(Value = @"FAILED")] + FAILED = 3, } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Pagination2 + public partial class Pagination10 { /// /// Whether there are more items available @@ -7608,57 +11542,108 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Wallets + public partial class Transactions2 { /// - /// The EOA (Externally Owned Wallet) address of the wallet. This is the traditional wallet address. + /// Index within transaction batch /// - [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("batchIndex", Required = Newtonsoft.Json.Required.Always)] + public int BatchIndex { get; set; } + + /// + /// ISO timestamp when transaction was cancelled, if applicable + /// + [Newtonsoft.Json.JsonProperty("cancelledAt", Required = Newtonsoft.Json.Required.AllowNull)] + public string CancelledAt { get; set; } + + /// + /// Blockchain network identifier as string + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Address { get; set; } + public string ChainId { get; set; } /// - /// The date and time the wallet was created + /// Client identifier that initiated the transaction /// - [Newtonsoft.Json.JsonProperty("createdAt", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + [Newtonsoft.Json.JsonProperty("clientId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string ClientId { get; set; } + + /// + /// ISO timestamp when transaction was confirmed on-chain + /// + [Newtonsoft.Json.JsonProperty("confirmedAt", Required = Newtonsoft.Json.Required.AllowNull)] + public string ConfirmedAt { get; set; } + + /// + /// Block number where transaction was confirmed + /// + [Newtonsoft.Json.JsonProperty("confirmedAtBlockNumber", Required = Newtonsoft.Json.Required.AllowNull)] + public string ConfirmedAtBlockNumber { get; set; } + + /// + /// ISO timestamp when transaction was created + /// + [Newtonsoft.Json.JsonProperty("createdAt", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] public string CreatedAt { get; set; } /// - /// The profiles linked to the wallet, can be email, phone, google etc, or backend for developer created wallets + /// Additional metadata and enriched transaction information /// - [Newtonsoft.Json.JsonProperty("profiles", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Profiles { get; set; } = new System.Collections.Generic.List(); + [Newtonsoft.Json.JsonProperty("enrichedData", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public object EnrichedData { get; set; } /// - /// The smart wallet address with EIP-4337 support. This address enables gasless transactions and advanced wallet features. + /// Error message if transaction failed /// - [Newtonsoft.Json.JsonProperty("smartWalletAddress", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string SmartWalletAddress { get; set; } + [Newtonsoft.Json.JsonProperty("errorMessage", Required = Newtonsoft.Json.Required.AllowNull)] + public string ErrorMessage { get; set; } /// - /// The wallet's public key in hexadecimal format. Useful for peer-to-peer encryption and cryptographic operations. + /// Parameters used for transaction execution /// - [Newtonsoft.Json.JsonProperty("publicKey", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string PublicKey { get; set; } + [Newtonsoft.Json.JsonProperty("executionParams", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public object ExecutionParams { get; set; } - private System.Collections.Generic.IDictionary _additionalProperties; + /// + /// Result data from transaction execution + /// + [Newtonsoft.Json.JsonProperty("executionResult", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public object ExecutionResult { get; set; } - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + /// + /// Sender wallet address + /// + [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.AllowNull)] + public string From { get; set; } - } + /// + /// Unique transaction identifier + /// + [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Id { get; set; } - /// - /// Authentication provider details with type-based discrimination - /// - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class profiles - { + /// + /// On-chain transaction hash once confirmed + /// + [Newtonsoft.Json.JsonProperty("transactionHash", Required = Newtonsoft.Json.Required.AllowNull)] + public string TransactionHash { get; set; } + + /// + /// Original transaction parameters and data + /// + [Newtonsoft.Json.JsonProperty("transactionParams", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public object TransactionParams { get; set; } + + /// + /// Transaction status + /// + [Newtonsoft.Json.JsonProperty("status", Required = Newtonsoft.Json.Required.AllowNull)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public Transactions2Status? Status { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -7672,31 +11657,53 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Pagination3 + public partial class Quote2 { /// - /// Whether there are more items available + /// Block number when quote was generated /// - [Newtonsoft.Json.JsonProperty("hasMore", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public bool HasMore { get; set; } + [Newtonsoft.Json.JsonProperty("blockNumber", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string BlockNumber { get; set; } /// - /// Number of items per page + /// Destination amount in wei /// - [Newtonsoft.Json.JsonProperty("limit", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? Limit { get; set; } = 20D; + [Newtonsoft.Json.JsonProperty("destinationAmount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string DestinationAmount { get; set; } /// - /// Current page number + /// Estimated execution time in milliseconds /// - [Newtonsoft.Json.JsonProperty("page", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? Page { get; set; } = 1D; + [Newtonsoft.Json.JsonProperty("estimatedExecutionTimeMs", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double EstimatedExecutionTimeMs { get; set; } /// - /// Total number of items available + /// Quote intent details /// - [Newtonsoft.Json.JsonProperty("totalCount", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? TotalCount { get; set; } + [Newtonsoft.Json.JsonProperty("intent", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Intent2 Intent { get; set; } = new Intent2(); + + /// + /// Origin amount in wei + /// + [Newtonsoft.Json.JsonProperty("originAmount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string OriginAmount { get; set; } + + /// + /// Array of steps to complete the bridge operation + /// + [Newtonsoft.Json.JsonProperty("steps", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Steps { get; set; } = new System.Collections.ObjectModel.Collection(); + + /// + /// Quote timestamp + /// + [Newtonsoft.Json.JsonProperty("timestamp", Required = Newtonsoft.Json.Required.Always)] + public double Timestamp { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -7710,39 +11717,53 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class wallets + public partial class Quote3 { /// - /// The EOA (Externally Owned Wallet) address of the wallet. This is the traditional wallet address. + /// Block number when quote was generated /// - [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("blockNumber", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string BlockNumber { get; set; } + + /// + /// Destination amount in wei + /// + [Newtonsoft.Json.JsonProperty("destinationAmount", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Address { get; set; } + public string DestinationAmount { get; set; } /// - /// The date and time the wallet was created + /// Estimated execution time in milliseconds /// - [Newtonsoft.Json.JsonProperty("createdAt", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string CreatedAt { get; set; } + [Newtonsoft.Json.JsonProperty("estimatedExecutionTimeMs", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double EstimatedExecutionTimeMs { get; set; } /// - /// The profiles linked to the wallet, can be email, phone, google etc, or backend for developer created wallets + /// Quote intent details /// - [Newtonsoft.Json.JsonProperty("profiles", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("intent", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Profiles { get; set; } = new System.Collections.Generic.List(); + public Intent3 Intent { get; set; } = new Intent3(); /// - /// The smart wallet address with EIP-4337 support. This address enables gasless transactions and advanced wallet features. + /// Origin amount in wei /// - [Newtonsoft.Json.JsonProperty("smartWalletAddress", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string SmartWalletAddress { get; set; } + [Newtonsoft.Json.JsonProperty("originAmount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string OriginAmount { get; set; } /// - /// The wallet's public key in hexadecimal format. Useful for peer-to-peer encryption and cryptographic operations. + /// Array of steps to complete the bridge operation /// - [Newtonsoft.Json.JsonProperty("publicKey", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string PublicKey { get; set; } + [Newtonsoft.Json.JsonProperty("steps", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Steps { get; set; } = new System.Collections.ObjectModel.Collection(); + + /// + /// Quote timestamp + /// + [Newtonsoft.Json.JsonProperty("timestamp", Required = Newtonsoft.Json.Required.Always)] + public double Timestamp { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -7755,12 +11776,16 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Authentication provider details with type-based discrimination - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Profiles2 + public partial class Transactions3 { + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } + + [Newtonsoft.Json.JsonProperty("transactionHash", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string TransactionHash { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -7774,31 +11799,69 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Pagination4 + public enum DataStatus { - /// - /// Whether there are more items available - /// - [Newtonsoft.Json.JsonProperty("hasMore", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public bool HasMore { get; set; } - /// - /// Number of items per page - /// - [Newtonsoft.Json.JsonProperty("limit", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? Limit { get; set; } = 20D; + [System.Runtime.Serialization.EnumMember(Value = @"PENDING")] + PENDING = 0, - /// - /// Current page number - /// - [Newtonsoft.Json.JsonProperty("page", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? Page { get; set; } = 1D; + [System.Runtime.Serialization.EnumMember(Value = @"COMPLETED")] + COMPLETED = 1, + + [System.Runtime.Serialization.EnumMember(Value = @"FAILED")] + FAILED = 2, + + [System.Runtime.Serialization.EnumMember(Value = @"NOT_FOUND")] + NOT_FOUND = 3, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum DataType + { + + [System.Runtime.Serialization.EnumMember(Value = @"buy")] + Buy = 0, + + [System.Runtime.Serialization.EnumMember(Value = @"sell")] + Sell = 1, + + [System.Runtime.Serialization.EnumMember(Value = @"transfer")] + Transfer = 2, + + [System.Runtime.Serialization.EnumMember(Value = @"onramp")] + Onramp = 3, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class OriginToken + { + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } /// - /// Total number of items available + /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). /// - [Newtonsoft.Json.JsonProperty("totalCount", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? TotalCount { get; set; } + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Address { get; set; } + + [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Symbol { get; set; } + + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Name { get; set; } + + [Newtonsoft.Json.JsonProperty("decimals", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int Decimals { get; set; } + + [Newtonsoft.Json.JsonProperty("iconUri", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string IconUri { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -7812,154 +11875,108 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class transactions + public partial class DestinationToken { - /// - /// The hash of the block containing this transaction. - /// - [Newtonsoft.Json.JsonProperty("blockHash", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string BlockHash { get; set; } + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } /// - /// The block number containing this transaction. + /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). /// - [Newtonsoft.Json.JsonProperty("blockNumber", Required = Newtonsoft.Json.Required.Always)] - public double BlockNumber { get; set; } + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Address { get; set; } - /// - /// The timestamp of the block (Unix timestamp). - /// - [Newtonsoft.Json.JsonProperty("blockTimestamp", Required = Newtonsoft.Json.Required.Always)] - public double BlockTimestamp { get; set; } + [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Symbol { get; set; } - /// - /// The chain ID where the transaction occurred. - /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string ChainId { get; set; } + public string Name { get; set; } - /// - /// Contract address created if this was a contract creation transaction. - /// - [Newtonsoft.Json.JsonProperty("contractAddress", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string ContractAddress { get; set; } + [Newtonsoft.Json.JsonProperty("decimals", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int Decimals { get; set; } - /// - /// Total gas used by all transactions in this block up to and including this one. - /// - [Newtonsoft.Json.JsonProperty("cumulativeGasUsed", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double CumulativeGasUsed { get; set; } + [Newtonsoft.Json.JsonProperty("iconUri", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string IconUri { get; set; } - /// - /// The transaction input data. - /// - [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Data { get; set; } + private System.Collections.Generic.IDictionary _additionalProperties; - /// - /// Decoded transaction data (included when ABI is available). - /// - [Newtonsoft.Json.JsonProperty("decoded", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public Decoded Decoded { get; set; } + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } - /// - /// The effective gas price paid (in wei as string). - /// - [Newtonsoft.Json.JsonProperty("effectiveGasPrice", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string EffectiveGasPrice { get; set; } + } - /// - /// The address that initiated the transaction. - /// - [Newtonsoft.Json.JsonProperty("fromAddress", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string FromAddress { get; set; } + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum KindsScheme + { - /// - /// The function selector (first 4 bytes of the transaction data). - /// - [Newtonsoft.Json.JsonProperty("functionSelector", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string FunctionSelector { get; set; } + [System.Runtime.Serialization.EnumMember(Value = @"exact")] + Exact = 0, - /// - /// The gas limit for the transaction. - /// - [Newtonsoft.Json.JsonProperty("gas", Required = Newtonsoft.Json.Required.Always)] - public double Gas { get; set; } + } - /// - /// The gas price used for the transaction (in wei as string). - /// - [Newtonsoft.Json.JsonProperty("gasPrice", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string GasPrice { get; set; } + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Network5 + { - /// - /// The amount of gas used by the transaction. - /// - [Newtonsoft.Json.JsonProperty("gasUsed", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double GasUsed { get; set; } + private System.Collections.Generic.IDictionary _additionalProperties; - /// - /// The transaction hash. - /// - [Newtonsoft.Json.JsonProperty("hash", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Hash { get; set; } + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } - /// - /// Maximum fee per gas (EIP-1559). - /// - [Newtonsoft.Json.JsonProperty("maxFeePerGas", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string MaxFeePerGas { get; set; } + } - /// - /// Maximum priority fee per gas (EIP-1559). - /// - [Newtonsoft.Json.JsonProperty("maxPriorityFeePerGas", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string MaxPriorityFeePerGas { get; set; } + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Extra + { + [Newtonsoft.Json.JsonProperty("defaultAsset", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public DefaultAsset DefaultAsset { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; - /// - /// The transaction nonce. - /// - [Newtonsoft.Json.JsonProperty("nonce", Required = Newtonsoft.Json.Required.Always)] - public double Nonce { get; set; } + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } - /// - /// The transaction status (1 for success, 0 for failure). - /// - [Newtonsoft.Json.JsonProperty("status", Required = Newtonsoft.Json.Required.Always)] - public double Status { get; set; } + } + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Owners + { /// - /// The address that received the transaction. + /// Owner wallet address /// - [Newtonsoft.Json.JsonProperty("toAddress", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string ToAddress { get; set; } - - /// - /// The index of the transaction within the block. - /// - [Newtonsoft.Json.JsonProperty("transactionIndex", Required = Newtonsoft.Json.Required.Always)] - public double TransactionIndex { get; set; } + public string Address { get; set; } /// - /// The transaction type (0=legacy, 1=EIP-2930, 2=EIP-1559). + /// Token amount owned as a string /// - [Newtonsoft.Json.JsonProperty("transactionType", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double TransactionType { get; set; } + [Newtonsoft.Json.JsonProperty("amount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Amount { get; set; } /// - /// The value transferred in the transaction (in wei as string). + /// Token ID for NFTs /// - [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Value { get; set; } + [Newtonsoft.Json.JsonProperty("tokenId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string TokenId { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -7973,7 +11990,7 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Pagination5 + public partial class Pagination11 { /// /// Whether there are more items available @@ -8011,51 +12028,87 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class tokens + public partial class NativeCurrency { /// - /// The token balance as a string + /// The name of the native currency /// - [Newtonsoft.Json.JsonProperty("balance", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Balance { get; set; } + public string Name { get; set; } /// - /// The chain ID of the token + /// The symbol of the native currency /// - [Newtonsoft.Json.JsonProperty("chain_id", Required = Newtonsoft.Json.Required.Always)] - public double Chain_id { get; set; } + [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Symbol { get; set; } /// - /// The number of decimal places + /// The number of decimals used by the native currency /// - [Newtonsoft.Json.JsonProperty("decimals", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + [Newtonsoft.Json.JsonProperty("decimals", Required = Newtonsoft.Json.Required.Always)] public double Decimals { get; set; } + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Quote4 + { /// - /// The token name + /// Block number when quote was generated /// - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Name { get; set; } + [Newtonsoft.Json.JsonProperty("blockNumber", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string BlockNumber { get; set; } /// - /// Price data for the token + /// Destination amount in wei /// - [Newtonsoft.Json.JsonProperty("price_data", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public Price_data Price_data { get; set; } + [Newtonsoft.Json.JsonProperty("destinationAmount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string DestinationAmount { get; set; } /// - /// The token symbol + /// Estimated execution time in milliseconds /// - [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Symbol { get; set; } + [Newtonsoft.Json.JsonProperty("estimatedExecutionTimeMs", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double EstimatedExecutionTimeMs { get; set; } /// - /// The contract address of the token + /// Quote intent details /// - [Newtonsoft.Json.JsonProperty("token_address", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("intent", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Intent4 Intent { get; set; } = new Intent4(); + + /// + /// Origin amount in wei + /// + [Newtonsoft.Json.JsonProperty("originAmount", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Token_address { get; set; } + public string OriginAmount { get; set; } + + /// + /// Array of steps to complete the bridge operation + /// + [Newtonsoft.Json.JsonProperty("steps", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Steps { get; set; } = new System.Collections.ObjectModel.Collection(); + + /// + /// Quote timestamp + /// + [Newtonsoft.Json.JsonProperty("timestamp", Required = Newtonsoft.Json.Required.Always)] + public double Timestamp { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -8069,75 +12122,199 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Nfts + public enum ActionsType + { + + [System.Runtime.Serialization.EnumMember(Value = @"sign_transaction")] + Sign_transaction = 0, + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Data2 + { + [Newtonsoft.Json.JsonProperty("chain_id", Required = Newtonsoft.Json.Required.Always)] + public double Chain_id { get; set; } + + [Newtonsoft.Json.JsonProperty("function", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Function { get; set; } + + [Newtonsoft.Json.JsonProperty("to", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string To { get; set; } + + [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Value { get; set; } + + [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Data { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Authentication provider details with type-based discrimination + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Profiles3 + { + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + /// + /// Authentication provider details with type-based discrimination + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Profiles4 + { + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Decoded { /// - /// The animation URL of the NFT + /// Object containing decoded function parameters. /// - [Newtonsoft.Json.JsonProperty("animation_url", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Animation_url { get; set; } + [Newtonsoft.Json.JsonProperty("inputs", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.IDictionary Inputs { get; set; } = new System.Collections.Generic.Dictionary(); /// - /// The attributes/traits of the NFT + /// The function name. /// - [Newtonsoft.Json.JsonProperty("attributes", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.Generic.List Attributes { get; set; } + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Name { get; set; } /// - /// The chain ID of the NFT + /// The function signature. /// - [Newtonsoft.Json.JsonProperty("chain_id", Required = Newtonsoft.Json.Required.Always)] - public double Chain_id { get; set; } + [Newtonsoft.Json.JsonProperty("signature", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Signature { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Price_data + { /// - /// Collection information + /// The circulating supply of the token /// - [Newtonsoft.Json.JsonProperty("collection", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public Collection Collection { get; set; } + [Newtonsoft.Json.JsonProperty("circulating_supply", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double Circulating_supply { get; set; } /// - /// The description of the NFT + /// The market cap of the token in USD /// - [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Description { get; set; } + [Newtonsoft.Json.JsonProperty("market_cap_usd", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double Market_cap_usd { get; set; } /// - /// The external URL of the NFT + /// The percentage change of the token in the last 24 hours /// - [Newtonsoft.Json.JsonProperty("external_url", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string External_url { get; set; } + [Newtonsoft.Json.JsonProperty("percent_change_24h", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double Percent_change_24h { get; set; } /// - /// The image URL of the NFT + /// The timestamp of the latest price update /// - [Newtonsoft.Json.JsonProperty("image_url", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Image_url { get; set; } + [Newtonsoft.Json.JsonProperty("price_timestamp", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Price_timestamp { get; set; } + + /// + /// The price of the token in USD + /// + [Newtonsoft.Json.JsonProperty("price_usd", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double Price_usd { get; set; } + + /// + /// The total supply of the token + /// + [Newtonsoft.Json.JsonProperty("total_supply", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double Total_supply { get; set; } + + /// + /// The value of the token balance in USD + /// + [Newtonsoft.Json.JsonProperty("usd_value", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double Usd_value { get; set; } + + /// + /// The volume of the token in USD + /// + [Newtonsoft.Json.JsonProperty("volume_24h_usd", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double Volume_24h_usd { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } - /// - /// Additional metadata for the NFT - /// - [Newtonsoft.Json.JsonProperty("metadata", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.Generic.Dictionary Metadata { get; set; } + } + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Attributes + { /// - /// The name of the NFT + /// The display type /// - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Name { get; set; } + [Newtonsoft.Json.JsonProperty("display_type", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Display_type { get; set; } /// - /// The contract address of the NFT collection + /// The trait type /// - [Newtonsoft.Json.JsonProperty("token_address", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Token_address { get; set; } + [Newtonsoft.Json.JsonProperty("trait_type", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Trait_type { get; set; } /// - /// The token ID of the NFT + /// The trait value /// - [Newtonsoft.Json.JsonProperty("token_id", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Token_id { get; set; } + [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public Value Value { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -8151,31 +12328,31 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Pagination6 + public partial class Collection { /// - /// Whether there are more items available + /// The collection description /// - [Newtonsoft.Json.JsonProperty("hasMore", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public bool HasMore { get; set; } + [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Description { get; set; } /// - /// Number of items per page + /// The collection external URL /// - [Newtonsoft.Json.JsonProperty("limit", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? Limit { get; set; } = 20D; + [Newtonsoft.Json.JsonProperty("external_url", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string External_url { get; set; } /// - /// Current page number + /// The collection image URL /// - [Newtonsoft.Json.JsonProperty("page", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? Page { get; set; } = 1D; + [Newtonsoft.Json.JsonProperty("image", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Image { get; set; } /// - /// Total number of items available + /// The collection name /// - [Newtonsoft.Json.JsonProperty("totalCount", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? TotalCount { get; set; } + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Name { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -8188,62 +12365,57 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Contract details enriched with additional project information from the API server. - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Contracts + public partial class Intent { /// - /// The contract address. + /// The amount in wei /// - [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("amount", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Address { get; set; } + public string Amount { get; set; } /// - /// The chain ID where the contract is deployed. + /// Destination chain ID /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string ChainId { get; set; } + [Newtonsoft.Json.JsonProperty("destinationChainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int DestinationChainId { get; set; } /// - /// The date when the contract was deployed. + /// Destination token address /// - [Newtonsoft.Json.JsonProperty("deployedAt", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string DeployedAt { get; set; } + [Newtonsoft.Json.JsonProperty("destinationTokenAddress", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string DestinationTokenAddress { get; set; } /// - /// The contract ID. + /// Origin chain ID /// - [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Id { get; set; } + [Newtonsoft.Json.JsonProperty("originChainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int OriginChainId { get; set; } /// - /// The date when the contract was imported to the dashboard. + /// Origin token address /// - [Newtonsoft.Json.JsonProperty("importedAt", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("originTokenAddress", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string ImportedAt { get; set; } - - /// - /// The contract name, if available. - /// - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Name { get; set; } + public string OriginTokenAddress { get; set; } /// - /// The contract symbol, if available. + /// Receiver address /// - [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Symbol { get; set; } + [Newtonsoft.Json.JsonProperty("receiver", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Receiver { get; set; } /// - /// The contract type (e.g., ERC20, ERC721, etc.). + /// Sender address /// - [Newtonsoft.Json.JsonProperty("type", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Type { get; set; } + [Newtonsoft.Json.JsonProperty("sender", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Sender { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -8257,31 +12429,48 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Pagination7 + public partial class Steps { /// - /// Whether there are more items available + /// Origin token information /// - [Newtonsoft.Json.JsonProperty("hasMore", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public bool HasMore { get; set; } + [Newtonsoft.Json.JsonProperty("originToken", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public OriginToken2 OriginToken { get; set; } = new OriginToken2(); /// - /// Number of items per page + /// Destination token information /// - [Newtonsoft.Json.JsonProperty("limit", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? Limit { get; set; } = 20D; + [Newtonsoft.Json.JsonProperty("destinationToken", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public DestinationToken2 DestinationToken { get; set; } = new DestinationToken2(); /// - /// Current page number + /// Array of transactions for this step /// - [Newtonsoft.Json.JsonProperty("page", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? Page { get; set; } = 1D; + [Newtonsoft.Json.JsonProperty("transactions", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Transactions { get; set; } = new System.Collections.ObjectModel.Collection(); /// - /// Total number of items available + /// Origin amount in wei /// - [Newtonsoft.Json.JsonProperty("totalCount", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? TotalCount { get; set; } + [Newtonsoft.Json.JsonProperty("originAmount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string OriginAmount { get; set; } + + /// + /// Destination amount in wei + /// + [Newtonsoft.Json.JsonProperty("destinationAmount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string DestinationAmount { get; set; } + + /// + /// Estimated execution time in milliseconds + /// + [Newtonsoft.Json.JsonProperty("estimatedExecutionTimeMs", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double EstimatedExecutionTimeMs { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -8295,154 +12484,190 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Data + public partial class Decoded2 { /// - /// The hash of the block containing this transaction. - /// - [Newtonsoft.Json.JsonProperty("blockHash", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string BlockHash { get; set; } - - /// - /// The block number containing this transaction. + /// Object containing decoded function parameters. /// - [Newtonsoft.Json.JsonProperty("blockNumber", Required = Newtonsoft.Json.Required.Always)] - public double BlockNumber { get; set; } + [Newtonsoft.Json.JsonProperty("inputs", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.IDictionary Inputs { get; set; } = new System.Collections.Generic.Dictionary(); /// - /// The timestamp of the block (Unix timestamp). + /// The function name. /// - [Newtonsoft.Json.JsonProperty("blockTimestamp", Required = Newtonsoft.Json.Required.Always)] - public double BlockTimestamp { get; set; } + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Name { get; set; } /// - /// The chain ID where the transaction occurred. + /// The function signature. /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("signature", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string ChainId { get; set; } + public string Signature { get; set; } - /// - /// Contract address created if this was a contract creation transaction. - /// - [Newtonsoft.Json.JsonProperty("contractAddress", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string ContractAddress { get; set; } + private System.Collections.Generic.IDictionary _additionalProperties; - /// - /// Total gas used by all transactions in this block up to and including this one. - /// - [Newtonsoft.Json.JsonProperty("cumulativeGasUsed", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double CumulativeGasUsed { get; set; } + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Decoded3 + { /// - /// The transaction input data. + /// The event name. /// - [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Data1 { get; set; } + public string Name { get; set; } /// - /// Decoded transaction data (included when ABI is available). + /// Object containing decoded parameters. /// - [Newtonsoft.Json.JsonProperty("decoded", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public Decoded2 Decoded { get; set; } + [Newtonsoft.Json.JsonProperty("params", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.IDictionary Params { get; set; } = new System.Collections.Generic.Dictionary(); /// - /// The effective gas price paid (in wei as string). + /// The event signature. /// - [Newtonsoft.Json.JsonProperty("effectiveGasPrice", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string EffectiveGasPrice { get; set; } + [Newtonsoft.Json.JsonProperty("signature", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Signature { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Metadata2 + { /// - /// The address that initiated the transaction. + /// Hash method used for bytecode metadata. /// - [Newtonsoft.Json.JsonProperty("fromAddress", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string FromAddress { get; set; } + [Newtonsoft.Json.JsonProperty("bytecodeHash", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string BytecodeHash { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Optimizer + { /// - /// The function selector (first 4 bytes of the transaction data). + /// Whether optimizer is enabled. /// - [Newtonsoft.Json.JsonProperty("functionSelector", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string FunctionSelector { get; set; } + [Newtonsoft.Json.JsonProperty("enabled", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public bool Enabled { get; set; } /// - /// The gas limit for the transaction. + /// Number of optimizer runs. /// - [Newtonsoft.Json.JsonProperty("gas", Required = Newtonsoft.Json.Required.Always)] - public double Gas { get; set; } + [Newtonsoft.Json.JsonProperty("runs", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double Runs { get; set; } + + private System.Collections.Generic.IDictionary _additionalProperties; + + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } + + } + + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public enum Transactions2Status + { + + [System.Runtime.Serialization.EnumMember(Value = @"QUEUED")] + QUEUED = 0, - /// - /// The gas price used for the transaction (in wei as string). - /// - [Newtonsoft.Json.JsonProperty("gasPrice", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string GasPrice { get; set; } + [System.Runtime.Serialization.EnumMember(Value = @"SUBMITTED")] + SUBMITTED = 1, - /// - /// The amount of gas used by the transaction. - /// - [Newtonsoft.Json.JsonProperty("gasUsed", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double GasUsed { get; set; } + [System.Runtime.Serialization.EnumMember(Value = @"CONFIRMED")] + CONFIRMED = 2, - /// - /// The transaction hash. - /// - [Newtonsoft.Json.JsonProperty("hash", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Hash { get; set; } + [System.Runtime.Serialization.EnumMember(Value = @"FAILED")] + FAILED = 3, - /// - /// Maximum fee per gas (EIP-1559). - /// - [Newtonsoft.Json.JsonProperty("maxFeePerGas", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string MaxFeePerGas { get; set; } + } + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Intent2 + { /// - /// Maximum priority fee per gas (EIP-1559). + /// The amount in wei /// - [Newtonsoft.Json.JsonProperty("maxPriorityFeePerGas", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string MaxPriorityFeePerGas { get; set; } + [Newtonsoft.Json.JsonProperty("amount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Amount { get; set; } /// - /// The transaction nonce. + /// Destination chain ID /// - [Newtonsoft.Json.JsonProperty("nonce", Required = Newtonsoft.Json.Required.Always)] - public double Nonce { get; set; } + [Newtonsoft.Json.JsonProperty("destinationChainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int DestinationChainId { get; set; } /// - /// The transaction status (1 for success, 0 for failure). + /// Destination token address /// - [Newtonsoft.Json.JsonProperty("status", Required = Newtonsoft.Json.Required.Always)] - public double Status { get; set; } + [Newtonsoft.Json.JsonProperty("destinationTokenAddress", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string DestinationTokenAddress { get; set; } /// - /// The address that received the transaction. + /// Origin chain ID /// - [Newtonsoft.Json.JsonProperty("toAddress", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string ToAddress { get; set; } + [Newtonsoft.Json.JsonProperty("originChainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int OriginChainId { get; set; } /// - /// The index of the transaction within the block. + /// Origin token address /// - [Newtonsoft.Json.JsonProperty("transactionIndex", Required = Newtonsoft.Json.Required.Always)] - public double TransactionIndex { get; set; } + [Newtonsoft.Json.JsonProperty("originTokenAddress", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string OriginTokenAddress { get; set; } /// - /// The transaction type (0=legacy, 1=EIP-2930, 2=EIP-1559). + /// Receiver address /// - [Newtonsoft.Json.JsonProperty("transactionType", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double TransactionType { get; set; } + [Newtonsoft.Json.JsonProperty("receiver", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Receiver { get; set; } /// - /// The value transferred in the transaction (in wei as string). + /// Sender address /// - [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("sender", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Value { get; set; } + public string Sender { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -8456,31 +12681,48 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Pagination8 + public partial class steps { /// - /// Whether there are more items available + /// Origin token information /// - [Newtonsoft.Json.JsonProperty("hasMore", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public bool HasMore { get; set; } + [Newtonsoft.Json.JsonProperty("originToken", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public OriginToken3 OriginToken { get; set; } = new OriginToken3(); /// - /// Number of items per page + /// Destination token information /// - [Newtonsoft.Json.JsonProperty("limit", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? Limit { get; set; } = 20D; + [Newtonsoft.Json.JsonProperty("destinationToken", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public DestinationToken3 DestinationToken { get; set; } = new DestinationToken3(); /// - /// Current page number + /// Array of transactions for this step /// - [Newtonsoft.Json.JsonProperty("page", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? Page { get; set; } = 1D; + [Newtonsoft.Json.JsonProperty("transactions", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Transactions { get; set; } = new System.Collections.ObjectModel.Collection(); /// - /// Total number of items available + /// Origin amount in wei /// - [Newtonsoft.Json.JsonProperty("totalCount", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? TotalCount { get; set; } + [Newtonsoft.Json.JsonProperty("originAmount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string OriginAmount { get; set; } + + /// + /// Destination amount in wei + /// + [Newtonsoft.Json.JsonProperty("destinationAmount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string DestinationAmount { get; set; } + + /// + /// Estimated execution time in milliseconds + /// + [Newtonsoft.Json.JsonProperty("estimatedExecutionTimeMs", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double EstimatedExecutionTimeMs { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -8494,79 +12736,56 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Events + public partial class Intent3 { /// - /// The contract address that emitted the event. + /// The amount in wei /// - [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("amount", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Address { get; set; } + public string Amount { get; set; } /// - /// The hash of the block containing this event. + /// Destination chain ID /// - [Newtonsoft.Json.JsonProperty("blockHash", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string BlockHash { get; set; } + [Newtonsoft.Json.JsonProperty("destinationChainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int DestinationChainId { get; set; } /// - /// The block number where the event was emitted. + /// Destination token address /// - [Newtonsoft.Json.JsonProperty("blockNumber", Required = Newtonsoft.Json.Required.Always)] - public double BlockNumber { get; set; } + [Newtonsoft.Json.JsonProperty("destinationTokenAddress", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string DestinationTokenAddress { get; set; } /// - /// The timestamp of the block (Unix timestamp). + /// Origin chain ID /// - [Newtonsoft.Json.JsonProperty("blockTimestamp", Required = Newtonsoft.Json.Required.Always)] - public double BlockTimestamp { get; set; } + [Newtonsoft.Json.JsonProperty("originChainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int OriginChainId { get; set; } /// - /// The chain ID where the event occurred. + /// Origin token address /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("originTokenAddress", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string ChainId { get; set; } + public string OriginTokenAddress { get; set; } /// - /// The non-indexed event data as a hex string. + /// Receiver address /// - [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("receiver", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Data { get; set; } - - /// - /// Decoded event data (included when ABI is available). - /// - [Newtonsoft.Json.JsonProperty("decoded", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public Decoded3 Decoded { get; set; } - - /// - /// The index of the log within the transaction. - /// - [Newtonsoft.Json.JsonProperty("logIndex", Required = Newtonsoft.Json.Required.Always)] - public double LogIndex { get; set; } - - /// - /// Array of indexed event topics (including event signature). - /// - [Newtonsoft.Json.JsonProperty("topics", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.List Topics { get; set; } = new System.Collections.Generic.List(); + public string Receiver { get; set; } /// - /// The hash of the transaction containing this event. + /// Sender address /// - [Newtonsoft.Json.JsonProperty("transactionHash", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("sender", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string TransactionHash { get; set; } - - /// - /// The index of the transaction within the block. - /// - [Newtonsoft.Json.JsonProperty("transactionIndex", Required = Newtonsoft.Json.Required.Always)] - public double TransactionIndex { get; set; } + public string Sender { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -8580,31 +12799,48 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Pagination9 + public partial class Steps2 { /// - /// Whether there are more items available + /// Origin token information /// - [Newtonsoft.Json.JsonProperty("hasMore", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public bool HasMore { get; set; } + [Newtonsoft.Json.JsonProperty("originToken", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public OriginToken4 OriginToken { get; set; } = new OriginToken4(); /// - /// Number of items per page + /// Destination token information /// - [Newtonsoft.Json.JsonProperty("limit", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? Limit { get; set; } = 20D; + [Newtonsoft.Json.JsonProperty("destinationToken", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public DestinationToken4 DestinationToken { get; set; } = new DestinationToken4(); /// - /// Current page number + /// Array of transactions for this step /// - [Newtonsoft.Json.JsonProperty("page", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? Page { get; set; } = 1D; + [Newtonsoft.Json.JsonProperty("transactions", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Transactions { get; set; } = new System.Collections.ObjectModel.Collection(); /// - /// Total number of items available + /// Origin amount in wei /// - [Newtonsoft.Json.JsonProperty("totalCount", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? TotalCount { get; set; } + [Newtonsoft.Json.JsonProperty("originAmount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string OriginAmount { get; set; } + + /// + /// Destination amount in wei + /// + [Newtonsoft.Json.JsonProperty("destinationAmount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string DestinationAmount { get; set; } + + /// + /// Estimated execution time in milliseconds + /// + [Newtonsoft.Json.JsonProperty("estimatedExecutionTimeMs", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double EstimatedExecutionTimeMs { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -8618,14 +12854,18 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Compiler + public partial class DefaultAsset { - /// - /// Solidity compiler version used to compile the contract. - /// - [Newtonsoft.Json.JsonProperty("version", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Version { get; set; } + public string Address { get; set; } + + [Newtonsoft.Json.JsonProperty("decimals", Required = Newtonsoft.Json.Required.Always)] + public double Decimals { get; set; } + + [Newtonsoft.Json.JsonProperty("eip712", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public Eip712 Eip712 { get; set; } = new Eip712(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -8639,25 +12879,56 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Output + public partial class Intent4 { /// - /// Contract ABI (Application Binary Interface) as an array of function/event/error definitions. + /// The amount in wei /// - [Newtonsoft.Json.JsonProperty("abi", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.Generic.List Abi { get; set; } + [Newtonsoft.Json.JsonProperty("amount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Amount { get; set; } /// - /// Developer documentation extracted from contract comments. + /// Destination chain ID /// - [Newtonsoft.Json.JsonProperty("devdoc", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.Generic.Dictionary Devdoc { get; set; } + [Newtonsoft.Json.JsonProperty("destinationChainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int DestinationChainId { get; set; } /// - /// User documentation extracted from contract comments. + /// Destination token address /// - [Newtonsoft.Json.JsonProperty("userdoc", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.Generic.Dictionary Userdoc { get; set; } + [Newtonsoft.Json.JsonProperty("destinationTokenAddress", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string DestinationTokenAddress { get; set; } + + /// + /// Origin chain ID + /// + [Newtonsoft.Json.JsonProperty("originChainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int OriginChainId { get; set; } + + /// + /// Origin token address + /// + [Newtonsoft.Json.JsonProperty("originTokenAddress", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string OriginTokenAddress { get; set; } + + /// + /// Receiver address + /// + [Newtonsoft.Json.JsonProperty("receiver", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Receiver { get; set; } + + /// + /// Sender address + /// + [Newtonsoft.Json.JsonProperty("sender", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Sender { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -8671,43 +12942,48 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Settings + public partial class Steps3 { /// - /// Compilation target mapping source file names to contract names. + /// Origin token information /// - [Newtonsoft.Json.JsonProperty("compilationTarget", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.Generic.Dictionary CompilationTarget { get; set; } + [Newtonsoft.Json.JsonProperty("originToken", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public OriginToken5 OriginToken { get; set; } = new OriginToken5(); /// - /// EVM version target for compilation. + /// Destination token information /// - [Newtonsoft.Json.JsonProperty("evmVersion", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string EvmVersion { get; set; } + [Newtonsoft.Json.JsonProperty("destinationToken", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public DestinationToken5 DestinationToken { get; set; } = new DestinationToken5(); /// - /// Library addresses for linking. + /// Array of transactions for this step /// - [Newtonsoft.Json.JsonProperty("libraries", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.Generic.Dictionary Libraries { get; set; } + [Newtonsoft.Json.JsonProperty("transactions", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.ICollection Transactions { get; set; } = new System.Collections.ObjectModel.Collection(); /// - /// Metadata settings for compilation. + /// Origin amount in wei /// - [Newtonsoft.Json.JsonProperty("metadata", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public Metadata Metadata { get; set; } + [Newtonsoft.Json.JsonProperty("originAmount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string OriginAmount { get; set; } /// - /// Optimizer settings used during compilation. + /// Destination amount in wei /// - [Newtonsoft.Json.JsonProperty("optimizer", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public Optimizer Optimizer { get; set; } + [Newtonsoft.Json.JsonProperty("destinationAmount", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string DestinationAmount { get; set; } /// - /// Import remappings used during compilation. + /// Estimated execution time in milliseconds /// - [Newtonsoft.Json.JsonProperty("remappings", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public System.Collections.Generic.List Remappings { get; set; } + [Newtonsoft.Json.JsonProperty("estimatedExecutionTimeMs", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public double EstimatedExecutionTimeMs { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -8721,49 +12997,53 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public enum Result19Status + public partial class Value { - [System.Runtime.Serialization.EnumMember(Value = @"QUEUED")] - QUEUED = 0, - - [System.Runtime.Serialization.EnumMember(Value = @"SUBMITTED")] - SUBMITTED = 1, - - [System.Runtime.Serialization.EnumMember(Value = @"CONFIRMED")] - CONFIRMED = 2, + private System.Collections.Generic.IDictionary _additionalProperties; - [System.Runtime.Serialization.EnumMember(Value = @"FAILED")] - FAILED = 3, + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Pagination10 + public partial class OriginToken2 { /// - /// Whether there are more items available - /// - [Newtonsoft.Json.JsonProperty("hasMore", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public bool HasMore { get; set; } - - /// - /// Number of items per page + /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). /// - [Newtonsoft.Json.JsonProperty("limit", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? Limit { get; set; } = 20D; + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } /// - /// Current page number + /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). /// - [Newtonsoft.Json.JsonProperty("page", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? Page { get; set; } = 1D; + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Address { get; set; } + + [Newtonsoft.Json.JsonProperty("decimals", Required = Newtonsoft.Json.Required.Always)] + public double Decimals { get; set; } + + [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Symbol { get; set; } + + [Newtonsoft.Json.JsonProperty("iconUri", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string IconUri { get; set; } /// - /// Total number of items available + /// Token price in different FIAT currencies. /// - [Newtonsoft.Json.JsonProperty("totalCount", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? TotalCount { get; set; } + [Newtonsoft.Json.JsonProperty("prices", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.IDictionary Prices { get; set; } = new System.Collections.Generic.Dictionary(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -8777,108 +13057,99 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Transactions2 + public partial class DestinationToken2 { /// - /// Index within transaction batch - /// - [Newtonsoft.Json.JsonProperty("batchIndex", Required = Newtonsoft.Json.Required.Always)] - public int BatchIndex { get; set; } - - /// - /// ISO timestamp when transaction was cancelled, if applicable + /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). /// - [Newtonsoft.Json.JsonProperty("cancelledAt", Required = Newtonsoft.Json.Required.AllowNull)] - public string CancelledAt { get; set; } + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } /// - /// Blockchain network identifier as string + /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). /// - [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string ChainId { get; set; } + public string Address { get; set; } - /// - /// Client identifier that initiated the transaction - /// - [Newtonsoft.Json.JsonProperty("clientId", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("decimals", Required = Newtonsoft.Json.Required.Always)] + public double Decimals { get; set; } + + [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string ClientId { get; set; } + public string Symbol { get; set; } - /// - /// ISO timestamp when transaction was confirmed on-chain - /// - [Newtonsoft.Json.JsonProperty("confirmedAt", Required = Newtonsoft.Json.Required.AllowNull)] - public string ConfirmedAt { get; set; } + [Newtonsoft.Json.JsonProperty("iconUri", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string IconUri { get; set; } /// - /// Block number where transaction was confirmed + /// Token price in different FIAT currencies. /// - [Newtonsoft.Json.JsonProperty("confirmedAtBlockNumber", Required = Newtonsoft.Json.Required.AllowNull)] - public string ConfirmedAtBlockNumber { get; set; } + [Newtonsoft.Json.JsonProperty("prices", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.IDictionary Prices { get; set; } = new System.Collections.Generic.Dictionary(); - /// - /// ISO timestamp when transaction was created - /// - [Newtonsoft.Json.JsonProperty("createdAt", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string CreatedAt { get; set; } + private System.Collections.Generic.IDictionary _additionalProperties; - /// - /// Additional metadata and enriched transaction information - /// - [Newtonsoft.Json.JsonProperty("enrichedData", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public object EnrichedData { get; set; } + [Newtonsoft.Json.JsonExtensionData] + public System.Collections.Generic.IDictionary AdditionalProperties + { + get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } + set { _additionalProperties = value; } + } - /// - /// Error message if transaction failed - /// - [Newtonsoft.Json.JsonProperty("errorMessage", Required = Newtonsoft.Json.Required.AllowNull)] - public string ErrorMessage { get; set; } + } + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class Transactions4 + { /// - /// Parameters used for transaction execution + /// Blockchain network identifier /// - [Newtonsoft.Json.JsonProperty("executionParams", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public object ExecutionParams { get; set; } + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } /// - /// Result data from transaction execution + /// Transaction recipient address /// - [Newtonsoft.Json.JsonProperty("executionResult", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public object ExecutionResult { get; set; } + [Newtonsoft.Json.JsonProperty("to", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string To { get; set; } /// - /// Sender wallet address + /// Transaction data payload /// - [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.AllowNull)] - public string From { get; set; } + [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Data { get; set; } /// - /// Unique transaction identifier + /// Type of action this transaction performs /// - [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("action", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Id { get; set; } + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public Transactions4Action Action { get; set; } /// - /// On-chain transaction hash once confirmed + /// Transaction sender address /// - [Newtonsoft.Json.JsonProperty("transactionHash", Required = Newtonsoft.Json.Required.AllowNull)] - public string TransactionHash { get; set; } + [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string From { get; set; } /// - /// Original transaction parameters and data + /// Spender address for approval transactions /// - [Newtonsoft.Json.JsonProperty("transactionParams", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public object TransactionParams { get; set; } + [Newtonsoft.Json.JsonProperty("spender", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Spender { get; set; } /// - /// Transaction status + /// Transaction value in wei /// - [Newtonsoft.Json.JsonProperty("status", Required = Newtonsoft.Json.Required.AllowNull)] - [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] - public Transactions2Status? Status { get; set; } + [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Value { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -8892,21 +13163,38 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Owners + public partial class OriginToken3 { /// - /// Owner wallet address + /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } + + /// + /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). /// [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] public string Address { get; set; } + [Newtonsoft.Json.JsonProperty("decimals", Required = Newtonsoft.Json.Required.Always)] + public double Decimals { get; set; } + + [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Symbol { get; set; } + + [Newtonsoft.Json.JsonProperty("iconUri", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string IconUri { get; set; } + /// - /// Token amount owned as a string + /// Token price in different FIAT currencies. /// - [Newtonsoft.Json.JsonProperty("amount", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Amount { get; set; } + [Newtonsoft.Json.JsonProperty("prices", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.IDictionary Prices { get; set; } = new System.Collections.Generic.Dictionary(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -8920,31 +13208,38 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Pagination11 + public partial class DestinationToken3 { /// - /// Whether there are more items available + /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). /// - [Newtonsoft.Json.JsonProperty("hasMore", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public bool HasMore { get; set; } + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } /// - /// Number of items per page + /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). /// - [Newtonsoft.Json.JsonProperty("limit", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? Limit { get; set; } = 20D; + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Address { get; set; } - /// - /// Current page number - /// - [Newtonsoft.Json.JsonProperty("page", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? Page { get; set; } = 1D; + [Newtonsoft.Json.JsonProperty("decimals", Required = Newtonsoft.Json.Required.Always)] + public double Decimals { get; set; } + + [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Symbol { get; set; } + + [Newtonsoft.Json.JsonProperty("iconUri", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string IconUri { get; set; } /// - /// Total number of items available + /// Token price in different FIAT currencies. /// - [Newtonsoft.Json.JsonProperty("totalCount", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double? TotalCount { get; set; } + [Newtonsoft.Json.JsonProperty("prices", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.IDictionary Prices { get; set; } = new System.Collections.Generic.Dictionary(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -8958,20 +13253,54 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public enum ActionsType + public partial class Transactions5 { + /// + /// Blockchain network identifier + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } - [System.Runtime.Serialization.EnumMember(Value = @"init")] - Init = 0, + /// + /// Transaction recipient address + /// + [Newtonsoft.Json.JsonProperty("to", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string To { get; set; } - } + /// + /// Transaction data payload + /// + [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Data { get; set; } - /// - /// Authentication provider details with type-based discrimination - /// - [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Profiles3 - { + /// + /// Type of action this transaction performs + /// + [Newtonsoft.Json.JsonProperty("action", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public Transactions5Action Action { get; set; } + + /// + /// Transaction sender address + /// + [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string From { get; set; } + + /// + /// Spender address for approval transactions + /// + [Newtonsoft.Json.JsonProperty("spender", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Spender { get; set; } + + /// + /// Transaction value in wei + /// + [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Value { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -8984,12 +13313,39 @@ public System.Collections.Generic.IDictionary AdditionalProperti } - /// - /// Authentication provider details with type-based discrimination - /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Profiles4 + public partial class OriginToken4 { + /// + /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). + /// + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } + + /// + /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). + /// + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Address { get; set; } + + [Newtonsoft.Json.JsonProperty("decimals", Required = Newtonsoft.Json.Required.Always)] + public double Decimals { get; set; } + + [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Symbol { get; set; } + + [Newtonsoft.Json.JsonProperty("iconUri", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string IconUri { get; set; } + + /// + /// Token price in different FIAT currencies. + /// + [Newtonsoft.Json.JsonProperty("prices", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.IDictionary Prices { get; set; } = new System.Collections.Generic.Dictionary(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -9003,28 +13359,38 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Decoded + public partial class DestinationToken4 { /// - /// Object containing decoded function parameters. + /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). /// - [Newtonsoft.Json.JsonProperty("inputs", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.Dictionary Inputs { get; set; } = new System.Collections.Generic.Dictionary(); + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } /// - /// The function name. + /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). /// - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Name { get; set; } + public string Address { get; set; } + + [Newtonsoft.Json.JsonProperty("decimals", Required = Newtonsoft.Json.Required.Always)] + public double Decimals { get; set; } + + [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Symbol { get; set; } + + [Newtonsoft.Json.JsonProperty("iconUri", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string IconUri { get; set; } /// - /// The function signature. + /// Token price in different FIAT currencies. /// - [Newtonsoft.Json.JsonProperty("signature", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Signature { get; set; } + [Newtonsoft.Json.JsonProperty("prices", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.IDictionary Prices { get; set; } = new System.Collections.Generic.Dictionary(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -9038,49 +13404,54 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Price_data + public partial class Transactions6 { /// - /// The circulating supply of the token + /// Blockchain network identifier /// - [Newtonsoft.Json.JsonProperty("circulating_supply", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double Circulating_supply { get; set; } + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } /// - /// The market cap of the token in USD + /// Transaction recipient address /// - [Newtonsoft.Json.JsonProperty("market_cap_usd", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double Market_cap_usd { get; set; } + [Newtonsoft.Json.JsonProperty("to", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string To { get; set; } /// - /// The percentage change of the token in the last 24 hours + /// Transaction data payload /// - [Newtonsoft.Json.JsonProperty("percent_change_24h", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double Percent_change_24h { get; set; } + [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Data { get; set; } /// - /// The timestamp of the latest price update + /// Type of action this transaction performs /// - [Newtonsoft.Json.JsonProperty("price_timestamp", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Price_timestamp { get; set; } + [Newtonsoft.Json.JsonProperty("action", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public Transactions6Action Action { get; set; } /// - /// The price of the token in USD + /// Transaction sender address /// - [Newtonsoft.Json.JsonProperty("price_usd", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double Price_usd { get; set; } + [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string From { get; set; } /// - /// The total supply of the token + /// Spender address for approval transactions /// - [Newtonsoft.Json.JsonProperty("total_supply", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double Total_supply { get; set; } + [Newtonsoft.Json.JsonProperty("spender", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Spender { get; set; } /// - /// The volume of the token in USD + /// Transaction value in wei /// - [Newtonsoft.Json.JsonProperty("volume_24h_usd", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double Volume_24h_usd { get; set; } + [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Value { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -9094,25 +13465,15 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Attributes + public partial class Eip712 { - /// - /// The display type - /// - [Newtonsoft.Json.JsonProperty("display_type", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Display_type { get; set; } - - /// - /// The trait type - /// - [Newtonsoft.Json.JsonProperty("trait_type", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Trait_type { get; set; } + [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Name { get; set; } - /// - /// The trait value - /// - [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public Value Value { get; set; } + [Newtonsoft.Json.JsonProperty("version", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Version { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -9126,31 +13487,38 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Collection + public partial class OriginToken5 { /// - /// The collection description + /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). /// - [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Description { get; set; } + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } /// - /// The collection external URL + /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). /// - [Newtonsoft.Json.JsonProperty("external_url", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string External_url { get; set; } + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Address { get; set; } - /// - /// The collection image URL - /// - [Newtonsoft.Json.JsonProperty("image", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Image { get; set; } + [Newtonsoft.Json.JsonProperty("decimals", Required = Newtonsoft.Json.Required.Always)] + public double Decimals { get; set; } + + [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Symbol { get; set; } + + [Newtonsoft.Json.JsonProperty("iconUri", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string IconUri { get; set; } /// - /// The collection name + /// Token price in different FIAT currencies. /// - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string Name { get; set; } + [Newtonsoft.Json.JsonProperty("prices", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.IDictionary Prices { get; set; } = new System.Collections.Generic.Dictionary(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -9164,28 +13532,38 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Decoded2 + public partial class DestinationToken5 { /// - /// Object containing decoded function parameters. + /// The blockchain network identifier. Common values include: 1 (Ethereum), 8453 (Base), 137 (Polygon), 56 (BSC), 43114 (Avalanche), 42161 (Arbitrum), 10 (Optimism). /// - [Newtonsoft.Json.JsonProperty("inputs", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.Dictionary Inputs { get; set; } = new System.Collections.Generic.Dictionary(); + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } /// - /// The function name. + /// A valid Ethereum address (0x-prefixed hex string) or ENS name (e.g., vitalik.eth). /// - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("address", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Name { get; set; } + public string Address { get; set; } + + [Newtonsoft.Json.JsonProperty("decimals", Required = Newtonsoft.Json.Required.Always)] + public double Decimals { get; set; } + + [Newtonsoft.Json.JsonProperty("symbol", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Symbol { get; set; } + + [Newtonsoft.Json.JsonProperty("iconUri", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string IconUri { get; set; } /// - /// The function signature. + /// Token price in different FIAT currencies. /// - [Newtonsoft.Json.JsonProperty("signature", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Signature { get; set; } + [Newtonsoft.Json.JsonProperty("prices", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required] + public System.Collections.Generic.IDictionary Prices { get; set; } = new System.Collections.Generic.Dictionary(); private System.Collections.Generic.IDictionary _additionalProperties; @@ -9199,28 +13577,54 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Decoded3 + public partial class Transactions7 { /// - /// The event name. + /// Blockchain network identifier /// - [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("chainId", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Range(1, int.MaxValue)] + public int ChainId { get; set; } + + /// + /// Transaction recipient address + /// + [Newtonsoft.Json.JsonProperty("to", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Name { get; set; } + public string To { get; set; } /// - /// Object containing decoded parameters. + /// Transaction data payload /// - [Newtonsoft.Json.JsonProperty("params", Required = Newtonsoft.Json.Required.Always)] - [System.ComponentModel.DataAnnotations.Required] - public System.Collections.Generic.Dictionary Params { get; set; } = new System.Collections.Generic.Dictionary(); + [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Always)] + [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] + public string Data { get; set; } /// - /// The event signature. + /// Type of action this transaction performs /// - [Newtonsoft.Json.JsonProperty("signature", Required = Newtonsoft.Json.Required.Always)] + [Newtonsoft.Json.JsonProperty("action", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] - public string Signature { get; set; } + [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] + public Transactions7Action Action { get; set; } + + /// + /// Transaction sender address + /// + [Newtonsoft.Json.JsonProperty("from", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string From { get; set; } + + /// + /// Spender address for approval transactions + /// + [Newtonsoft.Json.JsonProperty("spender", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Spender { get; set; } + + /// + /// Transaction value in wei + /// + [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public string Value { get; set; } private System.Collections.Generic.IDictionary _additionalProperties; @@ -9234,88 +13638,93 @@ public System.Collections.Generic.IDictionary AdditionalProperti } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Metadata + public enum Transactions4Action { - /// - /// Hash method used for bytecode metadata. - /// - [Newtonsoft.Json.JsonProperty("bytecodeHash", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public string BytecodeHash { get; set; } - private System.Collections.Generic.IDictionary _additionalProperties; + [System.Runtime.Serialization.EnumMember(Value = @"approval")] + Approval = 0, - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + [System.Runtime.Serialization.EnumMember(Value = @"transfer")] + Transfer = 1, + + [System.Runtime.Serialization.EnumMember(Value = @"buy")] + Buy = 2, + + [System.Runtime.Serialization.EnumMember(Value = @"sell")] + Sell = 3, + + [System.Runtime.Serialization.EnumMember(Value = @"fee")] + Fee = 4, } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Optimizer + public enum Transactions5Action { - /// - /// Whether optimizer is enabled. - /// - [Newtonsoft.Json.JsonProperty("enabled", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public bool Enabled { get; set; } - /// - /// Number of optimizer runs. - /// - [Newtonsoft.Json.JsonProperty("runs", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] - public double Runs { get; set; } + [System.Runtime.Serialization.EnumMember(Value = @"approval")] + Approval = 0, - private System.Collections.Generic.IDictionary _additionalProperties; + [System.Runtime.Serialization.EnumMember(Value = @"transfer")] + Transfer = 1, - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + [System.Runtime.Serialization.EnumMember(Value = @"buy")] + Buy = 2, + + [System.Runtime.Serialization.EnumMember(Value = @"sell")] + Sell = 3, + + [System.Runtime.Serialization.EnumMember(Value = @"fee")] + Fee = 4, } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public enum Transactions2Status + public enum Transactions6Action { - [System.Runtime.Serialization.EnumMember(Value = @"QUEUED")] - QUEUED = 0, + [System.Runtime.Serialization.EnumMember(Value = @"approval")] + Approval = 0, - [System.Runtime.Serialization.EnumMember(Value = @"SUBMITTED")] - SUBMITTED = 1, + [System.Runtime.Serialization.EnumMember(Value = @"transfer")] + Transfer = 1, - [System.Runtime.Serialization.EnumMember(Value = @"CONFIRMED")] - CONFIRMED = 2, + [System.Runtime.Serialization.EnumMember(Value = @"buy")] + Buy = 2, - [System.Runtime.Serialization.EnumMember(Value = @"FAILED")] - FAILED = 3, + [System.Runtime.Serialization.EnumMember(Value = @"sell")] + Sell = 3, + + [System.Runtime.Serialization.EnumMember(Value = @"fee")] + Fee = 4, } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class Value + public enum Transactions7Action { - private System.Collections.Generic.IDictionary _additionalProperties; + [System.Runtime.Serialization.EnumMember(Value = @"approval")] + Approval = 0, - [Newtonsoft.Json.JsonExtensionData] - public System.Collections.Generic.IDictionary AdditionalProperties - { - get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } - set { _additionalProperties = value; } - } + [System.Runtime.Serialization.EnumMember(Value = @"transfer")] + Transfer = 1, + + [System.Runtime.Serialization.EnumMember(Value = @"buy")] + Buy = 2, + + [System.Runtime.Serialization.EnumMember(Value = @"sell")] + Sell = 3, + + [System.Runtime.Serialization.EnumMember(Value = @"fee")] + Fee = 4, } [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class ThirdwebApiException : System.Exception + public partial class ApiException : System.Exception { public int StatusCode { get; private set; } @@ -9323,7 +13732,7 @@ public partial class ThirdwebApiException : System.Exception public System.Collections.Generic.IReadOnlyDictionary> Headers { get; private set; } - public ThirdwebApiException(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Exception innerException) + public ApiException(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary> headers, System.Exception innerException) : base(message + "\n\nStatus: " + statusCode + "\nResponse: \n" + ((response == null) ? "(null)" : response.Substring(0, response.Length >= 512 ? 512 : response.Length)), innerException) { StatusCode = statusCode; @@ -9338,11 +13747,11 @@ public override string ToString() } [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.4.0.0 (NJsonSchema v11.3.2.0 (Newtonsoft.Json v13.0.0.0))")] - public partial class ThirdwebApiException : ThirdwebApiException + public partial class ApiException : ApiException { public TResult Result { get; private set; } - public ThirdwebApiException(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary> headers, TResult result, System.Exception innerException) + public ApiException(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary> headers, TResult result, System.Exception innerException) : base(message, statusCode, response, headers, innerException) { Result = result; diff --git a/Thirdweb/Thirdweb.Api/ThirdwebHttpClientWrapper.cs b/Thirdweb/Thirdweb.Api/ThirdwebHttpClientWrapper.cs index 3fe8d91b..6b8b2ccc 100644 --- a/Thirdweb/Thirdweb.Api/ThirdwebHttpClientWrapper.cs +++ b/Thirdweb/Thirdweb.Api/ThirdwebHttpClientWrapper.cs @@ -3,7 +3,7 @@ namespace Thirdweb.Api; /// /// Wrapper class that adapts IThirdwebHttpClient to work with System.Net.Http.HttpClient expectations /// -internal class ThirdwebHttpClientWrapper : HttpClient +public class ThirdwebHttpClientWrapper : HttpClient { private readonly IThirdwebHttpClient _thirdwebClient; diff --git a/Thirdweb/Thirdweb.Bridge/ThirdwebBridge.Extensions.cs b/Thirdweb/Thirdweb.Bridge/ThirdwebBridge.Extensions.cs deleted file mode 100644 index aa231a8b..00000000 --- a/Thirdweb/Thirdweb.Bridge/ThirdwebBridge.Extensions.cs +++ /dev/null @@ -1,151 +0,0 @@ -using System.Numerics; - -namespace Thirdweb.Bridge; - -public static class ThirdwebBridgeExtensions -{ - #region Execution - - /// - /// Executes buy transaction(s) and handles status polling. - /// - /// The Thirdweb bridge. - /// The executor wallet. - /// The buy data. - /// The cancellation token. - /// The transaction receipts as a list of . - public static async Task> Execute(this ThirdwebBridge bridge, IThirdwebWallet executor, BuyPrepareData preparedBuy, CancellationToken cancellationToken = default) - { - return await ExecuteInternal(bridge, executor, preparedBuy.Steps, cancellationToken); - } - - /// - /// Executes sell transaction(s) and handles status polling. - /// - /// The Thirdweb bridge. - /// The executor wallet. - /// The prepared sell data. - /// The cancellation token. - /// The transaction receipts as a list of . - public static async Task> Execute( - this ThirdwebBridge bridge, - IThirdwebWallet executor, - SellPrepareData preparedSell, - CancellationToken cancellationToken = default - ) - { - return await ExecuteInternal(bridge, executor, preparedSell.Steps, cancellationToken); - } - - /// - /// Executes a transfer transaction and handles status polling. - /// - /// The Thirdweb bridge. - /// The executor wallet. - /// The prepared transfer data. - /// The cancellation token. - /// The transaction receipts as a list of . - public static Task> Execute( - this ThirdwebBridge bridge, - IThirdwebWallet executor, - TransferPrepareData preparedTransfer, - CancellationToken cancellationToken = default - ) - { - var steps = new List() { new() { Transactions = preparedTransfer.Transactions } }; - return ExecuteInternal(bridge, executor, steps, cancellationToken); - } - - /// - /// Executes a set of post-onramp transactions and handles status polling. - /// - /// The Thirdweb bridge. - /// The executor wallet. - /// The prepared onramp data. - /// The cancellation token. - /// The transaction receipts as a list of . - /// Note: This method is used for executing transactions after an onramp process. - public static Task> Execute(this ThirdwebBridge bridge, IThirdwebWallet executor, OnrampPrepareData preparedOnRamp, CancellationToken cancellationToken = default) - { - return ExecuteInternal(bridge, executor, preparedOnRamp.Steps, cancellationToken); - } - - /// - /// Executes a set of transactions and handles status polling. - /// - /// /// The Thirdweb bridge. - /// The executor wallet. - /// The steps containing transactions to execute. - /// The cancellation token. - public static Task> Execute(this ThirdwebBridge bridge, IThirdwebWallet executor, List steps, CancellationToken cancellationToken = default) - { - return ExecuteInternal(bridge, executor, steps, cancellationToken); - } - - private static async Task> ExecuteInternal(this ThirdwebBridge bridge, IThirdwebWallet executor, List steps, CancellationToken cancellationToken = default) - { - var receipts = new List(); - foreach (var step in steps) - { - foreach (var tx in step.Transactions) - { - var thirdwebTx = await tx.ToThirdwebTransaction(executor); - var hash = await ThirdwebTransaction.Send(thirdwebTx); - receipts.Add(await ThirdwebTransaction.WaitForTransactionReceipt(executor.Client, tx.ChainId, hash, cancellationToken)); - _ = await bridge.WaitForStatusCompletion(hash, tx.ChainId, cancellationToken); - } - } - return receipts; - } - - #endregion - - #region Helpers - - public static async Task ToThirdwebTransaction(this Transaction transaction, IThirdwebWallet executor) - { - return await ThirdwebTransaction.Create( - executor, - new ThirdwebTransactionInput( - chainId: transaction.ChainId, - to: transaction.To, - value: BigInteger.Parse(string.IsNullOrEmpty(transaction.Value) ? "0" : transaction.Value), - data: string.IsNullOrEmpty(transaction.Data) ? "0x" : transaction.Data - ) - ); - } - - public static async Task WaitForStatusCompletion(this ThirdwebBridge bridge, string hash, BigInteger chainId, CancellationToken cancellationToken = default) - { - if (string.IsNullOrEmpty(hash)) - { - throw new ArgumentNullException(nameof(hash)); - } - - if (chainId == 0) - { - throw new ArgumentNullException(nameof(chainId)); - } - - var status = await bridge.Status(hash, chainId); - while (status.StatusType is StatusType.PENDING or StatusType.NOT_FOUND) - { - await ThirdwebTask.Delay(500, cancellationToken); - status = await bridge.Status(hash, chainId); - } - - if (status.StatusType is StatusType.FAILED) - { - throw new Exception($"Transaction with hash {hash} failed."); - } - - return status; - } - - public static bool IsSwapRequiredPostOnramp(this OnrampPrepareData preparedOnramp) - { - return preparedOnramp.Steps == null || preparedOnramp.Steps.Count == 0 || !preparedOnramp.Steps.Any(step => step.Transactions?.Count > 0); - } - - #endregion -} diff --git a/Thirdweb/Thirdweb.Bridge/ThirdwebBridge.Types.cs b/Thirdweb/Thirdweb.Bridge/ThirdwebBridge.Types.cs deleted file mode 100644 index 9bfeb4da..00000000 --- a/Thirdweb/Thirdweb.Bridge/ThirdwebBridge.Types.cs +++ /dev/null @@ -1,598 +0,0 @@ -using System.Numerics; -using Newtonsoft.Json; - -namespace Thirdweb.Bridge; - -/// -/// Represents the response model wrapping the result of an API call. -/// -/// The type of the result. -internal class ResponseModel -{ - /// - /// The result returned by the API. - /// - [JsonProperty("data")] - internal T Data { get; set; } -} - -#region Common Types - -/// -/// Represents the base intent object for different types of transactions. -/// -public class Intent -{ - /// - /// The origin chain ID. - /// - [JsonProperty("originChainId")] - public BigInteger OriginChainId { get; set; } - - /// - /// The origin token address. - /// - [JsonProperty("originTokenAddress")] - public string OriginTokenAddress { get; set; } - - /// - /// The destination chain ID. - /// - [JsonProperty("destinationChainId")] - public BigInteger DestinationChainId { get; set; } - - /// - /// The destination token address. - /// - [JsonProperty("destinationTokenAddress")] - public string DestinationTokenAddress { get; set; } - - /// - /// The desired amount in wei. - /// - [JsonProperty("amount")] - public string Amount { get; set; } - - /// - /// The maximum number of steps in the returned route (optional). - /// - [JsonProperty("maxSteps", NullValueHandling = NullValueHandling.Ignore)] - public int? MaxSteps { get; set; } = 3; -} - -/// -/// Represents the common fields for both Buy and Sell transactions. -/// -public class QuoteData -{ - /// - /// The amount (in wei) of the input token that must be paid to receive the desired amount. - /// - [JsonProperty("originAmount")] - public string OriginAmount { get; set; } - - /// - /// The amount (in wei) of the output token to be received by the receiver address. - /// - [JsonProperty("destinationAmount")] - public string DestinationAmount { get; set; } - - /// - /// The timestamp when the quote was generated. - /// - [JsonProperty("timestamp")] - public long Timestamp { get; set; } - - /// - /// The block number when the quote was generated. - /// - [JsonProperty("blockNumber")] - public string BlockNumber { get; set; } - - /// - /// The estimated execution time in milliseconds for filling the quote. - /// - [JsonProperty("estimatedExecutionTimeMs")] - public long EstimatedExecutionTimeMs { get; set; } - - /// - /// The intent object containing details about the transaction. - /// - [JsonProperty("intent")] - public Intent Intent { get; set; } - - [JsonProperty("steps")] - public List Steps { get; set; } - - [JsonProperty("purchaseData", NullValueHandling = NullValueHandling.Ignore)] - public object PurchaseData { get; set; } -} - -/// -/// Represents a single step in a transaction, including origin and destination tokens. -/// -public class Step -{ - [JsonProperty("originToken")] - public TokenData OriginToken { get; set; } - - [JsonProperty("destinationToken")] - public TokenData DestinationToken { get; set; } - - [JsonProperty("transactions")] - public List Transactions { get; set; } - - [JsonProperty("originAmount")] - public string OriginAmount { get; set; } - - [JsonProperty("destinationAmount")] - public string DestinationAmount { get; set; } - - [JsonProperty("nativeFee")] - public string NativeFee { get; set; } - - [JsonProperty("estimatedExecutionTimeMs")] - public long EstimatedExecutionTimeMs { get; set; } -} - -/// -/// Represents a token in a step, including metadata like chain ID, address, and pricing. -/// -public class TokenData -{ - [JsonProperty("chainId")] - public BigInteger ChainId { get; set; } - - [JsonProperty("address")] - public string Address { get; set; } - - [JsonProperty("symbol")] - public string Symbol { get; set; } - - [JsonProperty("name")] - public string Name { get; set; } - - [JsonProperty("decimals")] - public int Decimals { get; set; } - - [JsonProperty("priceUsd")] - public decimal PriceUsd { get; set; } - - [JsonProperty("iconUri")] - public string IconUri { get; set; } -} - -/// -/// Represents a transaction ready to be executed. -/// -public class Transaction -{ - /// - /// The transaction ID, each step in a quoted payment will have a unique transaction ID. - /// - [JsonProperty("id")] - public string Id { get; set; } - - /// - /// The chain ID where the transaction will take place. - /// - [JsonProperty("chainId")] - public BigInteger ChainId { get; set; } - - /// - /// The maximum priority fee per gas (EIP-1559). - /// - [JsonProperty("maxPriorityFeePerGas", NullValueHandling = NullValueHandling.Ignore)] - public string MaxPriorityFeePerGas { get; set; } - - /// - /// The maximum fee per gas (EIP-1559). - /// - [JsonProperty("maxFeePerGas", NullValueHandling = NullValueHandling.Ignore)] - public string MaxFeePerGas { get; set; } - - /// - /// The address to which the transaction is sent. - /// - [JsonProperty("to")] - public string To { get; set; } - - /// - /// The address from which the transaction is sent, or null if not applicable. - /// - [JsonProperty("from", NullValueHandling = NullValueHandling.Ignore)] - public string From { get; set; } - - /// - /// The value (amount) to be sent in the transaction. - /// - [JsonProperty("value", NullValueHandling = NullValueHandling.Ignore)] - public string Value { get; set; } - - /// - /// The gas limit for the transaction. - /// - [JsonProperty("gas", NullValueHandling = NullValueHandling.Ignore)] - public string Gas { get; set; } - - /// - /// The transaction data. - /// - [JsonProperty("data")] - public string Data { get; set; } - - /// - /// The type of the transaction (e.g., "eip1559"). - /// - [JsonProperty("type")] - public string Type { get; set; } - - /// - /// The action type for the transaction (e.g., "approval", "transfer", "buy", "sell"). - /// - [JsonProperty("action")] - public string Action { get; set; } -} - -#endregion - -#region Buy - -/// -/// Represents the data returned in the buy quote response. -/// -public class BuyQuoteData : QuoteData { } - -/// -/// Represents the data returned in the buy prepare response. -/// -public class BuyPrepareData : QuoteData -{ - /// - /// A hex ID associated with the quoted payment. - /// - [JsonProperty("id")] - public string Id { get; set; } - - /// - /// An array of transactions to be executed to fulfill this quote (in order). - /// - [Obsolete("Use Steps.Transactions instead.")] - [JsonProperty("transactions")] - public List Transactions { get; set; } - - /// - /// The expiration timestamp for this prepared quote and its transactions (if applicable). - /// - [JsonProperty("expiration")] - public long? Expiration { get; set; } -} - -#endregion - -#region Sell - -/// -/// Represents the data returned in the sell quote response. -/// -public class SellQuoteData : QuoteData { } - -/// -/// Represents the data returned in the sell prepare response. -/// -public class SellPrepareData : QuoteData -{ - /// - /// A hex ID associated with the quoted payment. - /// - [JsonProperty("id")] - public string Id { get; set; } - - /// - /// An array of transactions to be executed to fulfill this quote (in order). - /// - [Obsolete("Use Steps.Transactions instead.")] - [JsonProperty("transactions")] - public List Transactions { get; set; } - - /// - /// The expiration timestamp for this prepared quote and its transactions (if applicable). - /// - [JsonProperty("expiration")] - public long? Expiration { get; set; } -} - -#endregion - -#region Transfer - -/// -/// Represents the data returned in the transfer prepare response. -/// -public class TransferPrepareData -{ - [JsonProperty("originAmount")] - public string OriginAmount { get; set; } - - [JsonProperty("destinationAmount")] - public string DestinationAmount { get; set; } - - [JsonProperty("timestamp")] - public long Timestamp { get; set; } - - [JsonProperty("blockNumber")] - public string BlockNumber { get; set; } - - [JsonProperty("estimatedExecutionTimeMs")] - public long EstimatedExecutionTimeMs { get; set; } - - [JsonProperty("id")] - public string Id { get; set; } - - [JsonProperty("transactions")] - public List Transactions { get; set; } - - [JsonProperty("expiration")] - public long? Expiration { get; set; } - - [JsonProperty("intent")] - public TransferIntent Intent { get; set; } -} - -/// -/// Represents the intent object for the transfer prepare response. -/// -public class TransferIntent -{ - [JsonProperty("chainId")] - public BigInteger ChainId { get; set; } - - [JsonProperty("tokenAddress")] - public string TokenAddress { get; set; } - - [JsonProperty("transferAmountWei")] - public string TransferAmountWei { get; set; } - - [JsonProperty("sender")] - public string Sender { get; set; } - - [JsonProperty("receiver")] - public string Receiver { get; set; } - - [JsonProperty("feePayer")] - public string FeePayer { get; set; } = "sender"; - - [JsonProperty("purchaseData", NullValueHandling = NullValueHandling.Ignore)] - public object PurchaseData { get; set; } -} - -#endregion - -#region Status - -/// -/// Represents the possible statuses for a transaction. -/// -public enum StatusType -{ - FAILED, - PENDING, - COMPLETED, - NOT_FOUND, - PROCESSING, - CREATED, - UNKNOWN, -} - -/// -/// Represents the data returned in the status response. -/// -public class StatusData -{ - /// - /// The status of the transaction (as StatusType enum). - /// - [JsonIgnore] - public StatusType StatusType => - this.Status switch - { - "FAILED" => StatusType.FAILED, - "PENDING" => StatusType.PENDING, - "COMPLETED" => StatusType.COMPLETED, - "NOT_FOUND" => StatusType.NOT_FOUND, - _ => StatusType.UNKNOWN, - }; - - /// - /// The status of the transaction. - /// - [JsonProperty("status")] - public string Status { get; set; } - - /// - /// A list of transactions involved in this status. - /// - [JsonProperty("transactions")] - public List Transactions { get; set; } - - /// - /// The unique payment ID for the transaction. - /// - [JsonProperty("paymentId", NullValueHandling = NullValueHandling.Ignore)] - public string PaymentId { get; set; } - - /// - /// The unique transaction ID for the transaction. - /// - [JsonProperty("transactionId", NullValueHandling = NullValueHandling.Ignore)] - public string TransactionId { get; set; } - - /// - /// The origin chain ID (for PENDING and COMPLETED statuses). - /// - [JsonProperty("originChainId", NullValueHandling = NullValueHandling.Ignore)] - public BigInteger? OriginChainId { get; set; } - - /// - /// The origin token address (for PENDING and COMPLETED statuses). - /// - [JsonProperty("originTokenAddress", NullValueHandling = NullValueHandling.Ignore)] - public string OriginTokenAddress { get; set; } - - /// - /// The destination chain ID (for PENDING and COMPLETED statuses). - /// - [JsonProperty("destinationChainId", NullValueHandling = NullValueHandling.Ignore)] - public BigInteger? DestinationChainId { get; set; } - - /// - /// The destination token address (for PENDING and COMPLETED statuses). - /// - [JsonProperty("destinationTokenAddress", NullValueHandling = NullValueHandling.Ignore)] - public string DestinationTokenAddress { get; set; } - - /// - /// The origin token amount in wei (for PENDING and COMPLETED statuses). - /// - [JsonProperty("originAmount", NullValueHandling = NullValueHandling.Ignore)] - public string OriginAmount { get; set; } - - /// - /// The destination token amount in wei (for COMPLETED status). - /// - [JsonProperty("destinationAmount", NullValueHandling = NullValueHandling.Ignore)] - public string DestinationAmount { get; set; } - - /// - /// The purchase data, which can be null. - /// - [JsonProperty("purchaseData", NullValueHandling = NullValueHandling.Ignore)] - public object PurchaseData { get; set; } -} - -/// -/// Represents the transaction details for a specific status. -/// -public class TransactionStatus -{ - /// - /// The chain ID where the transaction took place. - /// - [JsonProperty("chainId")] - public BigInteger ChainId { get; set; } - - /// - /// The transaction hash of the transaction. - /// - [JsonProperty("transactionHash")] - public string TransactionHash { get; set; } -} - -#endregion - -#region Onramp - -public enum OnrampProvider -{ - Stripe, - Coinbase, - Transak, -} - -/// -/// Represents the core data of an onramp response. -/// -public class OnrampPrepareData -{ - [JsonProperty("id")] - public string Id { get; set; } - - [JsonProperty("link")] - public string Link { get; set; } - - [JsonProperty("currency")] - public string Currency { get; set; } - - [JsonProperty("currencyAmount")] - public decimal CurrencyAmount { get; set; } - - [JsonProperty("destinationAmount")] - public string DestinationAmount { get; set; } - - [JsonProperty("timestamp", NullValueHandling = NullValueHandling.Ignore)] - public long? Timestamp { get; set; } - - [JsonProperty("expiration", NullValueHandling = NullValueHandling.Ignore)] - public long? Expiration { get; set; } - - [JsonProperty("steps")] - public List Steps { get; set; } - - [JsonProperty("intent")] - public OnrampIntent Intent { get; set; } -} - -/// -/// Represents the intent used to prepare the onramp. -/// -public class OnrampIntent -{ - [JsonProperty("onramp")] - public OnrampProvider Onramp { get; set; } - - [JsonProperty("chainId")] - public BigInteger ChainId { get; set; } - - [JsonProperty("tokenAddress")] - public string TokenAddress { get; set; } - - [JsonProperty("amount")] - public string Amount { get; set; } - - [JsonProperty("receiver")] - public string Receiver { get; set; } - - [JsonProperty("purchaseData", NullValueHandling = NullValueHandling.Ignore)] - public Dictionary PurchaseData { get; set; } - - [JsonProperty("onrampTokenAddress", NullValueHandling = NullValueHandling.Ignore)] - public string OnrampTokenAddress { get; set; } - - [JsonProperty("onrampChainId", NullValueHandling = NullValueHandling.Ignore)] - public BigInteger? OnrampChainId { get; set; } - - [JsonProperty("currency", NullValueHandling = NullValueHandling.Ignore)] - public string Currency { get; set; } = "USD"; - - [JsonProperty("maxSteps", NullValueHandling = NullValueHandling.Ignore)] - public int? MaxSteps { get; set; } = 3; - - [JsonProperty("excludeChainIds", NullValueHandling = NullValueHandling.Ignore)] - public List ExcludeChainIds { get; set; } -} - -/// -/// Represents the status of an onramp transaction. -/// -public class OnrampStatusData -{ - [JsonIgnore] - public StatusType StatusType => - this.Status switch - { - "FAILED" => StatusType.FAILED, - "PENDING" => StatusType.PENDING, - "COMPLETED" => StatusType.COMPLETED, - "PROCESSING" => StatusType.PROCESSING, - "CREATED" => StatusType.CREATED, - _ => StatusType.UNKNOWN, - }; - - [JsonProperty("status")] - public string Status { get; set; } - - [JsonProperty("transactionHash")] - public string TransactionHash { get; set; } -} - -#endregion diff --git a/Thirdweb/Thirdweb.Bridge/ThirdwebBridge.cs b/Thirdweb/Thirdweb.Bridge/ThirdwebBridge.cs deleted file mode 100644 index 00960be2..00000000 --- a/Thirdweb/Thirdweb.Bridge/ThirdwebBridge.cs +++ /dev/null @@ -1,527 +0,0 @@ -using System.Numerics; -using System.Text; -using Newtonsoft.Json; - -namespace Thirdweb.Bridge; - -public class ThirdwebBridge -{ - private readonly IThirdwebHttpClient _httpClient; - - internal ThirdwebBridge(ThirdwebClient client) - { - this._httpClient = client.HttpClient; - } - - /// - /// Create a new instance of the ThirdwebBridge class. - /// - /// The ThirdwebClient instance. - /// A new instance of . - public static Task Create(ThirdwebClient client) - { - return Task.FromResult(new ThirdwebBridge(client)); - } - - #region Buy - - /// - /// Get a quote for buying a specific amount of tokens on any chain. - /// - /// The chain ID of the origin chain. - /// The address of the token on the origin chain. - /// The chain ID of the destination chain. - /// The address of the token on the destination chain. - /// The amount of tokens to buy in wei. - /// The maximum number of steps in the returned route. - /// A object representing the quote. - /// Thrown when one of the parameters is invalid. - public async Task Buy_Quote( - BigInteger originChainId, - string originTokenAddress, - BigInteger destinationChainId, - string destinationTokenAddress, - BigInteger buyAmountWei, - int maxSteps = 3 - ) - { - if (originChainId <= 0) - { - throw new ArgumentException("originChainId cannot be less than or equal to 0", nameof(originChainId)); - } - - if (destinationChainId <= 0) - { - throw new ArgumentException("destinationChainId cannot be less than or equal to 0", nameof(destinationChainId)); - } - - if (!Utils.IsValidAddress(originTokenAddress)) - { - throw new ArgumentException("originTokenAddress is not a valid address", nameof(originTokenAddress)); - } - - if (buyAmountWei <= 0) - { - throw new ArgumentException("buyAmountWei cannot be less than or equal to 0", nameof(buyAmountWei)); - } - - var url = $"{Constants.BRIDGE_API_URL}/v1/buy/quote"; - var queryParams = new Dictionary - { - { "originChainId", originChainId.ToString() }, - { "originTokenAddress", originTokenAddress }, - { "destinationChainId", destinationChainId.ToString() }, - { "destinationTokenAddress", destinationTokenAddress }, - { "buyAmountWei", buyAmountWei.ToString() }, - { "maxSteps", maxSteps.ToString() }, - }; - url = AppendQueryParams(url, queryParams); - - var response = await this._httpClient.GetAsync(url).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - var result = JsonConvert.DeserializeObject>(responseContent); - return result.Data; - } - - /// - /// Get the transactions required to buy a specific amount of tokens on any chain, alongside the quote. - /// - /// The chain ID of the origin chain. - /// The address of the token on the origin chain. - /// The chain ID of the destination chain. - /// The address of the token on the destination chain. - /// The amount of tokens to buy in wei. - /// The address of the sender. - /// The address of the receiver. - /// The maximum number of steps in the returned route. - /// Arbitrary purchase data to be included with the payment and returned with all webhooks and status checks. - /// A object representing the prepare data. - /// Thrown when one of the parameters is invalid. - public async Task Buy_Prepare( - BigInteger originChainId, - string originTokenAddress, - BigInteger destinationChainId, - string destinationTokenAddress, - BigInteger buyAmountWei, - string sender, - string receiver, - int maxSteps = 3, - object purchaseData = null - ) - { - if (originChainId <= 0) - { - throw new ArgumentException("originChainId cannot be less than or equal to 0", nameof(originChainId)); - } - - if (destinationChainId <= 0) - { - throw new ArgumentException("destinationChainId cannot be less than or equal to 0", nameof(destinationChainId)); - } - - if (!Utils.IsValidAddress(originTokenAddress)) - { - throw new ArgumentException("originTokenAddress is not a valid address", nameof(originTokenAddress)); - } - - if (buyAmountWei <= 0) - { - throw new ArgumentException("buyAmountWei cannot be less than or equal to 0", nameof(buyAmountWei)); - } - - if (!Utils.IsValidAddress(sender)) - { - throw new ArgumentException("sender is not a valid address", nameof(sender)); - } - - if (!Utils.IsValidAddress(receiver)) - { - throw new ArgumentException("receiver is not a valid address", nameof(receiver)); - } - - var requestBody = new - { - originChainId = originChainId.ToString(), - originTokenAddress, - destinationChainId = destinationChainId.ToString(), - destinationTokenAddress, - buyAmountWei = buyAmountWei.ToString(), - sender, - receiver, - maxSteps, - purchaseData, - }; - - var url = $"{Constants.BRIDGE_API_URL}/v1/buy/prepare"; - - var jsonBody = JsonConvert.SerializeObject(requestBody, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); - - var content = new StringContent(jsonBody, Encoding.UTF8, "application/json"); - var response = await this._httpClient.PostAsync(url, content).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - - var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - var result = JsonConvert.DeserializeObject>(responseContent); - - return result.Data; - } - - #endregion - - #region Sell - - /// - /// Get a quote for selling a specific amount of tokens on any chain. - /// - /// The chain ID of the origin chain. - /// The address of the token on the origin chain. - /// The chain ID of the destination chain. - /// The address of the token on the destination chain. - /// The amount of tokens to sell in wei. - /// The maximum number of steps in the returned route. - /// A object representing the quote. - /// Thrown when one of the parameters is invalid. - public async Task Sell_Quote( - BigInteger originChainId, - string originTokenAddress, - BigInteger destinationChainId, - string destinationTokenAddress, - BigInteger sellAmountWei, - int maxSteps = 3 - ) - { - if (originChainId <= 0) - { - throw new ArgumentException("originChainId cannot be less than or equal to 0", nameof(originChainId)); - } - - if (destinationChainId <= 0) - { - throw new ArgumentException("destinationChainId cannot be less than or equal to 0", nameof(destinationChainId)); - } - - if (!Utils.IsValidAddress(originTokenAddress)) - { - throw new ArgumentException("originTokenAddress is not a valid address", nameof(originTokenAddress)); - } - - if (sellAmountWei <= 0) - { - throw new ArgumentException("sellAmountWei cannot be less than or equal to 0", nameof(sellAmountWei)); - } - - var url = $"{Constants.BRIDGE_API_URL}/v1/sell/quote"; - var queryParams = new Dictionary - { - { "originChainId", originChainId.ToString() }, - { "originTokenAddress", originTokenAddress }, - { "destinationChainId", destinationChainId.ToString() }, - { "destinationTokenAddress", destinationTokenAddress }, - { "sellAmountWei", sellAmountWei.ToString() }, - { "maxSteps", maxSteps.ToString() }, - }; - url = AppendQueryParams(url, queryParams); - - var response = await this._httpClient.GetAsync(url).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - var result = JsonConvert.DeserializeObject>(responseContent); - return result.Data; - } - - /// - /// Get the transactions required to sell a specific amount of tokens on any chain, alongside the quote. - /// - /// The chain ID of the origin chain. - /// The address of the token on the origin chain. - /// The chain ID of the destination chain. - /// The address of the token on the destination chain. - /// The amount of tokens to sell in wei. - /// The address of the sender. - /// The address of the receiver. - /// The maximum number of steps in the returned route. - /// Arbitrary purchase data to be included with the payment and returned with all webhooks and status checks. - /// A object representing the prepare data. - /// Thrown when one of the parameters is invalid. - public async Task Sell_Prepare( - BigInteger originChainId, - string originTokenAddress, - BigInteger destinationChainId, - string destinationTokenAddress, - BigInteger sellAmountWei, - string sender, - string receiver, - int maxSteps = 3, - object purchaseData = null - ) - { - if (originChainId <= 0) - { - throw new ArgumentException("originChainId cannot be less than or equal to 0", nameof(originChainId)); - } - - if (destinationChainId <= 0) - { - throw new ArgumentException("destinationChainId cannot be less than or equal to 0", nameof(destinationChainId)); - } - - if (!Utils.IsValidAddress(originTokenAddress)) - { - throw new ArgumentException("originTokenAddress is not a valid address", nameof(originTokenAddress)); - } - - if (sellAmountWei <= 0) - { - throw new ArgumentException("sellAmountWei cannot be less than or equal to 0", nameof(sellAmountWei)); - } - - if (!Utils.IsValidAddress(sender)) - { - throw new ArgumentException("sender is not a valid address", nameof(sender)); - } - - if (!Utils.IsValidAddress(receiver)) - { - throw new ArgumentException("receiver is not a valid address", nameof(receiver)); - } - - var requestBody = new - { - originChainId = originChainId.ToString(), - originTokenAddress, - destinationChainId = destinationChainId.ToString(), - destinationTokenAddress, - sellAmountWei = sellAmountWei.ToString(), - sender, - receiver, - maxSteps, - purchaseData, - }; - - var url = $"{Constants.BRIDGE_API_URL}/v1/sell/prepare"; - - var jsonBody = JsonConvert.SerializeObject(requestBody, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); - - var content = new StringContent(jsonBody, Encoding.UTF8, "application/json"); - var response = await this._httpClient.PostAsync(url, content).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - - var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - var result = JsonConvert.DeserializeObject>(responseContent); - - return result.Data; - } - - #endregion - - #region Transfer - - /// - /// Get the transactions required to transfer a specific amount of tokens on any chain. - /// - /// The chain ID of the token. - /// The address of the token. - /// The amount of tokens to transfer in wei. - /// The address of the sender. - /// The address of the receiver. - /// The fee payer (default is "sender"). - /// Arbitrary purchase data to be included with the payment and returned with all webhooks and status checks. - /// A object representing the prepare data. - /// Thrown when one of the parameters is invalid. - public async Task Transfer_Prepare( - BigInteger chainId, - string tokenAddress, - BigInteger transferAmountWei, - string sender, - string receiver, - string feePayer = "sender", - object purchaseData = null - ) - { - if (chainId <= 0) - { - throw new ArgumentException("chainId cannot be less than or equal to 0", nameof(chainId)); - } - - if (!Utils.IsValidAddress(tokenAddress)) - { - throw new ArgumentException("tokenAddress is not a valid address", nameof(tokenAddress)); - } - - if (transferAmountWei <= 0) - { - throw new ArgumentException("transferAmountWei cannot be less than or equal to 0", nameof(transferAmountWei)); - } - - if (!Utils.IsValidAddress(sender)) - { - throw new ArgumentException("sender is not a valid address", nameof(sender)); - } - - if (!Utils.IsValidAddress(receiver)) - { - throw new ArgumentException("receiver is not a valid address", nameof(receiver)); - } - - var requestBody = new - { - chainId = chainId.ToString(), - tokenAddress, - transferAmountWei = transferAmountWei.ToString(), - sender, - receiver, - feePayer, - purchaseData, - }; - - var url = $"{Constants.BRIDGE_API_URL}/v1/transfer/prepare"; - - var jsonBody = JsonConvert.SerializeObject(requestBody, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); - - var content = new StringContent(jsonBody, Encoding.UTF8, "application/json"); - var response = await this._httpClient.PostAsync(url, content).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - - var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - var result = JsonConvert.DeserializeObject>(responseContent); - - return result.Data; - } - - #endregion - - #region Onramp - - public async Task Onramp_Prepare( - OnrampProvider onramp, - BigInteger chainId, - string tokenAddress, - string amount, - string receiver, - string onrampTokenAddress = null, - BigInteger? onrampChainId = null, - string currency = "USD", - int? maxSteps = 3, - List excludeChainIds = null, - object purchaseData = null - ) - { - if (chainId <= 0) - { - throw new ArgumentException("chainId cannot be less than or equal to 0", nameof(chainId)); - } - - if (!Utils.IsValidAddress(tokenAddress)) - { - throw new ArgumentException("tokenAddress is not a valid address", nameof(tokenAddress)); - } - - if (string.IsNullOrWhiteSpace(amount)) - { - throw new ArgumentException("amount cannot be null or empty", nameof(amount)); - } - - if (!Utils.IsValidAddress(receiver)) - { - throw new ArgumentException("receiver is not a valid address", nameof(receiver)); - } - - var requestBody = new - { - onramp = onramp.ToString().ToLower(), - chainId = chainId.ToString(), - tokenAddress, - amount, - receiver, - onrampTokenAddress, - onrampChainId = onrampChainId?.ToString(), - currency, - maxSteps, - excludeChainIds = excludeChainIds != null && excludeChainIds.Count > 0 ? excludeChainIds.Select(id => id.ToString()).ToList() : null, - purchaseData, - }; - - var url = $"{Constants.BRIDGE_API_URL}/v1/onramp/prepare"; - - var jsonBody = JsonConvert.SerializeObject(requestBody, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); - - var content = new StringContent(jsonBody, Encoding.UTF8, "application/json"); - var response = await this._httpClient.PostAsync(url, content).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - - var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - var result = JsonConvert.DeserializeObject>(responseContent); - - return result.Data; - } - - public async Task Onramp_Status(string id) - { - if (string.IsNullOrWhiteSpace(id)) - { - throw new ArgumentException("id cannot be null or empty", nameof(id)); - } - - var url = $"{Constants.BRIDGE_API_URL}/v1/onramp/status"; - var queryParams = new Dictionary { { "id", id } }; - url = AppendQueryParams(url, queryParams); - - var response = await this._httpClient.GetAsync(url).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - var result = JsonConvert.DeserializeObject>(responseContent); - return result.Data; - } - - #endregion - - #region Status - - /// - /// Get the status of any bridge-initiated transaction. - /// - /// The hash of the transaction. - /// The chain ID of the transaction. - /// A object representing the status. - /// Thrown when one of the parameters is invalid. - public async Task Status(string transactionHash, BigInteger chainId) - { - if (string.IsNullOrWhiteSpace(transactionHash)) - { - throw new ArgumentException("transactionHash cannot be null or empty", nameof(transactionHash)); - } - - if (chainId <= 0) - { - throw new ArgumentException("chainId cannot be less than or equal to 0", nameof(chainId)); - } - - var url = $"{Constants.BRIDGE_API_URL}/v1/status"; - var queryParams = new Dictionary { { "transactionHash", transactionHash }, { "chainId", chainId.ToString() } }; - url = AppendQueryParams(url, queryParams); - - var response = await this._httpClient.GetAsync(url).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - var result = JsonConvert.DeserializeObject>(responseContent); - return result.Data; - } - - #endregion - - private static string AppendQueryParams(string url, Dictionary queryParams) - { - var query = new List(); - foreach (var param in queryParams) - { - if (string.IsNullOrEmpty(param.Value)) - { - continue; - } - query.Add($"{param.Key}={param.Value}"); - } - - return url + "?" + string.Join("&", query); - } -} diff --git a/Thirdweb/Thirdweb.Client/ITimeoutOptions.cs b/Thirdweb/Thirdweb.Client/ITimeoutOptions.cs deleted file mode 100644 index b4dfb165..00000000 --- a/Thirdweb/Thirdweb.Client/ITimeoutOptions.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Thirdweb; - -/// -/// Interface for defining timeout options for different types of operations. -/// -public interface ITimeoutOptions -{ - /// - /// Gets the timeout value for the specified operation type. - /// - /// The type of operation. - /// The fallback timeout value if none is specified. - /// The timeout value for the specified operation type. - int GetTimeout(TimeoutType type, int fallback = Constants.DEFAULT_FETCH_TIMEOUT); -} diff --git a/Thirdweb/Thirdweb.Client/TimeoutOptions.cs b/Thirdweb/Thirdweb.Client/ThirdwebClient.Types.cs similarity index 77% rename from Thirdweb/Thirdweb.Client/TimeoutOptions.cs rename to Thirdweb/Thirdweb.Client/ThirdwebClient.Types.cs index c94de84d..797a2516 100644 --- a/Thirdweb/Thirdweb.Client/TimeoutOptions.cs +++ b/Thirdweb/Thirdweb.Client/ThirdwebClient.Types.cs @@ -9,7 +9,7 @@ /// The timeout for storage operations (optional). /// The timeout for RPC operations (optional). /// The timeout for other operations (optional). -public class TimeoutOptions(int? storage = null, int? rpc = null, int? other = null) : ITimeoutOptions +public class TimeoutOptions(int? storage = null, int? rpc = null, int? other = null) { internal int? Storage { get; private set; } = storage; internal int? Rpc { get; private set; } = rpc; @@ -32,3 +32,24 @@ public int GetTimeout(TimeoutType type, int fallback = Constants.DEFAULT_FETCH_T }; } } + +/// +/// Specifies the type of timeout for various operations. +/// +public enum TimeoutType +{ + /// + /// Timeout for storage operations. + /// + Storage, + + /// + /// Timeout for RPC operations. + /// + Rpc, + + /// + /// Timeout for other types of operations. + /// + Other, +} diff --git a/Thirdweb/Thirdweb.Client/ThirdwebClient.cs b/Thirdweb/Thirdweb.Client/ThirdwebClient.cs index ffc99cbe..3c0398a6 100644 --- a/Thirdweb/Thirdweb.Client/ThirdwebClient.cs +++ b/Thirdweb/Thirdweb.Client/ThirdwebClient.cs @@ -21,21 +21,21 @@ public class ThirdwebClient public string ClientId { get; } /// - /// Interactiton with https://api.thirdweb.com + /// Low-level interaction with https://api.thirdweb.com /// Used in some places to enhance the core SDK functionality, or even extend it /// - internal ThirdwebApiClient Api { get; } + public ThirdwebApiClient Api { get; internal set; } internal string SecretKey { get; } internal string BundleId { get; } - internal ITimeoutOptions FetchTimeoutOptions { get; } + internal TimeoutOptions FetchTimeoutOptions { get; } internal Dictionary RpcOverrides { get; } private ThirdwebClient( string clientId = null, string secretKey = null, string bundleId = null, - ITimeoutOptions fetchTimeoutOptions = null, + TimeoutOptions fetchTimeoutOptions = null, IThirdwebHttpClient httpClient = null, string sdkName = null, string sdkOs = null, @@ -101,7 +101,7 @@ public static ThirdwebClient Create( string clientId = null, string secretKey = null, string bundleId = null, - ITimeoutOptions fetchTimeoutOptions = null, + TimeoutOptions fetchTimeoutOptions = null, IThirdwebHttpClient httpClient = null, string sdkName = null, string sdkOs = null, @@ -112,4 +112,10 @@ public static ThirdwebClient Create( { return new ThirdwebClient(clientId, secretKey, bundleId, fetchTimeoutOptions, httpClient, sdkName, sdkOs, sdkPlatform, sdkVersion, rpcOverrides); } + + internal void UpdateApiClient(IThirdwebHttpClient httpClient) + { + var wrappedHttpClient = new ThirdwebHttpClientWrapper(httpClient); + this.Api = new ThirdwebApiClient(wrappedHttpClient); + } } diff --git a/Thirdweb/Thirdweb.Client/TimeoutType.cs b/Thirdweb/Thirdweb.Client/TimeoutType.cs deleted file mode 100644 index 658affdb..00000000 --- a/Thirdweb/Thirdweb.Client/TimeoutType.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace Thirdweb; - -/// -/// Specifies the type of timeout for various operations. -/// -public enum TimeoutType -{ - /// - /// Timeout for storage operations. - /// - Storage, - - /// - /// Timeout for RPC operations. - /// - Rpc, - - /// - /// Timeout for other types of operations. - /// - Other, -} diff --git a/Thirdweb/Thirdweb.Contracts/ThirdwebContract.cs b/Thirdweb/Thirdweb.Contracts/ThirdwebContract.cs index d980bd16..ce5d6ecd 100644 --- a/Thirdweb/Thirdweb.Contracts/ThirdwebContract.cs +++ b/Thirdweb/Thirdweb.Contracts/ThirdwebContract.cs @@ -2,7 +2,6 @@ using Nethereum.ABI.FunctionEncoding; using Nethereum.ABI.Model; using Nethereum.Contracts; -using Nethereum.Hex.HexTypes; using Newtonsoft.Json; namespace Thirdweb; @@ -280,13 +279,7 @@ public static async Task Read(ThirdwebContract contract, string method, pa public static async Task Prepare(IThirdwebWallet wallet, ThirdwebContract contract, string method, BigInteger weiValue, params object[] parameters) { var data = contract.CreateCallData(method, parameters); - var transaction = new ThirdwebTransactionInput(chainId: contract.Chain) - { - To = contract.Address, - Data = data, - Value = new HexBigInteger(weiValue), - }; - + var transaction = new ThirdwebTransactionInput(chainId: contract.Chain, to: contract.Address, data: data, value: weiValue); return await ThirdwebTransaction.Create(wallet, transaction).ConfigureAwait(false); } diff --git a/Thirdweb/Thirdweb.Extensions/ThirdwebApiExtensions.cs b/Thirdweb/Thirdweb.Extensions/ThirdwebApiExtensions.cs deleted file mode 100644 index e69de29b..00000000 diff --git a/Thirdweb/Thirdweb.Extensions/ThirdwebExtensions.Types.cs b/Thirdweb/Thirdweb.Extensions/ThirdwebExtensions.Types.cs index 197cf08c..e0a34cb1 100644 --- a/Thirdweb/Thirdweb.Extensions/ThirdwebExtensions.Types.cs +++ b/Thirdweb/Thirdweb.Extensions/ThirdwebExtensions.Types.cs @@ -80,59 +80,6 @@ public class ContractMetadata #endregion -#region Forwarder - -/// -/// Represents a forward request for a forwarder. -/// -[Struct("ForwardRequest")] -public class Forwarder_ForwardRequest -{ - /// - /// Gets or sets the address of the sender. - /// - [Parameter("address", "from", 1)] - [JsonProperty("from")] - public string From { get; set; } - - /// - /// Gets or sets the address of the recipient. - /// - [Parameter("address", "to", 2)] - [JsonProperty("to")] - public string To { get; set; } - - /// - /// Gets or sets the value to be transferred. - /// - [Parameter("uint256", "value", 3)] - [JsonProperty("value")] - public BigInteger Value { get; set; } - - /// - /// Gets or sets the gas limit for the transaction. - /// - [Parameter("uint256", "gas", 4)] - [JsonProperty("gas")] - public BigInteger Gas { get; set; } - - /// - /// Gets or sets the nonce for the transaction. - /// - [Parameter("uint256", "nonce", 5)] - [JsonProperty("nonce")] - public BigInteger Nonce { get; set; } - - /// - /// Gets or sets the data to be sent with the transaction. - /// - [Parameter("bytes", "data", 6)] - [JsonProperty("data")] - public string Data { get; set; } -} - -#endregion - #region NFT /// diff --git a/Thirdweb/Thirdweb.Extensions/ThirdwebExtensions.cs b/Thirdweb/Thirdweb.Extensions/ThirdwebExtensions.cs index c706ef13..869344c0 100644 --- a/Thirdweb/Thirdweb.Extensions/ThirdwebExtensions.cs +++ b/Thirdweb/Thirdweb.Extensions/ThirdwebExtensions.cs @@ -1,5 +1,4 @@ using System.Numerics; -using Nethereum.Hex.HexTypes; using Nethereum.Util; using Newtonsoft.Json; @@ -39,6 +38,26 @@ public static string CreateCallData(this ThirdwebContract contract, string metho return data; } + /// + /// Sends the transaction. + /// + /// The transaction. + /// The transaction hash. + public static async Task Send(this ThirdwebTransaction transaction) + { + return await ThirdwebTransaction.Send(transaction); + } + + /// + /// Sends the transaction and waits for the transaction receipt. + /// + /// The transaction. + /// The transaction receipt. + public static async Task SendAndWaitForTransactionReceipt(this ThirdwebTransaction transaction) + { + return await ThirdwebTransaction.SendAndWaitForTransactionReceipt(transaction); + } + /// /// Reads data from the contract using the specified method. /// @@ -170,7 +189,7 @@ public static async Task GetBalanceRaw(ThirdwebClient client, BigInt var rpc = ThirdwebRPC.GetRpcInstance(client, chainId); var balanceHex = await rpc.SendRequestAsync("eth_getBalance", address, "latest").ConfigureAwait(false); - return new HexBigInteger(balanceHex).Value; + return balanceHex.HexToNumber(); } /// @@ -242,7 +261,7 @@ public static async Task GetTransactionCountRaw(ThirdwebClient clien var rpc = ThirdwebRPC.GetRpcInstance(client, chainId); var balanceHex = await rpc.SendRequestAsync("eth_getTransactionCount", address, blocktag).ConfigureAwait(false); - return new HexBigInteger(balanceHex).Value; + return balanceHex.HexToNumber(); } /// @@ -330,7 +349,7 @@ public static async Task Transfer( } else { - var txInput = new ThirdwebTransactionInput(chainId) { To = toAddress, Value = new HexBigInteger(weiAmount) }; + var txInput = new ThirdwebTransactionInput(chainId: chainId, to: toAddress, value: weiAmount); var tx = await ThirdwebTransaction.Create(wallet, txInput).ConfigureAwait(false); return await ThirdwebTransaction.SendAndWaitForTransactionReceipt(tx).ConfigureAwait(false); } diff --git a/Thirdweb/Thirdweb.Extensions/ThirdwebMarketplaceExtensions.Types.cs b/Thirdweb/Thirdweb.Extensions/ThirdwebMarketplaceExtensions.Types.cs deleted file mode 100644 index 453590da..00000000 --- a/Thirdweb/Thirdweb.Extensions/ThirdwebMarketplaceExtensions.Types.cs +++ /dev/null @@ -1,469 +0,0 @@ -using System.Numerics; -using Nethereum.ABI.FunctionEncoding.Attributes; - -namespace Thirdweb; - -#region Common - -/// -/// Enumeration representing the type of tokens (ERC721, ERC1155, or ERC20). -/// -public enum TokenType : byte -{ - /// - /// Represents an ERC721 token. - /// - ERC721 = 0, - - /// - /// Represents an ERC1155 token. - /// - ERC1155 = 1, - - /// - /// Represents an ERC20 token. - /// - ERC20 = 2, -} - -/// -/// Enumeration representing the status of an entity (unset, created, completed, or cancelled). -/// -public enum Status : byte -{ - /// - /// The status is not set. - /// - UNSET = 0, - - /// - /// The entity is created. - /// - CREATED = 1, - - /// - /// The entity is completed. - /// - COMPLETED = 2, - - /// - /// The entity is cancelled. - /// - CANCELLED = 3, -} - -#endregion - -#region IDirectListings - -/// -/// Represents the parameters for creating or updating a listing in the marketplace. -/// -[Struct("ListingParameters")] -public class ListingParameters -{ - /// - /// The address of the smart contract of the NFTs being listed. - /// - [Parameter("address", "assetContract", 1)] - public string AssetContract { get; set; } - - /// - /// The tokenId of the NFTs being listed. - /// - [Parameter("uint256", "tokenId", 2)] - public BigInteger TokenId { get; set; } - - /// - /// The quantity of NFTs being listed. - /// - [Parameter("uint256", "quantity", 3)] - public BigInteger Quantity { get; set; } - - /// - /// The currency in which the price must be paid when buying the listed NFTs. - /// - [Parameter("address", "currency", 4)] - public string Currency { get; set; } - - /// - /// The price per token for the NFTs listed. - /// - [Parameter("uint256", "pricePerToken", 5)] - public BigInteger PricePerToken { get; set; } - - /// - /// The UNIX timestamp at and after which NFTs can be bought from the listing. - /// - [Parameter("uint128", "startTimestamp", 6)] - public BigInteger StartTimestamp { get; set; } - - /// - /// The UNIX timestamp after which NFTs cannot be bought from the listing. - /// - [Parameter("uint128", "endTimestamp", 7)] - public BigInteger EndTimestamp { get; set; } - - /// - /// Whether the listing is reserved to be bought from a specific set of buyers. - /// - [Parameter("bool", "reserved", 8)] - public bool Reserved { get; set; } -} - -/// -/// Represents a listing in the marketplace. -/// -[FunctionOutput] -public class Listing -{ - /// - /// The unique ID of the listing. - /// - [Parameter("uint256", "listingId", 1)] - public BigInteger ListingId { get; set; } - - /// - /// The tokenId of the NFTs being listed. - /// - [Parameter("uint256", "tokenId", 2)] - public BigInteger TokenId { get; set; } - - /// - /// The quantity of NFTs being listed. - /// - [Parameter("uint256", "quantity", 3)] - public BigInteger Quantity { get; set; } - - /// - /// The price per token for the NFTs listed. - /// - [Parameter("uint256", "pricePerToken", 4)] - public BigInteger PricePerToken { get; set; } - - /// - /// The UNIX timestamp at and after which NFTs can be bought from the listing. - /// - [Parameter("uint128", "startTimestamp", 5)] - public BigInteger StartTimestamp { get; set; } - - /// - /// The UNIX timestamp after which NFTs cannot be bought from the listing. - /// - [Parameter("uint128", "endTimestamp", 6)] - public BigInteger EndTimestamp { get; set; } - - /// - /// The address of the listing creator. - /// - [Parameter("address", "listingCreator", 7)] - public string ListingCreator { get; set; } - - /// - /// The address of the smart contract of the NFTs being listed. - /// - [Parameter("address", "assetContract", 8)] - public string AssetContract { get; set; } - - /// - /// The currency in which the price must be paid when buying the listed NFTs. - /// - [Parameter("address", "currency", 9)] - public string Currency { get; set; } - - /// - /// The type of token being listed (ERC721 or ERC1155). - /// - [Parameter("uint8", "tokenType", 10)] - public TokenType TokenTypeEnum { get; set; } - - /// - /// The status of the listing (created, completed, or cancelled). - /// - [Parameter("uint8", "status", 11)] - public Status StatusEnum { get; set; } - - /// - /// Whether the listing is reserved for a specific set of buyers. - /// - [Parameter("bool", "reserved", 12)] - public bool Reserved { get; set; } -} - -#endregion - -#region IEnglishAuctions - -/// -/// Represents the parameters for creating or updating an auction. -/// -[Struct("AuctionParameters")] -public class AuctionParameters -{ - /// - /// The address of the smart contract of the NFTs being auctioned. - /// - [Parameter("address", "assetContract", 1)] - public string AssetContract { get; set; } - - /// - /// The tokenId of the NFTs being auctioned. - /// - [Parameter("uint256", "tokenId", 2)] - public BigInteger TokenId { get; set; } - - /// - /// The quantity of NFTs being auctioned. - /// - [Parameter("uint256", "quantity", 3)] - public BigInteger Quantity { get; set; } - - /// - /// The currency in which the bid must be made. - /// - [Parameter("address", "currency", 4)] - public string Currency { get; set; } - - /// - /// The minimum bid amount for the auction. - /// - [Parameter("uint256", "minimumBidAmount", 5)] - public BigInteger MinimumBidAmount { get; set; } - - /// - /// The buyout bid amount to instantly purchase the NFTs and close the auction. - /// - [Parameter("uint256", "buyoutBidAmount", 6)] - public BigInteger BuyoutBidAmount { get; set; } - - /// - /// The buffer time in seconds to extend the auction expiration if a new bid is made. - /// - [Parameter("uint64", "timeBufferInSeconds", 7)] - public long TimeBufferInSeconds { get; set; } - - /// - /// The bid buffer in basis points to ensure a new bid must be a certain percentage higher than the current bid. - /// - [Parameter("uint64", "bidBufferBps", 8)] - public long BidBufferBps { get; set; } - - /// - /// The timestamp at and after which bids can be made to the auction. - /// - [Parameter("uint64", "startTimestamp", 9)] - public long StartTimestamp { get; set; } - - /// - /// The timestamp after which bids cannot be made to the auction. - /// - [Parameter("uint64", "endTimestamp", 10)] - public long EndTimestamp { get; set; } -} - -/// -/// Represents an auction in the marketplace. -/// -[FunctionOutput] -public class Auction -{ - /// - /// The unique ID of the auction. - /// - [Parameter("uint256", "auctionId", 1)] - public BigInteger AuctionId { get; set; } - - /// - /// The tokenId of the NFTs being auctioned. - /// - [Parameter("uint256", "tokenId", 2)] - public BigInteger TokenId { get; set; } - - /// - /// The quantity of NFTs being auctioned. - /// - [Parameter("uint256", "quantity", 3)] - public BigInteger Quantity { get; set; } - - /// - /// The minimum bid amount for the auction. - /// - [Parameter("uint256", "minimumBidAmount", 4)] - public BigInteger MinimumBidAmount { get; set; } - - /// - /// The buyout bid amount to instantly purchase the NFTs and close the auction. - /// - [Parameter("uint256", "buyoutBidAmount", 5)] - public BigInteger BuyoutBidAmount { get; set; } - - /// - /// The buffer time in seconds to extend the auction expiration if a new bid is made. - /// - [Parameter("uint64", "timeBufferInSeconds", 6)] - public long TimeBufferInSeconds { get; set; } - - /// - /// The bid buffer in basis points to ensure a new bid must be a certain percentage higher than the current bid. - /// - [Parameter("uint64", "bidBufferBps", 7)] - public long BidBufferBps { get; set; } - - /// - /// The timestamp at and after which bids can be made to the auction. - /// - [Parameter("uint64", "startTimestamp", 8)] - public long StartTimestamp { get; set; } - - /// - /// The timestamp after which bids cannot be made to the auction. - /// - [Parameter("uint64", "endTimestamp", 9)] - public long EndTimestamp { get; set; } - - /// - /// The address of the auction creator. - /// - [Parameter("address", "auctionCreator", 10)] - public string AuctionCreator { get; set; } - - /// - /// The address of the smart contract of the NFTs being auctioned. - /// - [Parameter("address", "assetContract", 11)] - public string AssetContract { get; set; } - - /// - /// The currency in which the bid must be made. - /// - [Parameter("address", "currency", 12)] - public string Currency { get; set; } - - /// - /// The type of token being auctioned (ERC721 or ERC1155). - /// - [Parameter("uint8", "tokenType", 13)] - public TokenType TokenTypeEnum { get; set; } - - /// - /// The status of the auction (created, completed, or cancelled). - /// - [Parameter("uint8", "status", 14)] - public Status StatusEnum { get; set; } -} - -#endregion - -#region IOffers - -/// -/// Represents the parameters for making an offer on NFTs. -/// -[Struct("OfferParams")] -public class OfferParams -{ - /// - /// The contract address of the NFTs for which the offer is being made. - /// - [Parameter("address", "assetContract", 1)] - public string AssetContract { get; set; } - - /// - /// The tokenId of the NFTs for which the offer is being made. - /// - [Parameter("uint256", "tokenId", 2)] - public BigInteger TokenId { get; set; } - - /// - /// The quantity of NFTs desired in the offer. - /// - [Parameter("uint256", "quantity", 3)] - public BigInteger Quantity { get; set; } - - /// - /// The currency offered in exchange for the NFTs. - /// - [Parameter("address", "currency", 4)] - public string Currency { get; set; } - - /// - /// The total price offered for the NFTs. - /// - [Parameter("uint256", "totalPrice", 5)] - public BigInteger TotalPrice { get; set; } - - /// - /// The UNIX timestamp after which the offer cannot be accepted. - /// - [Parameter("uint256", "expirationTimestamp", 6)] - public BigInteger ExpirationTimestamp { get; set; } -} - -/// -/// Represents an offer made on NFTs. -/// -[FunctionOutput] -public class Offer -{ - /// - /// The unique ID of the offer. - /// - [Parameter("uint256", "offerId", 1)] - public BigInteger OfferId { get; set; } - - /// - /// The tokenId of the NFTs for which the offer is being made. - /// - [Parameter("uint256", "tokenId", 2)] - public BigInteger TokenId { get; set; } - - /// - /// The quantity of NFTs desired in the offer. - /// - [Parameter("uint256", "quantity", 3)] - public BigInteger Quantity { get; set; } - - /// - /// The total price offered for the NFTs. - /// - [Parameter("uint256", "totalPrice", 4)] - public BigInteger TotalPrice { get; set; } - - /// - /// The UNIX timestamp after which the offer cannot be accepted. - /// - [Parameter("uint256", "expirationTimestamp", 5)] - public BigInteger ExpirationTimestamp { get; set; } - - /// - /// The address of the offeror. - /// - [Parameter("address", "offeror", 6)] - public string Offeror { get; set; } - - /// - /// The contract address of the NFTs for which the offer is made. - /// - [Parameter("address", "assetContract", 7)] - public string AssetContract { get; set; } - - /// - /// The currency offered in exchange for the NFTs. - /// - [Parameter("address", "currency", 8)] - public string Currency { get; set; } - - /// - /// The type of token being offered (ERC721, ERC1155, or ERC20). - /// - [Parameter("uint8", "tokenType", 9)] - public TokenType TokenTypeEnum { get; set; } - - /// - /// The status of the offer (created, completed, or cancelled). - /// - [Parameter("uint8", "status", 10)] - public Status StatusEnum { get; set; } -} - -#endregion diff --git a/Thirdweb/Thirdweb.Extensions/ThirdwebMarketplaceExtensions.cs b/Thirdweb/Thirdweb.Extensions/ThirdwebMarketplaceExtensions.cs deleted file mode 100644 index 70fa4542..00000000 --- a/Thirdweb/Thirdweb.Extensions/ThirdwebMarketplaceExtensions.cs +++ /dev/null @@ -1,888 +0,0 @@ -using System.Numerics; - -namespace Thirdweb; - -public static class ThirdwebMarketplaceExtensions -{ - #region IDirectListings - - /// - /// Creates a new direct listing for selling NFTs at a fixed price. - /// - /// The contract instance. - /// The wallet used for the transaction. - /// The parameters of the listing to be created. - /// Whether to handle token approvals automatically. - /// A task that represents the transaction receipt of the listing creation. - public static async Task Marketplace_DirectListings_CreateListing( - this ThirdwebContract contract, - IThirdwebWallet wallet, - ListingParameters parameters, - bool handleApprovals = false - ) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - if (wallet == null) - { - throw new ArgumentNullException(nameof(wallet)); - } - - if (parameters == null) - { - throw new ArgumentNullException(nameof(parameters)); - } - - if (handleApprovals) - { - var assetContractAddress = parameters.AssetContract; - - var prepTasks = new List(); - - var assetContractTask = ThirdwebContract.Create(contract.Client, assetContractAddress, contract.Chain); - prepTasks.Add(assetContractTask); - - var walletAddressTask = wallet.GetAddress(); - prepTasks.Add(walletAddressTask); - - await Task.WhenAll(prepTasks); - - var assetContract = assetContractTask.Result; - var walletAddress = walletAddressTask.Result; - - TokenType assetType; - if (await assetContract.SupportsInterface(Constants.IERC1155_INTERFACE_ID)) - { - assetType = TokenType.ERC1155; - } - else if (await assetContract.SupportsInterface(Constants.IERC721_INTERFACE_ID)) - { - assetType = TokenType.ERC721; - } - else - { - throw new ArgumentException("Asset contract does not support ERC1155 or ERC721 interface."); - } - - if (assetType == TokenType.ERC721) - { - var tokenId = parameters.TokenId; - var @operator = await assetContract.ERC721_GetApproved(tokenId); - if (@operator != contract.Address) - { - _ = await assetContract.ERC721_Approve(wallet, contract.Address, tokenId); - } - } - else - { - var isApprovedForAll = await assetContract.ERC1155_IsApprovedForAll(walletAddress, contract.Address); - if (!isApprovedForAll) - { - _ = await assetContract.ERC1155_SetApprovalForAll(wallet, contract.Address, true); - } - } - } - - return await contract.Write(wallet, "createListing", 0, parameters); - } - - /// - /// Updates an existing direct listing. - /// - /// The contract instance. - /// The wallet used for the transaction. - /// The ID of the listing to update. - /// The updated parameters of the listing. - /// A task that represents the transaction receipt of the listing update. - public static async Task Marketplace_DirectListings_UpdateListing( - this ThirdwebContract contract, - IThirdwebWallet wallet, - BigInteger listingId, - ListingParameters parameters - ) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - if (wallet == null) - { - throw new ArgumentNullException(nameof(wallet)); - } - - if (parameters == null) - { - throw new ArgumentNullException(nameof(parameters)); - } - - return await contract.Write(wallet, "updateListing", 0, listingId, parameters); - } - - /// - /// Cancels a direct listing. - /// - /// The contract instance. - /// The wallet used for the transaction. - /// The ID of the listing to cancel. - /// A task that represents the transaction receipt of the listing cancellation. - public static async Task Marketplace_DirectListings_CancelListing(this ThirdwebContract contract, IThirdwebWallet wallet, BigInteger listingId) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - if (wallet == null) - { - throw new ArgumentNullException(nameof(wallet)); - } - - return await contract.Write(wallet, "cancelListing", 0, listingId); - } - - /// - /// Approves a buyer to purchase from a reserved listing. - /// - /// The contract instance. - /// The wallet used for the transaction. - /// The ID of the listing. - /// The address of the buyer to approve. - /// Whether to approve or disapprove the buyer. - /// A task that represents the transaction receipt of the approval. - public static async Task Marketplace_DirectListings_ApproveBuyerForListing( - this ThirdwebContract contract, - IThirdwebWallet wallet, - BigInteger listingId, - string buyer, - bool toApprove - ) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - if (wallet == null) - { - throw new ArgumentNullException(nameof(wallet)); - } - - return await contract.Write(wallet, "approveBuyerForListing", 0, listingId, buyer, toApprove); - } - - /// - /// Approves a currency for a direct listing. - /// - /// The contract instance. - /// The wallet used for the transaction. - /// The ID of the listing. - /// The address of the currency to approve. - /// The price per token in the specified currency. - /// A task that represents the transaction receipt of the currency approval. - public static async Task Marketplace_DirectListings_ApproveCurrencyForListing( - this ThirdwebContract contract, - IThirdwebWallet wallet, - BigInteger listingId, - string currency, - BigInteger pricePerTokenInCurrency - ) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - if (wallet == null) - { - throw new ArgumentNullException(nameof(wallet)); - } - - return await contract.Write(wallet, "approveCurrencyForListing", 0, listingId, currency, pricePerTokenInCurrency); - } - - /// - /// Buys from a direct listing. - /// - /// The contract instance. - /// The wallet used for the transaction. - /// The ID of the listing. - /// The recipient address for the purchased NFTs. - /// The quantity of NFTs to buy. - /// The currency to use for the purchase. - /// The expected total price to pay. - /// Whether to handle token approvals automatically. - /// A task that represents the transaction receipt of the purchase. - public static async Task Marketplace_DirectListings_BuyFromListing( - this ThirdwebContract contract, - IThirdwebWallet wallet, - BigInteger listingId, - string buyFor, - BigInteger quantity, - string currency, - BigInteger expectedTotalPrice, - bool handleApprovals = false - ) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - if (wallet == null) - { - throw new ArgumentNullException(nameof(wallet)); - } - - var value = BigInteger.Zero; - - if (currency == Constants.NATIVE_TOKEN_ADDRESS) - { - value = expectedTotalPrice; - } - else if (handleApprovals) - { - var tokenContractAddress = currency; - - var prepTasks = new List(); - - var tokenContractTask = ThirdwebContract.Create(contract.Client, tokenContractAddress, contract.Chain); - prepTasks.Add(tokenContractTask); - - var walletAddressTask = wallet.GetAddress(); - prepTasks.Add(walletAddressTask); - - await Task.WhenAll(prepTasks); - - var tokenContract = tokenContractTask.Result; - var walletAddress = walletAddressTask.Result; - - var allowance = await tokenContract.ERC20_Allowance(walletAddress, contract.Address); - if (allowance < expectedTotalPrice) - { - _ = await tokenContract.ERC20_Approve(wallet, contract.Address, expectedTotalPrice); - } - } - - return await contract.Write(wallet, "buyFromListing", value, listingId, buyFor, quantity, currency, expectedTotalPrice); - } - - /// - /// Gets the total number of direct listings created. - /// - /// The contract instance. - /// A task that represents the total number of direct listings. - public static async Task Marketplace_DirectListings_TotalListings(this ThirdwebContract contract) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - return await contract.Read("totalListings"); - } - - /// - /// Gets all direct listings within a given range of IDs. - /// - /// The contract instance. - /// The start ID of the range. - /// The end ID of the range. - /// A task that represents a list of listings within the range. - public static async Task> Marketplace_DirectListings_GetAllListings(this ThirdwebContract contract, BigInteger startId, BigInteger endId) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - return await contract.Read>("getAllListings", startId, endId); - } - - /// - /// Gets all valid direct listings within a given range of IDs. - /// - /// The contract instance. - /// The start ID of the range. - /// The end ID of the range. - /// A task that represents a list of valid listings within the range. - public static async Task> Marketplace_DirectListings_GetAllValidListings(this ThirdwebContract contract, BigInteger startId, BigInteger endId) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - return await contract.Read>("getAllValidListings", startId, endId); - } - - /// - /// Gets a specific direct listing by its ID. - /// - /// The contract instance. - /// The ID of the listing to fetch. - /// A task that represents the requested listing. - public static async Task Marketplace_DirectListings_GetListing(this ThirdwebContract contract, BigInteger listingId) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - return await contract.Read("getListing", listingId); - } - - /// - /// Checks whether a buyer is approved for a direct listing. - /// - /// The contract instance. - /// The ID of the listing. - /// The address of the buyer to check. - /// A task that represents a boolean indicating if the buyer is approved. - public static async Task Marketplace_DirectListings_IsBuyerApprovedForListing(this ThirdwebContract contract, BigInteger listingId, string buyer) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - return await contract.Read("isBuyerApprovedForListing", listingId, buyer); - } - - /// - /// Checks whether a currency is approved for a direct listing. - /// - /// The contract instance. - /// The ID of the listing. - /// The address of the currency to check. - /// A task that represents a boolean indicating if the currency is approved. - public static async Task Marketplace_DirectListings_IsCurrencyApprovedForListing(this ThirdwebContract contract, BigInteger listingId, string currency) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - return await contract.Read("isCurrencyApprovedForListing", listingId, currency); - } - - /// - /// Gets the price per token for a direct listing in the specified currency. - /// - /// The contract instance. - /// The ID of the listing. - /// The address of the currency to check. - /// A task that represents the price per token in the specified currency. - public static async Task Marketplace_DirectListings_CurrencyPriceForListing(this ThirdwebContract contract, BigInteger listingId, string currency) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - return await contract.Read("currencyPriceForListing", listingId, currency); - } - - #endregion - - #region IEnglishAuctions - - /// - /// Creates a new auction listing for NFTs. - /// - /// The contract instance. - /// The wallet used for the transaction. - /// The parameters of the auction to be created. - /// Whether to handle token approvals automatically. - /// A task that represents the transaction receipt of the auction creation. - public static async Task Marketplace_EnglishAuctions_CreateAuction( - this ThirdwebContract contract, - IThirdwebWallet wallet, - AuctionParameters parameters, - bool handleApprovals = false - ) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - if (wallet == null) - { - throw new ArgumentNullException(nameof(wallet)); - } - - if (parameters == null) - { - throw new ArgumentNullException(nameof(parameters)); - } - - if (handleApprovals) - { - var assetContractAddress = parameters.AssetContract; - - var prepTasks = new List(); - - var assetContractTask = ThirdwebContract.Create(contract.Client, assetContractAddress, contract.Chain); - prepTasks.Add(assetContractTask); - - var walletAddressTask = wallet.GetAddress(); - prepTasks.Add(walletAddressTask); - - await Task.WhenAll(prepTasks); - - var assetContract = assetContractTask.Result; - var walletAddress = walletAddressTask.Result; - - TokenType assetType; - if (await assetContract.SupportsInterface(Constants.IERC1155_INTERFACE_ID)) - { - assetType = TokenType.ERC1155; - } - else if (await assetContract.SupportsInterface(Constants.IERC721_INTERFACE_ID)) - { - assetType = TokenType.ERC721; - } - else - { - throw new ArgumentException("Asset contract does not support ERC1155 or ERC721 interface."); - } - - if (assetType == TokenType.ERC721) - { - var tokenId = parameters.TokenId; - var @operator = await assetContract.ERC721_GetApproved(tokenId); - if (@operator != contract.Address) - { - _ = await assetContract.ERC721_Approve(wallet, contract.Address, tokenId); - } - } - else - { - var isApprovedForAll = await assetContract.ERC1155_IsApprovedForAll(walletAddress, contract.Address); - if (!isApprovedForAll) - { - _ = await assetContract.ERC1155_SetApprovalForAll(wallet, contract.Address, true); - } - } - } - - return await contract.Write(wallet, "createAuction", 0, parameters); - } - - /// - /// Cancels an existing auction listing. - /// - /// The contract instance. - /// The wallet used for the transaction. - /// The ID of the auction to cancel. - /// A task that represents the transaction receipt of the auction cancellation. - public static async Task Marketplace_EnglishAuctions_CancelAuction(this ThirdwebContract contract, IThirdwebWallet wallet, BigInteger auctionId) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - if (wallet == null) - { - throw new ArgumentNullException(nameof(wallet)); - } - - return await contract.Write(wallet, "cancelAuction", 0, auctionId); - } - - /// - /// Collects the payout for a completed auction. - /// - /// The contract instance. - /// The wallet used for the transaction. - /// The ID of the auction for which to collect the payout. - /// A task that represents the transaction receipt of the auction payout collection. - public static async Task Marketplace_EnglishAuctions_CollectAuctionPayout(this ThirdwebContract contract, IThirdwebWallet wallet, BigInteger auctionId) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - if (wallet == null) - { - throw new ArgumentNullException(nameof(wallet)); - } - - return await contract.Write(wallet, "collectAuctionPayout", 0, auctionId); - } - - /// - /// Collects the tokens from a completed auction. - /// - /// The contract instance. - /// The wallet used for the transaction. - /// The ID of the auction for which to collect the tokens. - /// A task that represents the transaction receipt of the auction token collection. - public static async Task Marketplace_EnglishAuctions_CollectAuctionTokens(this ThirdwebContract contract, IThirdwebWallet wallet, BigInteger auctionId) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - if (wallet == null) - { - throw new ArgumentNullException(nameof(wallet)); - } - - return await contract.Write(wallet, "collectAuctionTokens", 0, auctionId); - } - - /// - /// Places a bid in an auction. - /// - /// The contract instance. - /// The wallet used for the transaction. - /// The ID of the auction to bid in. - /// The bid amount to place. - /// Whether to handle token approvals automatically. - /// A task that represents the transaction receipt of the placed bid. - public static async Task Marketplace_EnglishAuctions_BidInAuction( - this ThirdwebContract contract, - IThirdwebWallet wallet, - BigInteger auctionId, - BigInteger bidAmount, - bool handleApprovals = false - ) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - if (wallet == null) - { - throw new ArgumentNullException(nameof(wallet)); - } - - var value = BigInteger.Zero; - - var auctionDetails = await contract.Marketplace_EnglishAuctions_GetAuction(auctionId); - if (auctionDetails.Currency == Constants.NATIVE_TOKEN_ADDRESS) - { - value = bidAmount; - } - else if (handleApprovals) - { - var tokenContractAddress = auctionDetails.Currency; - - var prepTasks = new List(); - - var tokenContractTask = ThirdwebContract.Create(contract.Client, tokenContractAddress, contract.Chain); - prepTasks.Add(tokenContractTask); - - var walletAddressTask = wallet.GetAddress(); - prepTasks.Add(walletAddressTask); - - await Task.WhenAll(prepTasks); - - var tokenContract = tokenContractTask.Result; - var walletAddress = walletAddressTask.Result; - - var allowance = await tokenContract.ERC20_Allowance(walletAddress, contract.Address); - if (allowance < bidAmount) - { - _ = await tokenContract.ERC20_Approve(wallet, contract.Address, bidAmount); - } - } - - return await contract.Write(wallet, "bidInAuction", value, auctionId, bidAmount); - } - - /// - /// Checks whether the bid amount would make for a winning bid in an auction. - /// - /// The contract instance. - /// The ID of the auction. - /// The bid amount to check. - /// A task that represents a boolean indicating if the bid would be a winning bid. - public static async Task Marketplace_EnglishAuctions_IsNewWinningBid(this ThirdwebContract contract, BigInteger auctionId, BigInteger bidAmount) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - return await contract.Read("isNewWinningBid", auctionId, bidAmount); - } - - /// - /// Retrieves the details of a specific auction by its ID. - /// - /// The contract instance. - /// The ID of the auction to fetch. - /// A task that represents the requested auction details. - public static async Task Marketplace_EnglishAuctions_GetAuction(this ThirdwebContract contract, BigInteger auctionId) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - return await contract.Read("getAuction", auctionId); - } - - /// - /// Gets all auctions within a given range of IDs. - /// - /// The contract instance. - /// The start ID of the range. - /// The end ID of the range. - /// A task that represents a list of auctions within the range. - public static async Task> Marketplace_EnglishAuctions_GetAllAuctions(this ThirdwebContract contract, BigInteger startId, BigInteger endId) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - return await contract.Read>("getAllAuctions", startId, endId); - } - - /// - /// Gets all valid auctions within a given range of IDs. - /// - /// The contract instance. - /// The start ID of the range. - /// The end ID of the range. - /// A task that represents a list of valid auctions within the range. - public static async Task> Marketplace_EnglishAuctions_GetAllValidAuctions(this ThirdwebContract contract, BigInteger startId, BigInteger endId) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - return await contract.Read>("getAllValidAuctions", startId, endId); - } - - /// - /// Gets the winning bid of a specific auction. - /// - /// The contract instance. - /// The ID of the auction to retrieve the winning bid from. - /// A task that represents the winning bid details (bidder, currency, bidAmount). - public static async Task<(string bidder, string currency, BigInteger bidAmount)> Marketplace_EnglishAuctions_GetWinningBid(this ThirdwebContract contract, BigInteger auctionId) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - var res = await contract.Read>("getWinningBid", auctionId); - return (res[0].ToString(), res[1].ToString(), (BigInteger)res[2]); - } - - /// - /// Checks whether an auction is expired. - /// - /// The contract instance. - /// The ID of the auction to check. - /// A task that represents a boolean indicating if the auction is expired. - public static async Task Marketplace_EnglishAuctions_IsAuctionExpired(this ThirdwebContract contract, BigInteger auctionId) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - return await contract.Read("isAuctionExpired", auctionId); - } - - /// - /// Gets the total number of auctions created. - /// - /// The contract instance. - /// A task that represents the total number of auctions. - public static async Task Marketplace_EnglishAuctions_TotalAuctions(this ThirdwebContract contract) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - return await contract.Read("totalAuctions"); - } - - #endregion - - #region IOffers - - /// - /// Makes an offer for NFTs. - /// - /// The contract instance. - /// The wallet used for the transaction. - /// The parameters of the offer to make. - /// Whether to handle token approvals automatically. - /// A task that represents the transaction receipt of the offer creation. - public static async Task Marketplace_Offers_MakeOffer(this ThirdwebContract contract, IThirdwebWallet wallet, OfferParams parameters, bool handleApprovals = false) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - if (wallet == null) - { - throw new ArgumentNullException(nameof(wallet)); - } - - if (parameters == null) - { - throw new ArgumentNullException(nameof(parameters)); - } - - var token = parameters.Currency; - if (token == Constants.NATIVE_TOKEN_ADDRESS) - { - throw new ArgumentException("Native token is not supported for offers, please wrap it or use ERC20 to make an offer.", nameof(parameters)); - } - - if (handleApprovals) - { - var prepTasks = new List(); - - var tokenContractTask = ThirdwebContract.Create(contract.Client, token, contract.Chain); - prepTasks.Add(tokenContractTask); - - var walletAddressTask = wallet.GetAddress(); - prepTasks.Add(walletAddressTask); - - await Task.WhenAll(prepTasks); - - var tokenContract = tokenContractTask.Result; - var walletAddress = walletAddressTask.Result; - - var allowance = await tokenContract.ERC20_Allowance(walletAddress, contract.Address); - if (allowance < parameters.TotalPrice) - { - _ = await tokenContract.ERC20_Approve(wallet, contract.Address, parameters.Quantity); - } - } - - return await contract.Write(wallet, "makeOffer", 0, parameters); - } - - /// - /// Cancels an existing offer. - /// - /// The contract instance. - /// The wallet used for the transaction. - /// The ID of the offer to cancel. - /// A task that represents the transaction receipt of the offer cancellation. - public static async Task Marketplace_Offers_CancelOffer(this ThirdwebContract contract, IThirdwebWallet wallet, BigInteger offerId) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - if (wallet == null) - { - throw new ArgumentNullException(nameof(wallet)); - } - - return await contract.Write(wallet, "cancelOffer", 0, offerId); - } - - /// - /// Accepts an existing offer. - /// - /// The contract instance. - /// The wallet used for the transaction. - /// The ID of the offer to accept. - /// A task that represents the transaction receipt of the offer acceptance. - public static async Task Marketplace_Offers_AcceptOffer(this ThirdwebContract contract, IThirdwebWallet wallet, BigInteger offerId) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - if (wallet == null) - { - throw new ArgumentNullException(nameof(wallet)); - } - - return await contract.Write(wallet, "acceptOffer", 0, offerId); - } - - /// - /// Retrieves the details of a specific offer by its ID. - /// - /// The contract instance. - /// The ID of the offer to fetch. - /// A task that represents the requested offer details. - public static async Task Marketplace_Offers_GetOffer(this ThirdwebContract contract, BigInteger offerId) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - return await contract.Read("getOffer", offerId); - } - - /// - /// Gets all offers within a given range of IDs. - /// - /// The contract instance. - /// The start ID of the range. - /// The end ID of the range. - /// A task that represents a list of offers within the range. - public static async Task> Marketplace_Offers_GetAllOffers(this ThirdwebContract contract, BigInteger startId, BigInteger endId) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - return await contract.Read>("getAllOffers", startId, endId); - } - - /// - /// Gets all valid offers within a given range of IDs. - /// - /// The contract instance. - /// The start ID of the range. - /// The end ID of the range. - /// A task that represents a list of valid offers within the range. - public static async Task> Marketplace_Offers_GetAllValidOffers(this ThirdwebContract contract, BigInteger startId, BigInteger endId) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - return await contract.Read>("getAllValidOffers", startId, endId); - } - - /// - /// Gets the total number of offers created. - /// - /// The contract instance. - /// A task that represents the total number of offers. - public static async Task Marketplace_Offers_TotalOffers(this ThirdwebContract contract) - { - if (contract == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - return await contract.Read("totalOffers"); - } - - #endregion -} diff --git a/Thirdweb/Thirdweb.Indexer/ThirdwebInsight.Extensions.cs b/Thirdweb/Thirdweb.Indexer/ThirdwebInsight.Extensions.cs deleted file mode 100644 index 5d20d3fc..00000000 --- a/Thirdweb/Thirdweb.Indexer/ThirdwebInsight.Extensions.cs +++ /dev/null @@ -1,47 +0,0 @@ -namespace Thirdweb.Indexer; - -public static class ThirdwebInsightExtensions -{ - public static NFT ToNFT(this Token_NFT token) - { - if (token == null) - { - return new NFT(); - } - - return new NFT() - { - Type = token.Contract?.Type switch - { - "ERC721" => NFTType.ERC721, - "ERC1155" => NFTType.ERC1155, - "erc721" => NFTType.ERC721, - "erc1155" => NFTType.ERC1155, - _ => throw new Exception($"Unknown NFT type: {token.Contract.Type}"), - }, - Metadata = new NFTMetadata() - { - Id = token.TokenId, - Description = token.Description, - Image = token.ImageUrl, - Name = token.Name, - VideoUrl = token.VideoUrl, - AnimationUrl = token.AnimationUrl, - ExternalUrl = token.ExternalUrl, - BackgroundColor = token.BackgroundColor, - Attributes = token.ExtraMetadata?.Attributes, - Properties = token.ExtraMetadata?.Properties, - }, - }; - } - - public static List ToNFTList(this IEnumerable tokens) - { - if (tokens == null) - { - return new List(); - } - - return tokens.Select(token => token.ToNFT()).ToList(); - } -} diff --git a/Thirdweb/Thirdweb.Indexer/ThirdwebInsight.Types.cs b/Thirdweb/Thirdweb.Indexer/ThirdwebInsight.Types.cs deleted file mode 100644 index 4a3d83fb..00000000 --- a/Thirdweb/Thirdweb.Indexer/ThirdwebInsight.Types.cs +++ /dev/null @@ -1,343 +0,0 @@ -using System.Numerics; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Thirdweb.Indexer; - -/// -/// Represents the response model wrapping the result of an API call. -/// -/// The type of the result. -internal class ResponseModel -{ - /// - /// The result returned by the API. - /// - [JsonProperty("data")] - internal T[] Data { get; set; } - - [JsonProperty("aggregations")] - public object Aggregations { get; set; } = null!; - - [JsonProperty("meta")] - public Meta Meta { get; set; } = null!; -} - -public class Meta -{ - [JsonProperty("chain_ids")] - public List ChainIds { get; set; } = new(); - - [JsonProperty("address")] - public string Address { get; set; } - - [JsonProperty("signature")] - public string Signature { get; set; } - - [JsonProperty("page")] - public BigInteger Page { get; set; } - - [JsonProperty("limit_per_chain")] - public BigInteger LimitPerChain { get; set; } - - [JsonProperty("total_items")] - public BigInteger TotalItems { get; set; } - - [JsonProperty("total_pages")] - public BigInteger TotalPages { get; set; } -} - -#region Price API - -public class Token_Price -{ - [JsonProperty("chain_id")] - public BigInteger ChainId { get; set; } - - [JsonProperty("address")] - public string Address { get; set; } - - [JsonProperty("symbol")] - public string Symbol { get; set; } - - [JsonProperty("price_usd")] - public double PriceUsd { get; set; } - - [JsonProperty("price_usd_cents")] - public double PriceUsdCents { get; set; } - - public override string ToString() - { - return JsonConvert.SerializeObject(this); - } -} - -#endregion - -#region Tokens API - -public class Token_ERC20 : Token { } - -public class Token_ERC721 : Token_NFT { } - -public class Token_ERC1155 : Token_NFT { } - -public class Token -{ - [JsonProperty("chain_id")] - public BigInteger ChainId { get; set; } - - [JsonProperty("balance")] - public BigInteger Balance { get; set; } - - [JsonProperty("token_address")] - public string TokenAddress { get; set; } -} - -[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] -public class Token_NFT : Token -{ - [JsonProperty("token_id")] - public string TokenId { get; set; } - - [JsonProperty("name")] - public string Name { get; set; } - - [JsonProperty("description")] - public string Description { get; set; } - - [JsonProperty("image_url")] - public string ImageUrl { get; set; } - - [JsonProperty("video_url")] - public string VideoUrl { get; set; } - - [JsonProperty("animation_url")] - public string AnimationUrl { get; set; } - - [JsonProperty("background_color")] - public string BackgroundColor { get; set; } - - [JsonProperty("external_url")] - public string ExternalUrl { get; set; } - - [JsonProperty("status")] - public string Status { get; set; } - - [JsonProperty("extra_metadata")] - public NFT_ExtraMetadata ExtraMetadata { get; set; } - - [JsonProperty("collection")] - public NFT_Collection Collection { get; set; } - - [JsonProperty("contract")] - public NFT_Contract Contract { get; set; } -} - -[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] -public class NFT_ExtraMetadata -{ - [JsonProperty("attributes")] - public object Attributes { get; set; } - - [JsonProperty("properties")] - public object Properties { get; set; } -} - -[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] -public class AttributeData -{ - [JsonProperty("trait_type")] - public string TraitType { get; set; } - - [JsonProperty("value")] - public object Value { get; set; } - - [JsonProperty("display_type")] - public string DisplayType { get; set; } -} - -[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] -public class NFT_Collection -{ - [JsonProperty("name")] - public string Name { get; set; } - - [JsonProperty("description")] - public string Description { get; set; } - - [JsonProperty("image_url")] - public string ImageUrl { get; set; } - - [JsonProperty("banner_image_url")] - public string BannerImageUrl { get; set; } - - [JsonProperty("featured_image_url")] - public string FeaturedImageUrl { get; set; } - - [JsonProperty("external_link")] - public string ExternalLink { get; set; } -} - -public class NFT_Contract -{ - [JsonProperty("name")] - public string Name { get; set; } - - [JsonProperty("symbol")] - public string Symbol { get; set; } - - [JsonProperty("type")] - internal string Type { get; set; } // ERC721, ERC1155 -} - -#endregion - -#region Events API - -public class Event -{ - [JsonProperty("chain_id")] - public BigInteger ChainId { get; set; } - - [JsonProperty("block_number")] - public string BlockNumber { get; set; } = null!; - - [JsonProperty("block_hash")] - public string BlockHash { get; set; } = null!; - - [JsonProperty("block_timestamp")] - public string BlockTimestamp { get; set; } = null!; - - [JsonProperty("transaction_hash")] - public string TransactionHash { get; set; } = null!; - - [JsonProperty("transaction_index")] - public BigInteger TransactionIndex { get; set; } - - [JsonProperty("log_index")] - public BigInteger LogIndex { get; set; } - - [JsonProperty("address")] - public string Address { get; set; } = null!; - - [JsonProperty("data")] - public string Data { get; set; } = null!; - - [JsonProperty("topics")] - public List Topics { get; set; } = new(); - - [JsonProperty("decoded")] - public Event_Decoded Decoded { get; set; } = null!; -} - -public class Event_Decoded -{ - [JsonProperty("name")] - public string Name { get; set; } = null!; - - [JsonProperty("signature")] - public string Signature { get; set; } = null!; - - [JsonProperty("indexed_params")] - public JObject IndexedParams { get; set; } = new(); - - [JsonProperty("non_indexed_params")] - public JObject NonIndexedParams { get; set; } = new(); -} - -#endregion - -#region Transactions API - -public class Transaction -{ - [JsonProperty("chain_id")] - public BigInteger ChainId { get; set; } - - [JsonProperty("block_number")] - public string BlockNumber { get; set; } = null!; - - [JsonProperty("block_hash")] - public string BlockHash { get; set; } = null!; - - [JsonProperty("block_timestamp")] - public string BlockTimestamp { get; set; } = null!; - - [JsonProperty("hash")] - public string Hash { get; set; } = null!; - - [JsonProperty("nonce")] - public BigInteger Nonce { get; set; } - - [JsonProperty("transaction_index")] - public BigInteger TransactionIndex { get; set; } - - [JsonProperty("from_address")] - public string FromAddress { get; set; } = null!; - - [JsonProperty("to_address")] - public string ToAddress { get; set; } = null!; - - [JsonProperty("value")] - public BigInteger Value { get; set; } - - [JsonProperty("gas_price")] - public BigInteger GasPrice { get; set; } - - [JsonProperty("gas")] - public BigInteger Gas { get; set; } - - [JsonProperty("function_selector")] - public string FunctionSelector { get; set; } = null!; - - [JsonProperty("data")] - public string Data { get; set; } = null!; - - [JsonProperty("max_fee_per_gas")] - public BigInteger MaxFeePerGas { get; set; } - - [JsonProperty("max_priority_fee_per_gas")] - public BigInteger MaxPriorityFeePerGas { get; set; } - - [JsonProperty("transaction_type")] - public BigInteger TransactionType { get; set; } - - [JsonProperty("r")] - public BigInteger R { get; set; } - - [JsonProperty("s")] - public BigInteger S { get; set; } - - [JsonProperty("v")] - public BigInteger V { get; set; } - - [JsonProperty("access_list_json")] - public string AccessListJson { get; set; } - - [JsonProperty("contract_address")] - public string ContractAddress { get; set; } - - [JsonProperty("gas_used")] - public BigInteger? GasUsed { get; set; } - - [JsonProperty("cumulative_gas_used")] - public BigInteger? CumulativeGasUsed { get; set; } - - [JsonProperty("effective_gas_price")] - public BigInteger? EffectiveGasPrice { get; set; } - - [JsonProperty("blob_gas_used")] - public BigInteger? BlobGasUsed { get; set; } - - [JsonProperty("blob_gas_price")] - public BigInteger? BlobGasPrice { get; set; } - - [JsonProperty("logs_bloom")] - public string LogsBloom { get; set; } - - [JsonProperty("status")] - public BigInteger? Status { get; set; } -} - -#endregion diff --git a/Thirdweb/Thirdweb.Indexer/ThirdwebInsight.cs b/Thirdweb/Thirdweb.Indexer/ThirdwebInsight.cs deleted file mode 100644 index b232cca5..00000000 --- a/Thirdweb/Thirdweb.Indexer/ThirdwebInsight.cs +++ /dev/null @@ -1,409 +0,0 @@ -using System.Numerics; -using Newtonsoft.Json; - -namespace Thirdweb.Indexer; - -public enum SortBy -{ - BlockNumber, - BlockTimestamp, - TransactionIndex, -} - -public enum SortOrder -{ - Asc, - Desc, -} - -public class InsightEvents -{ - public Event[] Events { get; set; } - public Meta Meta { get; set; } -} - -public class InsightTransactions -{ - public Transaction[] Transactions { get; set; } - public Meta Meta { get; set; } -} - -public class ThirdwebInsight -{ - private readonly IThirdwebHttpClient _httpClient; - - internal ThirdwebInsight(ThirdwebClient client) - { - this._httpClient = client.HttpClient; - } - - /// - /// Create a new instance of the ThirdwebInsight class. - /// - /// The ThirdwebClient instance. - /// A new instance of . - public static Task Create(ThirdwebClient client) - { - return Task.FromResult(new ThirdwebInsight(client)); - } - - public async Task GetTokenPrice(string addressOrSymbol, BigInteger chainId, long? timestamp = null) - { - var prices = await this.GetTokenPrices(new[] { addressOrSymbol }, new[] { chainId }, timestamp).ConfigureAwait(false); - if (prices.Length == 0) - { - throw new Exception("Token price not found."); - } - return prices[0]; - } - - public async Task GetTokenPrices(string[] addressOrSymbols, BigInteger[] chainIds, long? timestamp = null) - { - var addresses = addressOrSymbols.Where(Utils.IsValidAddress).ToArray(); - var symbols = addressOrSymbols.Except(addresses).ToArray(); - - var url = AppendChains($"{Constants.INSIGHT_API_URL}/v1/tokens/price", chainIds); - - if (addresses.Length > 0) - { - url += $"&address={string.Join("&address=", addresses)}"; - } - - if (symbols.Length > 0) - { - url += $"&symbol={string.Join("&symbol=", symbols)}"; - } - - if (timestamp.HasValue) - { - url += $"×tamp={timestamp}"; - } - - var response = await this._httpClient.GetAsync(url).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - return JsonConvert.DeserializeObject>(responseContent).Data; - } - - /// - /// Get the token balances of an address. - /// - /// The address to get the token balances of. - /// The chain IDs to get the token balances from. - /// Whether to include NFT metadata in the response. (Default: true) - /// A tuple containing the ERC20, ERC721, and ERC1155 tokens. - /// Thrown when the owner address is null or empty. - /// Thrown when no chain IDs are provided. - public async Task<(Token_ERC20[] erc20Tokens, Token_ERC721[] erc721Tokens, Token_ERC1155[] erc1155Tokens)> GetTokens(string ownerAddress, BigInteger[] chainIds, bool withMetadata = true) - { - if (string.IsNullOrEmpty(ownerAddress)) - { - throw new ArgumentNullException(nameof(ownerAddress)); - } - - if (chainIds.Length == 0) - { - throw new ArgumentException("At least one chain ID must be provided.", nameof(chainIds)); - } - - var erc20Tokens = await this.GetTokens_ERC20(ownerAddress, chainIds).ConfigureAwait(false); - var erc721Tokens = await this.GetTokens_ERC721(ownerAddress, chainIds, withMetadata: withMetadata).ConfigureAwait(false); - var erc1155Tokens = await this.GetTokens_ERC1155(ownerAddress, chainIds, withMetadata: withMetadata).ConfigureAwait(false); - return (erc20Tokens, erc721Tokens, erc1155Tokens); - } - - /// - /// Get the ERC20 tokens of an address. - /// - /// The address to get the ERC20 tokens of. - /// The chain IDs to get the ERC20 tokens from. - /// The number of tokens to return. (Default: 50) - /// The page number to return. (Default: 0) - /// An array of ERC20 tokens. - /// Thrown when the owner address is null or empty. - /// /// Thrown when no chain IDs are provided. - public async Task GetTokens_ERC20(string ownerAddress, BigInteger[] chainIds, int limit = 50, int page = 0) - { - if (string.IsNullOrEmpty(ownerAddress)) - { - throw new ArgumentNullException(nameof(ownerAddress)); - } - - if (chainIds.Length == 0) - { - throw new ArgumentException("At least one chain ID must be provided.", nameof(chainIds)); - } - - var url = AppendChains($"{Constants.INSIGHT_API_URL}/v1/tokens/erc20/{ownerAddress}", chainIds); - url += $"&limit={limit}"; - url += $"&page={page}"; - var response = await this._httpClient.GetAsync(url).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - return JsonConvert.DeserializeObject>(responseContent).Data; - } - - /// - /// Get the ERC721 tokens of an address. - /// - /// The address to get the ERC721 tokens of. - /// The chain IDs to get the ERC721 tokens from. - /// The number of tokens to return. (Default: 50) - /// The page number to return. (Default: 0) - /// Whether to include NFT metadata in the response. (Default: true) - /// An array of ERC721 tokens. - /// Thrown when the owner address is null or empty. - /// /// Thrown when no chain IDs are provided. - public async Task GetTokens_ERC721(string ownerAddress, BigInteger[] chainIds, int limit = 50, int page = 0, bool withMetadata = true) - { - if (string.IsNullOrEmpty(ownerAddress)) - { - throw new ArgumentNullException(nameof(ownerAddress)); - } - - if (chainIds.Length == 0) - { - throw new ArgumentException("At least one chain ID must be provided.", nameof(chainIds)); - } - - var url = AppendChains($"{Constants.INSIGHT_API_URL}/v1/tokens/erc721/{ownerAddress}", chainIds); - url += $"&limit={limit}"; - url += $"&page={page}"; - url += $"&metadata={withMetadata.ToString().ToLower()}"; - var response = await this._httpClient.GetAsync(url).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - return JsonConvert.DeserializeObject>(responseContent).Data; - } - - /// - /// Get the ERC1155 tokens of an address. - /// - /// The address to get the ERC1155 tokens of. - /// The chain IDs to get the ERC1155 tokens from. - /// The number of tokens to return. (Default: 50) - /// The page number to return. (Default: 0) - /// Whether to include NFT metadata in the response. (Default: true) - /// An array of ERC1155 tokens. - /// Thrown when the owner address is null or empty. - /// /// Thrown when no chain IDs are provided. - public async Task GetTokens_ERC1155(string ownerAddress, BigInteger[] chainIds, int limit = 50, int page = 0, bool withMetadata = true) - { - if (string.IsNullOrEmpty(ownerAddress)) - { - throw new ArgumentNullException(nameof(ownerAddress)); - } - - if (chainIds.Length == 0) - { - throw new ArgumentException("At least one chain ID must be provided.", nameof(chainIds)); - } - - var url = AppendChains($"{Constants.INSIGHT_API_URL}/v1/tokens/erc1155/{ownerAddress}", chainIds); - url += $"&limit={limit}"; - url += $"&page={page}"; - url += $"&metadata={withMetadata.ToString().ToLower()}"; - var response = await this._httpClient.GetAsync(url).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - return JsonConvert.DeserializeObject>(responseContent).Data; - } - - /// - /// Get events, optionally filtered by contract address, event signature, and more. - /// - /// The chain IDs to get the events from. - /// The contract address to get the events from. (Optional) - /// The event signature to get the events from. (Optional) - /// The starting block number to get the events from. (Optional, if provided, said block is included in query) - /// The ending block number to get the events from. (Optional, if provided, said block is included in query) - /// The starting block timestamp to get the events from. (Optional, if provided, said block is included in query) - /// The ending block timestamp to get the events from. (Optional, if provided, said block is included in query) - /// The field to sort the events by. (Default: BlockNumber) - /// The order to sort the events by. (Default: Desc) - /// The number of events to return. (Default: 20) - /// The page number to return. (Default: 0) - /// Whether to decode the events. (Default: true) - /// The events and metadata as an instance of . - /// Thrown when an event signature is provided without a contract address. - /// /// Thrown when no chain IDs are provided. - public async Task GetEvents( - BigInteger[] chainIds, - string contractAddress = null, - string eventSignature = null, - BigInteger? fromBlock = null, - BigInteger? toBlock = null, - BigInteger? fromTimestamp = null, - BigInteger? toTimestamp = null, - SortBy sortBy = SortBy.BlockNumber, - SortOrder sortOrder = SortOrder.Desc, - int limit = 20, - int page = 0, - bool decode = true - ) - { - if (!string.IsNullOrEmpty(eventSignature) && string.IsNullOrEmpty(contractAddress)) - { - throw new ArgumentException("Contract address must be provided when event signature is provided."); - } - - if (chainIds.Length == 0) - { - throw new ArgumentException("At least one chain ID must be provided.", nameof(chainIds)); - } - - var baseUrl = $"{Constants.INSIGHT_API_URL}/v1/events"; - var url = AppendChains( - !string.IsNullOrEmpty(contractAddress) - ? !string.IsNullOrEmpty(eventSignature) - ? $"{baseUrl}/{contractAddress}/{eventSignature}" - : $"{baseUrl}/{contractAddress}" - : baseUrl, - chainIds - ); - - url += $"&sort_by={SortByToString(sortBy)}"; - url += $"&sort_order={SortOrderToString(sortOrder)}"; - url += $"&limit={limit}"; - url += $"&page={page}"; - url += $"&decode={decode}"; - - if (fromBlock.HasValue) - { - url += $"&filter_block_number_gte={fromBlock}"; - } - - if (toBlock.HasValue) - { - url += $"&filter_block_number_lte={toBlock}"; - } - - if (fromTimestamp.HasValue) - { - url += $"&filter_block_timestamp_gte={fromTimestamp}"; - } - - if (toTimestamp.HasValue) - { - url += $"&filter_block_timestamp_lte={toTimestamp}"; - } - - var response = await this._httpClient.GetAsync(url).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - var result = JsonConvert.DeserializeObject>(responseContent); - return new InsightEvents { Events = result.Data, Meta = result.Meta }; - } - - /// - /// Get transactions, optionally filtered by contract address, signature, and more. - /// - /// The chain IDs to get the transactions from. - /// The contract address to get the transactions from. (Optional) - /// The signature to filter transactions by. (Optional) - /// The starting block number to get the transactions from. (Optional, if provided, said block is included in query) - /// The ending block number to get the transactions from. (Optional, if provided, said block is included in query) - /// The starting block timestamp to get the transactions from. (Optional, if provided, said block is included in query) - /// The ending block timestamp to get the transactions from. (Optional, if provided, said block is included in query) - /// The field to sort the transactions by. (Default: BlockNumber) - /// The order to sort the transactions by. (Default: Desc) - /// The number of transactions to return. (Default: 20) - /// The page number to return. (Default: 0) - /// Whether to decode the transactions. (Default: true) - /// The transactions and metadata as an instance of . - /// Thrown when a signature is provided without a contract address. - /// /// Thrown when no chain IDs are provided. - public async Task GetTransactions( - BigInteger[] chainIds, - string contractAddress = null, - string signature = null, - BigInteger? fromBlock = null, - BigInteger? toBlock = null, - BigInteger? fromTimestamp = null, - BigInteger? toTimestamp = null, - SortBy sortBy = SortBy.BlockNumber, - SortOrder sortOrder = SortOrder.Desc, - int limit = 20, - int page = 0, - bool decode = true - ) - { - if (!string.IsNullOrEmpty(signature) && string.IsNullOrEmpty(contractAddress)) - { - throw new ArgumentException("Contract address must be provided when signature is provided."); - } - - if (chainIds.Length == 0) - { - throw new ArgumentException("At least one chain ID must be provided.", nameof(chainIds)); - } - - var baseUrl = $"{Constants.INSIGHT_API_URL}/v1/transactions"; - var url = AppendChains( - !string.IsNullOrEmpty(contractAddress) - ? !string.IsNullOrEmpty(signature) - ? $"{baseUrl}/{contractAddress}/{signature}" - : $"{baseUrl}/{contractAddress}" - : baseUrl, - chainIds - ); - - url += $"&sort_by={SortByToString(sortBy)}"; - url += $"&sort_order={SortOrderToString(sortOrder)}"; - url += $"&limit={limit}"; - url += $"&page={page}"; - url += $"&decode={decode}"; - - if (fromBlock.HasValue) - { - url += $"&filter_block_number_gte={fromBlock}"; - } - - if (toBlock.HasValue) - { - url += $"&filter_block_number_lte={toBlock}"; - } - - if (fromTimestamp.HasValue) - { - url += $"&filter_block_timestamp_gte={fromTimestamp}"; - } - - if (toTimestamp.HasValue) - { - url += $"&filter_block_timestamp_lte={toTimestamp}"; - } - - var response = await this._httpClient.GetAsync(url).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - var result = JsonConvert.DeserializeObject>(responseContent); - return new InsightTransactions { Transactions = result.Data, Meta = result.Meta }; - } - - private static string AppendChains(string url, BigInteger[] chainIds) - { - return $"{url}?chain={string.Join("&chain=", chainIds)}"; - } - - private static string SortByToString(SortBy sortBy) - { - return sortBy switch - { - SortBy.BlockNumber => "block_number", - SortBy.BlockTimestamp => "block_timestamp", - SortBy.TransactionIndex => "transaction_index", - _ => throw new ArgumentOutOfRangeException(nameof(sortBy), sortBy, null), - }; - } - - private static string SortOrderToString(SortOrder sortOrder) - { - return sortOrder switch - { - SortOrder.Asc => "asc", - SortOrder.Desc => "desc", - _ => throw new ArgumentOutOfRangeException(nameof(sortOrder), sortOrder, null), - }; - } -} diff --git a/Thirdweb/Thirdweb.Pay/ThirdwebPay.BuyWithCrypto.cs b/Thirdweb/Thirdweb.Pay/ThirdwebPay.BuyWithCrypto.cs deleted file mode 100644 index 492a6112..00000000 --- a/Thirdweb/Thirdweb.Pay/ThirdwebPay.BuyWithCrypto.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System.Numerics; -using Nethereum.Hex.HexTypes; - -namespace Thirdweb.Pay; - -/// -/// Provides methods for processing payments with cryptocurrency. -/// -public partial class ThirdwebPay -{ - /// - /// Initiates a cryptocurrency purchase using the provided wallet and quote. - /// - /// The wallet to use for the purchase. - /// The quote result containing transaction details. - /// A task that represents the asynchronous operation. The task result contains the transaction hash. - public static async Task BuyWithCrypto(IThirdwebWallet wallet, BuyWithCryptoQuoteResult buyWithCryptoQuote) - { - if (buyWithCryptoQuote.Approval != null) - { - var erc20ToApprove = await ThirdwebContract.Create(wallet.Client, buyWithCryptoQuote.Approval.TokenAddress, buyWithCryptoQuote.Approval.ChainId); - var currentAllowance = await erc20ToApprove.ERC20_Allowance(await wallet.GetAddress(), buyWithCryptoQuote.Approval.SpenderAddress); - if (currentAllowance < BigInteger.Parse(buyWithCryptoQuote.Approval.AmountWei)) - { - _ = await erc20ToApprove.ERC20_Approve(wallet, buyWithCryptoQuote.Approval.SpenderAddress, BigInteger.Parse(buyWithCryptoQuote.Approval.AmountWei)); - } - } - - var txInput = new ThirdwebTransactionInput(chainId: buyWithCryptoQuote.TransactionRequest.ChainId) - { - To = buyWithCryptoQuote.TransactionRequest.To, - Data = buyWithCryptoQuote.TransactionRequest.Data, - Value = new HexBigInteger(BigInteger.Parse(buyWithCryptoQuote.TransactionRequest.Value)), - Gas = new HexBigInteger(BigInteger.Parse(buyWithCryptoQuote.TransactionRequest.GasLimit)), - GasPrice = new HexBigInteger(BigInteger.Parse(buyWithCryptoQuote.TransactionRequest.GasPrice)), - }; - - var tx = await ThirdwebTransaction.Create(wallet, txInput); - - var hash = await ThirdwebTransaction.Send(tx); - - return hash; - } -} diff --git a/Thirdweb/Thirdweb.Pay/ThirdwebPay.BuyWithFiat.cs b/Thirdweb/Thirdweb.Pay/ThirdwebPay.BuyWithFiat.cs deleted file mode 100644 index 83f4446c..00000000 --- a/Thirdweb/Thirdweb.Pay/ThirdwebPay.BuyWithFiat.cs +++ /dev/null @@ -1,25 +0,0 @@ -namespace Thirdweb.Pay; - -/// -/// Provides methods for processing payments with cryptocurrency and fiat. -/// -public partial class ThirdwebPay -{ - /// - /// Initiates a purchase using fiat currency through an on-ramp service. - /// - /// The quote result containing the on-ramp link. - /// The on-ramp link for the fiat purchase. - /// Thrown if the on-ramp link is null or empty. - public static string BuyWithFiat(BuyWithFiatQuoteResult buyWithFiatQuote) - { - if (string.IsNullOrEmpty(buyWithFiatQuote.OnRampLink)) - { - throw new ArgumentException("On-ramp link cannot be null or empty."); - } - - var onRampLink = buyWithFiatQuote.OnRampLink; - - return onRampLink; - } -} diff --git a/Thirdweb/Thirdweb.Pay/ThirdwebPay.GetBuyHistory.cs b/Thirdweb/Thirdweb.Pay/ThirdwebPay.GetBuyHistory.cs deleted file mode 100644 index a2db51dc..00000000 --- a/Thirdweb/Thirdweb.Pay/ThirdwebPay.GetBuyHistory.cs +++ /dev/null @@ -1,68 +0,0 @@ -using Newtonsoft.Json; - -namespace Thirdweb.Pay; - -/// -/// Provides methods for processing payments with cryptocurrency and fiat. -/// -public partial class ThirdwebPay -{ - /// - /// Retrieves the buy history for a specified wallet address. - /// - /// The Thirdweb client. - /// The wallet address to retrieve history for. - /// The start index for the history. - /// The number of history records to retrieve. - /// The cursor for pagination (optional). - /// The page size for pagination (optional). - /// A task that represents the asynchronous operation. The task result contains the buy history result. - /// Thrown if the HTTP response is not successful. - public static async Task GetBuyHistory(ThirdwebClient client, string walletAddress, int start, int count, string cursor = null, int? pageSize = null) - { - var queryString = new Dictionary - { - { "walletAddress", walletAddress }, - { "start", start.ToString() }, - { "count", count.ToString() }, - { "cursor", cursor }, - { "pageSize", pageSize?.ToString() }, - }; - - var queryStringFormatted = string.Join("&", queryString.Where(kv => kv.Value != null).Select(kv => $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value)}")); - var url = $"{THIRDWEB_PAY_HISTORY_ENDPOINT}?{queryStringFormatted}"; - - var getResponse = await client.HttpClient.GetAsync(url); - - var content = await getResponse.Content.ReadAsStringAsync(); - - if (!getResponse.IsSuccessStatusCode) - { - ErrorResponse error; - - try - { - error = JsonConvert.DeserializeObject(content); - } - catch - { - error = new ErrorResponse - { - Error = new ErrorDetails - { - Message = "Unknown error", - Reason = "Unknown", - Code = "Unknown", - Stack = "Unknown", - StatusCode = (int)getResponse.StatusCode, - }, - }; - } - - throw new Exception($"HTTP error! Code: {error.Error.Code} Message: {error.Error.Message} Reason: {error.Error.Reason} StatusCode: {error.Error.StatusCode} Stack: {error.Error.Stack}"); - } - - var data = JsonConvert.DeserializeObject(content); - return data.Result; - } -} diff --git a/Thirdweb/Thirdweb.Pay/ThirdwebPay.GetBuyWithCryptoQuote.cs b/Thirdweb/Thirdweb.Pay/ThirdwebPay.GetBuyWithCryptoQuote.cs deleted file mode 100644 index 544b5763..00000000 --- a/Thirdweb/Thirdweb.Pay/ThirdwebPay.GetBuyWithCryptoQuote.cs +++ /dev/null @@ -1,58 +0,0 @@ -using Newtonsoft.Json; - -namespace Thirdweb.Pay; - -/// -/// Provides methods for processing payments with cryptocurrency and fiat. -/// -public partial class ThirdwebPay -{ - /// - /// Retrieves a quote for buying with cryptocurrency using the provided parameters. - /// - /// The Thirdweb client. - /// The parameters for the crypto purchase. - /// A task that represents the asynchronous operation. The task result contains the quote result. - /// Thrown if the HTTP response is not successful. - public static async Task GetBuyWithCryptoQuote(ThirdwebClient client, BuyWithCryptoQuoteParams buyWithCryptoParams) - { - var response = await client.HttpClient.PostAsync( - THIRDWEB_PAY_CRYPTO_QUOTE_ENDPOINT, - new StringContent( - JsonConvert.SerializeObject(buyWithCryptoParams, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }), - System.Text.Encoding.UTF8, - "application/json" - ) - ); - - var content = await response.Content.ReadAsStringAsync(); - - if (!response.IsSuccessStatusCode) - { - ErrorResponse error; - try - { - error = JsonConvert.DeserializeObject(content); - } - catch - { - error = new ErrorResponse - { - Error = new ErrorDetails - { - Message = "Unknown error", - Reason = "Unknown", - Code = "Unknown", - Stack = "Unknown", - StatusCode = (int)response.StatusCode, - }, - }; - } - - throw new Exception($"HTTP error! Code: {error.Error.Code} Message: {error.Error.Message} Reason: {error.Error.Reason} StatusCode: {error.Error.StatusCode} Stack: {error.Error.Stack}"); - } - - var data = JsonConvert.DeserializeObject(content); - return data.Result; - } -} diff --git a/Thirdweb/Thirdweb.Pay/ThirdwebPay.GetBuyWithCryptoStatus.cs b/Thirdweb/Thirdweb.Pay/ThirdwebPay.GetBuyWithCryptoStatus.cs deleted file mode 100644 index f8123241..00000000 --- a/Thirdweb/Thirdweb.Pay/ThirdwebPay.GetBuyWithCryptoStatus.cs +++ /dev/null @@ -1,62 +0,0 @@ -using Newtonsoft.Json; - -namespace Thirdweb.Pay; - -/// -/// Provides methods for processing payments with cryptocurrency and fiat. -/// -public partial class ThirdwebPay -{ - /// - /// Retrieves the status of a cryptocurrency purchase using the transaction hash. - /// - /// The Thirdweb client. - /// The transaction hash to check the status of. - /// A task that represents the asynchronous operation. The task result contains the status result. - /// Thrown if the transaction hash is null or empty. - /// Thrown if the HTTP response is not successful. - public static async Task GetBuyWithCryptoStatus(ThirdwebClient client, string transactionHash) - { - if (string.IsNullOrEmpty(transactionHash)) - { - throw new ArgumentException(nameof(transactionHash), "Transaction hash cannot be null or empty."); - } - - var queryString = new Dictionary { { "transactionHash", transactionHash } }; - - var queryStringFormatted = string.Join("&", queryString.Where(kv => kv.Value != null).Select(kv => $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value)}")); - var url = $"{THIRDWEB_PAY_CRYPTO_STATUS_ENDPOINT}?{queryStringFormatted}"; - - var getResponse = await client.HttpClient.GetAsync(url); - - var content = await getResponse.Content.ReadAsStringAsync(); - - if (!getResponse.IsSuccessStatusCode) - { - ErrorResponse error; - try - { - error = JsonConvert.DeserializeObject(content); - } - catch - { - error = new ErrorResponse - { - Error = new ErrorDetails - { - Message = "Unknown error", - Reason = "Unknown", - Code = "Unknown", - Stack = "Unknown", - StatusCode = (int)getResponse.StatusCode, - }, - }; - } - - throw new Exception($"HTTP error! Code: {error.Error.Code} Message: {error.Error.Message} Reason: {error.Error.Reason} StatusCode: {error.Error.StatusCode} Stack: {error.Error.Stack}"); - } - - var data = JsonConvert.DeserializeObject(content); - return data.Result; - } -} diff --git a/Thirdweb/Thirdweb.Pay/ThirdwebPay.GetBuyWithFiatCurrencies.cs b/Thirdweb/Thirdweb.Pay/ThirdwebPay.GetBuyWithFiatCurrencies.cs deleted file mode 100644 index a2865d7b..00000000 --- a/Thirdweb/Thirdweb.Pay/ThirdwebPay.GetBuyWithFiatCurrencies.cs +++ /dev/null @@ -1,52 +0,0 @@ -using Newtonsoft.Json; - -namespace Thirdweb.Pay; - -/// -/// Provides methods for processing payments with cryptocurrency and fiat. -/// -public partial class ThirdwebPay -{ - /// - /// Retrieves the list of supported fiat currencies for buying with fiat. - /// - /// The Thirdweb client. - /// A task that represents the asynchronous operation. The task result contains the list of supported fiat currencies. - /// Thrown if the HTTP response is not successful. - public static async Task> GetBuyWithFiatCurrencies(ThirdwebClient client) - { - var url = $"{THIRDWEB_PAY_FIAT_CURRENCIES_ENDPOINT}"; - - var getResponse = await client.HttpClient.GetAsync(url); - - var content = await getResponse.Content.ReadAsStringAsync(); - - if (!getResponse.IsSuccessStatusCode) - { - ErrorResponse error; - try - { - error = JsonConvert.DeserializeObject(content); - } - catch - { - error = new ErrorResponse - { - Error = new ErrorDetails - { - Message = "Unknown error", - Reason = "Unknown", - Code = "Unknown", - Stack = "Unknown", - StatusCode = (int)getResponse.StatusCode, - }, - }; - } - - throw new Exception($"HTTP error! Code: {error.Error.Code} Message: {error.Error.Message} Reason: {error.Error.Reason} StatusCode: {error.Error.StatusCode} Stack: {error.Error.Stack}"); - } - - var data = JsonConvert.DeserializeObject(content); - return data.Result.FiatCurrencies; - } -} diff --git a/Thirdweb/Thirdweb.Pay/ThirdwebPay.GetBuyWithFiatQuote.cs b/Thirdweb/Thirdweb.Pay/ThirdwebPay.GetBuyWithFiatQuote.cs deleted file mode 100644 index ae0ff05b..00000000 --- a/Thirdweb/Thirdweb.Pay/ThirdwebPay.GetBuyWithFiatQuote.cs +++ /dev/null @@ -1,58 +0,0 @@ -using Newtonsoft.Json; - -namespace Thirdweb.Pay; - -/// -/// Provides methods for processing payments with cryptocurrency and fiat. -/// -public partial class ThirdwebPay -{ - /// - /// Retrieves a quote for buying with fiat using the provided parameters. - /// - /// The Thirdweb client. - /// The parameters for the fiat purchase. - /// A task that represents the asynchronous operation. The task result contains the quote result. - /// Thrown if the HTTP response is not successful. - public static async Task GetBuyWithFiatQuote(ThirdwebClient client, BuyWithFiatQuoteParams buyWithFiatParams) - { - var response = await client.HttpClient.PostAsync( - THIRDWEB_PAY_FIAT_QUOTE_ENDPOINT, - new StringContent( - JsonConvert.SerializeObject(buyWithFiatParams, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }), - System.Text.Encoding.UTF8, - "application/json" - ) - ); - - var content = await response.Content.ReadAsStringAsync(); - - if (!response.IsSuccessStatusCode) - { - ErrorResponse error; - try - { - error = JsonConvert.DeserializeObject(content); - } - catch - { - error = new ErrorResponse - { - Error = new ErrorDetails - { - Message = "Unknown error", - Reason = "Unknown", - Code = "Unknown", - Stack = "Unknown", - StatusCode = (int)response.StatusCode, - }, - }; - } - - throw new Exception($"HTTP error! Code: {error.Error.Code} Message: {error.Error.Message} Reason: {error.Error.Reason} StatusCode: {error.Error.StatusCode} Stack: {error.Error.Stack}"); - } - - var data = JsonConvert.DeserializeObject(content); - return data.Result; - } -} diff --git a/Thirdweb/Thirdweb.Pay/ThirdwebPay.GetBuyWithFiatStatus.cs b/Thirdweb/Thirdweb.Pay/ThirdwebPay.GetBuyWithFiatStatus.cs deleted file mode 100644 index 00fbbf27..00000000 --- a/Thirdweb/Thirdweb.Pay/ThirdwebPay.GetBuyWithFiatStatus.cs +++ /dev/null @@ -1,62 +0,0 @@ -using Newtonsoft.Json; - -namespace Thirdweb.Pay; - -/// -/// Provides methods for processing payments with cryptocurrency and fiat. -/// -public partial class ThirdwebPay -{ - /// - /// Retrieves the status of a fiat purchase using the intent ID. - /// - /// The Thirdweb client. - /// The intent ID to check the status of. - /// A task that represents the asynchronous operation. The task result contains the status result. - /// Thrown if the intent ID is null or empty. - /// Thrown if the HTTP response is not successful. - public static async Task GetBuyWithFiatStatus(ThirdwebClient client, string intentId) - { - if (string.IsNullOrEmpty(intentId)) - { - throw new ArgumentException(nameof(intentId), "Intent ID cannot be null or empty."); - } - - var queryString = new Dictionary { { "intentId", intentId } }; - - var queryStringFormatted = string.Join("&", queryString.Where(kv => kv.Value != null).Select(kv => $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value)}")); - var url = $"{THIRDWEB_PAY_FIAT_STATUS_ENDPOINT}?{queryStringFormatted}"; - - var getResponse = await client.HttpClient.GetAsync(url); - - var content = await getResponse.Content.ReadAsStringAsync(); - - if (!getResponse.IsSuccessStatusCode) - { - ErrorResponse error; - try - { - error = JsonConvert.DeserializeObject(content); - } - catch - { - error = new ErrorResponse - { - Error = new ErrorDetails - { - Message = "Unknown error", - Reason = "Unknown", - Code = "Unknown", - Stack = "Unknown", - StatusCode = (int)getResponse.StatusCode, - }, - }; - } - - throw new Exception($"HTTP error! Code: {error.Error.Code} Message: {error.Error.Message} Reason: {error.Error.Reason} StatusCode: {error.Error.StatusCode} Stack: {error.Error.Stack}"); - } - - var data = JsonConvert.DeserializeObject(content); - return data.Result; - } -} diff --git a/Thirdweb/Thirdweb.Pay/ThirdwebPay.cs b/Thirdweb/Thirdweb.Pay/ThirdwebPay.cs deleted file mode 100644 index f493cc28..00000000 --- a/Thirdweb/Thirdweb.Pay/ThirdwebPay.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace Thirdweb.Pay; - -[Obsolete("This class is deprecated, please use ThirdwebBridge instead.")] -public partial class ThirdwebPay -{ - private const string THIRDWEB_PAY_BASE_URL = "https://pay.thirdweb.com"; - - private const string THIRDWEB_PAY_CRYPTO_QUOTE_ENDPOINT = THIRDWEB_PAY_BASE_URL + "/buy-with-crypto/quote/v1"; - private const string THIRDWEB_PAY_CRYPTO_STATUS_ENDPOINT = THIRDWEB_PAY_BASE_URL + "/buy-with-crypto/status/v1"; - - private const string THIRDWEB_PAY_FIAT_QUOTE_ENDPOINT = THIRDWEB_PAY_BASE_URL + "/buy-with-fiat/quote/v1"; - private const string THIRDWEB_PAY_FIAT_STATUS_ENDPOINT = THIRDWEB_PAY_BASE_URL + "/buy-with-fiat/status/v1"; - - private const string THIRDWEB_PAY_FIAT_CURRENCIES_ENDPOINT = THIRDWEB_PAY_BASE_URL + "/buy-with-fiat/currency/v1"; - - private const string THIRDWEB_PAY_HISTORY_ENDPOINT = THIRDWEB_PAY_BASE_URL + "/wallet/history/v1"; -} diff --git a/Thirdweb/Thirdweb.Pay/Types.GetBuyHistory.cs b/Thirdweb/Thirdweb.Pay/Types.GetBuyHistory.cs deleted file mode 100644 index 3244501d..00000000 --- a/Thirdweb/Thirdweb.Pay/Types.GetBuyHistory.cs +++ /dev/null @@ -1,63 +0,0 @@ -using Newtonsoft.Json; - -namespace Thirdweb.Pay; - -/// -/// Represents the response for buy history. -/// -public class BuyHistoryResponse -{ - /// - /// Gets or sets the result of the buy history. - /// - [JsonProperty("result")] - public BuyHistoryResult Result { get; set; } -} - -/// -/// Represents the result of the buy history. -/// -public class BuyHistoryResult -{ - /// - /// Gets or sets the wallet address. - /// - [JsonProperty("walletAddress")] - public string WalletAddress { get; set; } - - /// - /// Gets or sets the list of history pages. - /// - [JsonProperty("page")] - public List Page { get; set; } - - /// - /// Gets or sets the next cursor for pagination. - /// - [JsonProperty("nextCursor")] - public string NextCursor { get; set; } - - /// - /// Gets or sets the page size. - /// - [JsonProperty("pageSize")] - public int PageSize { get; set; } -} - -/// -/// Represents a page in the buy history. -/// -public class HistoryPage -{ - /// - /// Gets or sets the status of the buy with crypto transaction. - /// - [JsonProperty("buyWithCryptoStatus")] - public BuyWithCryptoStatusResult BuyWithCryptoStatus { get; set; } - - /// - /// Gets or sets the status of the buy with fiat transaction. - /// - [JsonProperty("buyWithFiatStatus")] - public BuyWithFiatStatusResult BuyWithFiatStatus { get; set; } -} diff --git a/Thirdweb/Thirdweb.Pay/Types.GetBuyWithCryptoQuote.cs b/Thirdweb/Thirdweb.Pay/Types.GetBuyWithCryptoQuote.cs deleted file mode 100644 index 1cb75f21..00000000 --- a/Thirdweb/Thirdweb.Pay/Types.GetBuyWithCryptoQuote.cs +++ /dev/null @@ -1,369 +0,0 @@ -using System.Numerics; -using Newtonsoft.Json; - -namespace Thirdweb.Pay; - -/// -/// Parameters for getting a quote for buying with cryptocurrency. -/// -/// -/// Initializes a new instance of the class. -/// -public class BuyWithCryptoQuoteParams( - string fromAddress, - BigInteger? fromChainId, - string fromTokenAddress, - string toTokenAddress, - string fromAmount = null, - string fromAmountWei = null, - BigInteger? toChainId = null, - string toAmount = null, - string toAmountWei = null, - string toAddress = null, - double? maxSlippageBPS = null, - string intentId = null, - object purchaseData = null -) -{ - /// - /// The address from which the payment is made. - /// - [JsonProperty("fromAddress")] - public string FromAddress { get; set; } = fromAddress; - - /// - /// The chain ID of the source token. - /// - [JsonProperty("fromChainId")] - public BigInteger? FromChainId { get; set; } = fromChainId; - - /// - /// The address of the source token. - /// - [JsonProperty("fromTokenAddress")] - public string FromTokenAddress { get; set; } = fromTokenAddress; - - /// - /// The amount of the source token. - /// - [JsonProperty("fromAmount")] - public string FromAmount { get; set; } = fromAmount; - - /// - /// The amount of the source token in wei. - /// - [JsonProperty("fromAmountWei")] - public string FromAmountWei { get; set; } = fromAmountWei; - - /// - /// The chain ID of the destination token. - /// - [JsonProperty("toChainId")] - public BigInteger? ToChainId { get; set; } = toChainId; - - /// - /// The address of the destination token. - /// - [JsonProperty("toTokenAddress")] - public string ToTokenAddress { get; set; } = toTokenAddress; - - /// - /// The amount of the destination token. - /// - [JsonProperty("toAmount")] - public string ToAmount { get; set; } = toAmount; - - /// - /// The amount of the destination token in wei. - /// - [JsonProperty("toAmountWei")] - public string ToAmountWei { get; set; } = toAmountWei; - - /// - /// The address of the recipient. - /// - [JsonProperty("toAddress")] - public string ToAddress { get; set; } = toAddress; - - /// - /// The maximum slippage in basis points. - /// - [JsonProperty("maxSlippageBPS")] - public double? MaxSlippageBPS { get; set; } = maxSlippageBPS; - - /// - /// The intent ID for the transaction. - /// - [JsonProperty("intentId")] - public string IntentId { get; set; } = intentId; - - /// - /// Additional data for the purchase. Useful with direct transfer flow. - /// - [JsonProperty("purchaseData")] - public object PurchaseData { get; set; } = purchaseData; -} - -/// -/// Represents a transaction request. -/// -public class TransactionRequest -{ - /// - /// Gets or sets the data of the transaction. - /// - [JsonProperty("data")] - public string Data { get; set; } - - /// - /// Gets or sets the recipient address of the transaction. - /// - [JsonProperty("to")] - public string To { get; set; } - - /// - /// Gets or sets the value of the transaction. - /// - [JsonProperty("value")] - public string Value { get; set; } - - /// - /// Gets or sets the sender address of the transaction. - /// - [JsonProperty("from")] - public string From { get; set; } - - /// - /// Gets or sets the chain ID of the transaction. - /// - [JsonProperty("chainId")] - public BigInteger ChainId { get; set; } - - /// - /// Gets or sets the gas price of the transaction. - /// - [JsonProperty("gasPrice")] - public string GasPrice { get; set; } - - /// - /// Gets or sets the gas limit of the transaction. - /// - [JsonProperty("gasLimit")] - public string GasLimit { get; set; } -} - -/// -/// Represents an approval request. -/// -public class Approval -{ - /// - /// Gets or sets the chain ID of the approval request. - /// - [JsonProperty("chainId")] - public BigInteger ChainId { get; set; } - - /// - /// Gets or sets the token address for the approval request. - /// - [JsonProperty("tokenAddress")] - public string TokenAddress { get; set; } - - /// - /// Gets or sets the spender address for the approval request. - /// - [JsonProperty("spenderAddress")] - public string SpenderAddress { get; set; } - - /// - /// Gets or sets the amount in wei for the approval request. - /// - [JsonProperty("amountWei")] - public string AmountWei { get; set; } -} - -/// -/// Represents a payment token. -/// -public class PaymentToken -{ - /// - /// Gets or sets the token details. - /// - [JsonProperty("token")] - public Token Token { get; set; } - - /// - /// Gets or sets the amount in wei. - /// - [JsonProperty("amountWei")] - public string AmountWei { get; set; } - - /// - /// Gets or sets the amount. - /// - [JsonProperty("amount")] - public string Amount { get; set; } - - /// - /// Gets or sets the amount in USD cents. - /// - [JsonProperty("amountUSDCents")] - public double AmountUSDCents { get; set; } -} - -/// -/// Represents a processing fee. -/// -public class ProcessingFee -{ - /// - /// Gets or sets the token details. - /// - [JsonProperty("token")] - public Token Token { get; set; } - - /// - /// Gets or sets the amount in wei. - /// - [JsonProperty("amountWei")] - public string AmountWei { get; set; } - - /// - /// Gets or sets the amount. - /// - [JsonProperty("amount")] - public string Amount { get; set; } - - /// - /// Gets or sets the amount in USD cents. - /// - [JsonProperty("amountUSDCents")] - public double AmountUSDCents { get; set; } -} - -/// -/// Represents the result of a quote for buying with cryptocurrency. -/// -public class BuyWithCryptoQuoteResult -{ - /// - /// Gets or sets the quote ID. - /// - [JsonProperty("quoteId")] - public string QuoteId { get; set; } - - /// - /// Gets or sets the transaction request. - /// - [JsonProperty("transactionRequest")] - public TransactionRequest TransactionRequest { get; set; } - - /// - /// Gets or sets the approval details. - /// - [JsonProperty("approval")] - public Approval Approval { get; set; } - - /// - /// Gets or sets the address from which the payment is made. - /// - [JsonProperty("fromAddress")] - public string FromAddress { get; set; } - - /// - /// Gets or sets the recipient address. - /// - [JsonProperty("toAddress")] - public string ToAddress { get; set; } - - /// - /// Gets or sets the details of the source token. - /// - [JsonProperty("fromToken")] - public Token FromToken { get; set; } - - /// - /// Gets or sets the details of the destination token. - /// - [JsonProperty("toToken")] - public Token ToToken { get; set; } - - /// - /// Gets or sets the amount of the source token in wei. - /// - [JsonProperty("fromAmountWei")] - public string FromAmountWei { get; set; } - - /// - /// Gets or sets the amount of the source token. - /// - [JsonProperty("fromAmount")] - public string FromAmount { get; set; } - - /// - /// Gets or sets the minimum amount of the destination token in wei. - /// - [JsonProperty("toAmountMinWei")] - public string ToAmountMinWei { get; set; } - - /// - /// Gets or sets the minimum amount of the destination token. - /// - [JsonProperty("toAmountMin")] - public string ToAmountMin { get; set; } - - /// - /// Gets or sets the amount of the destination token in wei. - /// - [JsonProperty("toAmountWei")] - public string ToAmountWei { get; set; } - - /// - /// Gets or sets the amount of the destination token. - /// - [JsonProperty("toAmount")] - public string ToAmount { get; set; } - - /// - /// Gets or sets the list of payment tokens. - /// - [JsonProperty("paymentTokens")] - public List PaymentTokens { get; set; } - - /// - /// Gets or sets the list of processing fees. - /// - [JsonProperty("processingFees")] - public List ProcessingFees { get; set; } - - /// - /// Gets or sets the estimated details. - /// - [JsonProperty("estimated")] - public Estimated Estimated { get; set; } - - /// - /// Gets or sets the maximum slippage in basis points. - /// - [JsonProperty("maxSlippageBPS")] - public double MaxSlippageBPS { get; set; } - - /// - /// Gets or sets the bridge details. - /// - [JsonProperty("bridge")] - public string Bridge { get; set; } -} - -/// -/// Represents the response for getting a swap quote. -/// -public class GetSwapQuoteResponse -{ - /// - /// Gets or sets the result of the swap quote. - /// - [JsonProperty("result")] - public BuyWithCryptoQuoteResult Result { get; set; } -} diff --git a/Thirdweb/Thirdweb.Pay/Types.GetBuyWithCryptoStatus.cs b/Thirdweb/Thirdweb.Pay/Types.GetBuyWithCryptoStatus.cs deleted file mode 100644 index 5778cc44..00000000 --- a/Thirdweb/Thirdweb.Pay/Types.GetBuyWithCryptoStatus.cs +++ /dev/null @@ -1,268 +0,0 @@ -using Newtonsoft.Json; - -namespace Thirdweb.Pay; - -/// -/// Represents the response for a swap status. -/// -public class SwapStatusResponse -{ - /// - /// Gets or sets the result of the swap status. - /// - [JsonProperty("result")] - public BuyWithCryptoStatusResult Result { get; set; } -} - -/// -/// Represents the status result of buying with cryptocurrency. -/// -public class BuyWithCryptoStatusResult -{ - /// - /// Gets or sets the swap quote details. - /// - [JsonProperty("quote")] - public SwapQuote Quote { get; set; } - - /// - /// Gets or sets the type of swap. - /// - [JsonProperty("swapType")] - public string SwapType { get; set; } - - /// - /// Gets or sets the source transaction details. - /// - [JsonProperty("source")] - public TransactionDetails Source { get; set; } - - /// - /// Gets or sets the destination transaction details. - /// - [JsonProperty("destination")] - public TransactionDetails Destination { get; set; } - - /// - /// Gets or sets the status of the swap. - /// - [JsonProperty("status")] - public string Status { get; set; } - - /// - /// Gets or sets the sub-status of the swap. - /// - [JsonProperty("subStatus")] - public string SubStatus { get; set; } - - /// - /// Gets or sets the address from which the swap is initiated. - /// - [JsonProperty("fromAddress")] - public string FromAddress { get; set; } - - /// - /// Gets or sets the recipient address. - /// - [JsonProperty("toAddress")] - public string ToAddress { get; set; } - - /// - /// Gets or sets the failure message if the swap fails. - /// - [JsonProperty("failureMessage")] - public string FailureMessage { get; set; } - - /// - /// Gets or sets the bridge details. - /// - [JsonProperty("bridge")] - public string Bridge { get; set; } - - /// - /// Additional data for the purchase. Useful with direct transfer flow. - /// - [JsonProperty("purchaseData")] - public object PurchaseData { get; set; } -} - -/// -/// Represents the transaction details. -/// -public class TransactionDetails -{ - /// - /// Gets or sets the transaction hash. - /// - [JsonProperty("transactionHash")] - public string TransactionHash { get; set; } - - /// - /// Gets or sets the token details. - /// - [JsonProperty("token")] - public Token Token { get; set; } - - /// - /// Gets or sets the amount of the token. - /// - [JsonProperty("amount")] - public string Amount { get; set; } - - /// - /// Gets or sets the amount of the token in wei. - /// - [JsonProperty("amountWei")] - public string AmountWei { get; set; } - - /// - /// Gets or sets the amount in USD cents. - /// - [JsonProperty("amountUSDCents")] - public double AmountUSDCents { get; set; } - - /// - /// Gets or sets the completion date of the transaction. - /// - [JsonProperty("completedAt")] - public DateTime CompletedAt { get; set; } - - /// - /// Gets or sets the explorer link for the transaction. - /// - [JsonProperty("explorerLink")] - public string ExplorerLink { get; set; } -} - -/// -/// Represents a swap quote. -/// -public class SwapQuote -{ - /// - /// Gets or sets the source token details. - /// - [JsonProperty("fromToken")] - public Token FromToken { get; set; } - - /// - /// Gets or sets the destination token details. - /// - [JsonProperty("toToken")] - public Token ToToken { get; set; } - - /// - /// Gets or sets the amount of the source token in wei. - /// - [JsonProperty("fromAmountWei")] - public string FromAmountWei { get; set; } - - /// - /// Gets or sets the amount of the source token. - /// - [JsonProperty("fromAmount")] - public string FromAmount { get; set; } - - /// - /// Gets or sets the amount of the destination token in wei. - /// - [JsonProperty("toAmountWei")] - public string ToAmountWei { get; set; } - - /// - /// Gets or sets the amount of the destination token. - /// - [JsonProperty("toAmount")] - public string ToAmount { get; set; } - - /// - /// Gets or sets the minimum amount of the destination token. - /// - [JsonProperty("toAmountMin")] - public string ToAmountMin { get; set; } - - /// - /// Gets or sets the minimum amount of the destination token in wei. - /// - [JsonProperty("toAmountMinWei")] - public string ToAmountMinWei { get; set; } - - /// - /// Gets or sets the estimated details. - /// - [JsonProperty("estimated")] - public Estimated Estimated { get; set; } - - /// - /// Gets or sets the creation date of the swap quote. - /// - [JsonProperty("createdAt")] - public DateTime CreatedAt { get; set; } -} - -/// -/// Represents the swap status. -/// -public enum SwapStatus -{ - /// - /// Status when the swap is not found. - /// - NOT_FOUND, - - /// - /// Status when there is no swap. - /// - NONE, - - /// - /// Status when the swap is pending. - /// - PENDING, - - /// - /// Status when the swap has failed. - /// - FAILED, - - /// - /// Status when the swap is completed. - /// - COMPLETED, -} - -/// -/// Represents the swap sub-status. -/// -public enum SwapSubStatus -{ - /// - /// Sub-status when there is no specific sub-status. - /// - NONE, - - /// - /// Sub-status when waiting for the bridge. - /// - WAITING_BRIDGE, - - /// - /// Sub-status when the swap is reverted on chain. - /// - REVERTED_ON_CHAIN, - - /// - /// Sub-status when the swap is successful. - /// - SUCCESS, - - /// - /// Sub-status when the swap is partially successful. - /// - PARTIAL_SUCCESS, - - /// - /// Sub-status when there is an unknown error. - /// - UNKNOWN_ERROR, -} diff --git a/Thirdweb/Thirdweb.Pay/Types.GetBuyWithFiatCurrencies.cs b/Thirdweb/Thirdweb.Pay/Types.GetBuyWithFiatCurrencies.cs deleted file mode 100644 index 1763c296..00000000 --- a/Thirdweb/Thirdweb.Pay/Types.GetBuyWithFiatCurrencies.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Newtonsoft.Json; - -namespace Thirdweb.Pay; - -/// -/// Represents the response for fiat currencies. -/// -public class FiatCurrenciesResponse -{ - /// - /// Gets or sets the result of the fiat currencies response. - /// - [JsonProperty("result")] - public FiatCurrenciesResult Result { get; set; } -} - -/// -/// Represents the result containing the list of fiat currencies. -/// -public class FiatCurrenciesResult -{ - /// - /// Gets or sets the list of fiat currencies. - /// - [JsonProperty("fiatCurrencies")] - public List FiatCurrencies { get; set; } -} diff --git a/Thirdweb/Thirdweb.Pay/Types.GetBuyWithFiatQuote.cs b/Thirdweb/Thirdweb.Pay/Types.GetBuyWithFiatQuote.cs deleted file mode 100644 index 8d3f343e..00000000 --- a/Thirdweb/Thirdweb.Pay/Types.GetBuyWithFiatQuote.cs +++ /dev/null @@ -1,253 +0,0 @@ -using Newtonsoft.Json; - -namespace Thirdweb.Pay; - -/// -/// Parameters for getting a quote for buying with fiat. -/// -/// -/// Initializes a new instance of the class. -/// -public class BuyWithFiatQuoteParams( - string fromCurrencySymbol, - string toAddress, - string toChainId, - string toTokenAddress, - string fromAmount = null, - string fromAmountUnits = null, - string toAmount = null, - string toAmountWei = null, - double? maxSlippageBPS = null, - bool isTestMode = false, - string preferredProvider = null, - object purchaseData = null -) -{ - /// - /// The symbol of the currency to be used for the purchase. - /// - [JsonProperty("fromCurrencySymbol")] - public string FromCurrencySymbol { get; set; } = fromCurrencySymbol; - - /// - /// The amount of the currency to be used for the purchase. - /// - [JsonProperty("fromAmount")] - public string FromAmount { get; set; } = fromAmount; - - /// - /// The units of the currency amount. - /// - [JsonProperty("fromAmountUnits")] - public string FromAmountUnits { get; set; } = fromAmountUnits; - - /// - /// The address to receive the purchased tokens. - /// - [JsonProperty("toAddress")] - public string ToAddress { get; set; } = toAddress; - - /// - /// The chain ID of the destination token. - /// - [JsonProperty("toChainId")] - public string ToChainId { get; set; } = toChainId; - - /// - /// The address of the destination token. - /// - [JsonProperty("toTokenAddress")] - public string ToTokenAddress { get; set; } = toTokenAddress; - - /// - /// The amount of the destination token. - /// - [JsonProperty("toAmount")] - public string ToAmount { get; set; } = toAmount; - - /// - /// The amount of the destination token in wei. - /// - [JsonProperty("toAmountWei")] - public string ToAmountWei { get; set; } = toAmountWei; - - /// - /// The maximum slippage in basis points. - /// - [JsonProperty("maxSlippageBPS")] - public double? MaxSlippageBPS { get; set; } = maxSlippageBPS; - - /// - /// Indicates whether the transaction is in test mode. - /// - [JsonProperty("isTestMode")] - public bool IsTestMode { get; set; } = isTestMode; - - /// - /// The provider to use on the application for thirdweb pay - /// - [JsonProperty("preferredProvider")] - public string PreferredProvider { get; set; } = preferredProvider; - - /// - /// Additional data for the purchase. Useful with direct transfer flow. - /// - [JsonProperty("purchaseData")] - public object PurchaseData { get; set; } = purchaseData; -} - -/// -/// Represents the result of a quote for buying with fiat. -/// -public class BuyWithFiatQuoteResult -{ - /// - /// Gets or sets the intent ID of the quote. - /// - [JsonProperty("intentId")] - public string IntentId { get; set; } - - /// - /// Gets or sets the recipient address. - /// - [JsonProperty("toAddress")] - public string ToAddress { get; set; } - - /// - /// Gets or sets the details of the source currency. - /// - [JsonProperty("fromCurrency")] - public OnRampCurrency FromCurrency { get; set; } - - /// - /// Gets or sets the details of the source currency including fees. - /// - [JsonProperty("fromCurrencyWithFees")] - public OnRampCurrency FromCurrencyWithFees { get; set; } - - /// - /// Gets or sets the on-ramp token details. - /// - [JsonProperty("onRampToken")] - public OnRampToken OnRampToken { get; set; } - - /// - /// Gets or sets the details of the destination token. - /// - [JsonProperty("toToken")] - public Token ToToken { get; set; } - - /// - /// Gets or sets the estimated minimum amount of the destination token in wei. - /// - [JsonProperty("estimatedToAmountMinWei")] - public string EstimatedToAmountMinWei { get; set; } - - /// - /// Gets or sets the estimated minimum amount of the destination token. - /// - [JsonProperty("estimatedToAmountMin")] - public string EstimatedToAmountMin { get; set; } - - /// - /// Gets or sets the list of processing fees. - /// - [JsonProperty("processingFees")] - public List ProcessingFees { get; set; } - - /// - /// Gets or sets the estimated duration of the transaction in seconds. - /// - [JsonProperty("estimatedDurationSeconds")] - public string EstimatedDurationSeconds { get; set; } - - /// - /// Gets or sets the maximum slippage in basis points. - /// - [JsonProperty("maxSlippageBPS")] - public double MaxSlippageBPS { get; set; } - - /// - /// Gets or sets the on-ramp link for the transaction. - /// - [JsonProperty("onRampLink")] - public string OnRampLink { get; set; } -} - -/// -/// Represents an on-ramp token. -/// -public class OnRampToken -{ - /// - /// Gets or sets the token details. - /// - [JsonProperty("token")] - public Token Token { get; set; } - - /// - /// Gets or sets the amount in wei. - /// - [JsonProperty("amountWei")] - public string AmountWei { get; set; } - - /// - /// Gets or sets the amount. - /// - [JsonProperty("amount")] - public string Amount { get; set; } - - /// - /// Gets or sets the amount in USD cents. - /// - [JsonProperty("amountUSDCents")] - public double AmountUSDCents { get; set; } -} - -/// -/// Represents on-ramp fees. -/// -public class OnRampFees -{ - /// - /// Gets or sets the fee amount. - /// - [JsonProperty("amount")] - public string Amount { get; set; } - - /// - /// Gets or sets the units of the fee amount. - /// - [JsonProperty("amountUnits")] - public string AmountUnits { get; set; } - - /// - /// Gets or sets the number of decimals for the fee amount. - /// - [JsonProperty("decimals")] - public int Decimals { get; set; } - - /// - /// Gets or sets the currency symbol for the fee. - /// - [JsonProperty("currencySymbol")] - public string CurrencySymbol { get; set; } - - /// - /// Gets or sets the type of the fee. - /// - [JsonProperty("feeType")] - public string FeeType { get; set; } -} - -/// -/// Represents the response for getting a fiat quote. -/// -public class GetFiatQuoteResponse -{ - /// - /// Gets or sets the result of the fiat quote. - /// - [JsonProperty("result")] - public BuyWithFiatQuoteResult Result { get; set; } -} diff --git a/Thirdweb/Thirdweb.Pay/Types.GetBuyWithFiatStatus.cs b/Thirdweb/Thirdweb.Pay/Types.GetBuyWithFiatStatus.cs deleted file mode 100644 index b4f9a21e..00000000 --- a/Thirdweb/Thirdweb.Pay/Types.GetBuyWithFiatStatus.cs +++ /dev/null @@ -1,201 +0,0 @@ -using Newtonsoft.Json; - -namespace Thirdweb.Pay; - -/// -/// Represents the response for an on-ramp status. -/// -public class OnRampStatusResponse -{ - /// - /// Gets or sets the result of the on-ramp status. - /// - [JsonProperty("result")] - public BuyWithFiatStatusResult Result { get; set; } -} - -/// -/// Represents the status result of buying with fiat. -/// -public class BuyWithFiatStatusResult -{ - /// - /// Gets or sets the intent ID of the transaction. - /// - [JsonProperty("intentId")] - public string IntentId { get; set; } - - /// - /// Gets or sets the status of the transaction. - /// - [JsonProperty("status")] - public string Status { get; set; } - - /// - /// Gets or sets the recipient address. - /// - [JsonProperty("toAddress")] - public string ToAddress { get; set; } - - /// - /// Gets or sets the quote details for the on-ramp transaction. - /// - [JsonProperty("quote")] - public OnRampQuote Quote { get; set; } - - /// - /// Gets or sets the source transaction details. - /// - [JsonProperty("source")] - public TransactionDetails Source { get; set; } - - /// - /// Gets or sets the destination transaction details. - /// - [JsonProperty("destination")] - public TransactionDetails Destination { get; set; } - - /// - /// Gets or sets the failure message if the transaction fails. - /// - [JsonProperty("failureMessage")] - public string FailureMessage { get; set; } - - /// - /// Additional data for the purchase. Useful with direct transfer flow. - /// - [JsonProperty("purchaseData")] - public object PurchaseData { get; set; } -} - -/// -/// Represents a quote for an on-ramp transaction. -/// -public class OnRampQuote -{ - /// - /// Gets or sets the creation date of the quote. - /// - [JsonProperty("createdAt")] - public string CreatedAt { get; set; } - - /// - /// Gets or sets the estimated amount for the on-ramp transaction in wei. - /// - [JsonProperty("estimatedOnRampAmountWei")] - public string EstimatedOnRampAmountWei { get; set; } - - /// - /// Gets or sets the estimated amount for the on-ramp transaction. - /// - [JsonProperty("estimatedOnRampAmount")] - public string EstimatedOnRampAmount { get; set; } - - /// - /// Gets or sets the estimated amount of the destination token. - /// - [JsonProperty("estimatedToTokenAmount")] - public string EstimatedToTokenAmount { get; set; } - - /// - /// Gets or sets the estimated amount of the destination token in wei. - /// - [JsonProperty("estimatedToTokenAmountWei")] - public string EstimatedToTokenAmountWei { get; set; } - - /// - /// Gets or sets the details of the source currency. - /// - [JsonProperty("fromCurrency")] - public OnRampCurrency FromCurrency { get; set; } - - /// - /// Gets or sets the details of the source currency including fees. - /// - [JsonProperty("fromCurrencyWithFees")] - public OnRampCurrency FromCurrencyWithFees { get; set; } - - /// - /// Gets or sets the on-ramp token details. - /// - [JsonProperty("onRampToken")] - public Token OnRampToken { get; set; } - - /// - /// Gets or sets the details of the destination token. - /// - [JsonProperty("toToken")] - public Token ToToken { get; set; } - - /// - /// Gets or sets the estimated duration of the transaction in seconds. - /// - [JsonProperty("estimatedDurationSeconds")] - public long EstimatedDurationSeconds { get; set; } -} - -/// -/// Represents the various statuses of an on-ramp transaction. -/// -public enum OnRampStatus -{ - /// - /// No status. - /// - NONE, - - /// - /// Payment is pending. - /// - PENDING_PAYMENT, - - /// - /// Payment has failed. - /// - PAYMENT_FAILED, - - /// - /// Pending on-ramp transfer. - /// - PENDING_ON_RAMP_TRANSFER, - - /// - /// On-ramp transfer is in progress. - /// - ON_RAMP_TRANSFER_IN_PROGRESS, - - /// - /// On-ramp transfer is completed. - /// - ON_RAMP_TRANSFER_COMPLETED, - - /// - /// On-ramp transfer has failed. - /// - ON_RAMP_TRANSFER_FAILED, - - /// - /// Crypto swap is required. - /// - CRYPTO_SWAP_REQUIRED, - - /// - /// Crypto swap is completed. - /// - CRYPTO_SWAP_COMPLETED, - - /// - /// Crypto swap fallback. - /// - CRYPTO_SWAP_FALLBACK, - - /// - /// Crypto swap is in progress. - /// - CRYPTO_SWAP_IN_PROGRESS, - - /// - /// Crypto swap has failed. - /// - CRYPTO_SWAP_FAILED, -} diff --git a/Thirdweb/Thirdweb.Pay/Types.Shared.cs b/Thirdweb/Thirdweb.Pay/Types.Shared.cs deleted file mode 100644 index 43310b96..00000000 --- a/Thirdweb/Thirdweb.Pay/Types.Shared.cs +++ /dev/null @@ -1,193 +0,0 @@ -using System.Numerics; -using Newtonsoft.Json; - -namespace Thirdweb.Pay; - -/// -/// Represents the error response. -/// -public class ErrorResponse -{ - /// - /// Gets or sets the error details. - /// - [JsonProperty("error")] - public ErrorDetails Error { get; set; } -} - -/// -/// Represents the details of an error. -/// -public class ErrorDetails -{ - /// - /// Gets or sets the error message. - /// - [JsonProperty("message")] - public string Message { get; set; } - - /// - /// Gets or sets the reason for the error. - /// - [JsonProperty("reason")] - public string Reason { get; set; } - - /// - /// Gets or sets the error code. - /// - [JsonProperty("code")] - public string Code { get; set; } - - /// - /// Gets or sets the error stack trace. - /// - [JsonProperty("stack")] - public string Stack { get; set; } - - /// - /// Gets or sets the status code of the error. - /// - [JsonProperty("statusCode")] - public int StatusCode { get; set; } -} - -/// -/// Represents a token. -/// -public class Token -{ - /// - /// Gets or sets the chain ID of the token. - /// - [JsonProperty("chainId")] - public BigInteger ChainId { get; set; } - - /// - /// Gets or sets the address of the token. - /// - [JsonProperty("tokenAddress")] - public string TokenAddress { get; set; } - - /// - /// Gets or sets the number of decimals of the token. - /// - [JsonProperty("decimals")] - public int Decimals { get; set; } - - /// - /// Gets or sets the price of the token in USD cents. - /// - [JsonProperty("priceUSDCents")] - public int PriceUSDCents { get; set; } - - /// - /// Gets or sets the name of the token. - /// - [JsonProperty("name")] - public string Name { get; set; } - - /// - /// Gets or sets the symbol of the token. - /// - [JsonProperty("symbol")] - public string Symbol { get; set; } -} - -/// -/// Represents the estimated details for a transaction. -/// -public class Estimated -{ - /// - /// Gets or sets the amount in USD cents for the source token. - /// - [JsonProperty("fromAmountUSDCents")] - public double FromAmountUSDCents { get; set; } - - /// - /// Gets or sets the minimum amount in USD cents for the destination token. - /// - [JsonProperty("toAmountMinUSDCents")] - public double ToAmountMinUSDCents { get; set; } - - /// - /// Gets or sets the amount in USD cents for the destination token. - /// - [JsonProperty("toAmountUSDCents")] - public double ToAmountUSDCents { get; set; } - - /// - /// Gets or sets the slippage in basis points. - /// - [JsonProperty("slippageBPS")] - public int SlippageBPS { get; set; } - - /// - /// Gets or sets the fees in USD cents. - /// - [JsonProperty("feesUSDCents")] - public double FeesUSDCents { get; set; } - - /// - /// Gets or sets the gas cost in USD cents. - /// - [JsonProperty("gasCostUSDCents")] - public double GasCostUSDCents { get; set; } - - /// - /// Gets or sets the duration of the transaction in seconds. - /// - [JsonProperty("durationSeconds")] - public int DurationSeconds { get; set; } -} - -/// -/// Represents the currency details for an on-ramp transaction. -/// -public class OnRampCurrency -{ - /// - /// Gets or sets the amount of the currency. - /// - [JsonProperty("amount")] - public string Amount { get; set; } - - /// - /// Gets or sets the units of the currency amount. - /// - [JsonProperty("amountUnits")] - public string AmountUnits { get; set; } - - /// - /// Gets or sets the number of decimals for the currency. - /// - [JsonProperty("decimals")] - public int Decimals { get; set; } - - /// - /// Gets or sets the symbol of the currency. - /// - [JsonProperty("currencySymbol")] - public string CurrencySymbol { get; set; } -} - -/// -/// Represents the different types of swaps. -/// -public enum SwapType -{ - /// - /// Swap on the same chain. - /// - SAME_CHAIN, - - /// - /// Swap across different chains. - /// - CROSS_CHAIN, - - /// - /// On-ramp swap. - /// - ON_RAMP, -} diff --git a/Thirdweb/Thirdweb.RPC/RpcError.cs b/Thirdweb/Thirdweb.RPC/RpcError.cs deleted file mode 100644 index 7f22ebb1..00000000 --- a/Thirdweb/Thirdweb.RPC/RpcError.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Newtonsoft.Json; - -namespace Thirdweb; - -/// -/// Represents an error returned from an RPC call. -/// -public class RpcError -{ - /// - /// Gets or sets the error code. - /// - [JsonProperty("code")] - public int Code { get; set; } - - /// - /// Gets or sets the error message. - /// - [JsonProperty("message")] - public string Message { get; set; } - - /// - /// Gets or sets additional data about the error. - /// - [JsonProperty("data")] - public object Data { get; set; } -} diff --git a/Thirdweb/Thirdweb.RPC/RpcRequest.cs b/Thirdweb/Thirdweb.RPC/RpcRequest.cs deleted file mode 100644 index e2877aeb..00000000 --- a/Thirdweb/Thirdweb.RPC/RpcRequest.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Newtonsoft.Json; - -namespace Thirdweb; - -/// -/// Represents an RPC request. -/// -public class RpcRequest -{ - /// - /// Gets or sets the JSON-RPC version. - /// - [JsonProperty("jsonrpc")] - public string Jsonrpc { get; set; } = "2.0"; - - /// - /// Gets or sets the method name for the RPC request. - /// - [JsonProperty("method")] - public string Method { get; set; } - - /// - /// Gets or sets the parameters for the RPC request. - /// - [JsonProperty("params")] - public object[] Params { get; set; } - - /// - /// Gets or sets the ID of the RPC request. - /// - [JsonProperty("id")] - public int Id { get; set; } -} diff --git a/Thirdweb/Thirdweb.RPC/RpcResponse.cs b/Thirdweb/Thirdweb.RPC/RpcResponse.cs deleted file mode 100644 index 09cb55b0..00000000 --- a/Thirdweb/Thirdweb.RPC/RpcResponse.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Newtonsoft.Json; - -namespace Thirdweb; - -/// -/// Represents a response from an RPC call. -/// -/// The type of the result. -public class RpcResponse -{ - /// - /// Gets or sets the JSON-RPC version. - /// - [JsonProperty("jsonrpc")] - public string Jsonrpc { get; set; } - - /// - /// Gets or sets the ID of the RPC request. - /// - [JsonProperty("id")] - public int Id { get; set; } - - /// - /// Gets or sets the result of the RPC call. - /// - [JsonProperty("result")] - public T Result { get; set; } - - /// - /// Gets or sets the error details if the RPC call fails. - /// - [JsonProperty("error")] - public RpcError Error { get; set; } -} diff --git a/Thirdweb/Thirdweb.RPC/ThirdwebRPC.Types.cs b/Thirdweb/Thirdweb.RPC/ThirdwebRPC.Types.cs new file mode 100644 index 00000000..98f4b1dc --- /dev/null +++ b/Thirdweb/Thirdweb.RPC/ThirdwebRPC.Types.cs @@ -0,0 +1,147 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Thirdweb; + +[JsonObject] +public class RpcError +{ + [JsonConstructor] + private RpcError() { } + + [JsonProperty("code")] + public int Code { get; private set; } + + [JsonProperty("message")] + public string Message { get; private set; } + + [JsonProperty("data")] + public JToken Data { get; private set; } +} + +[JsonObject] +public class RpcResponseMessage +{ + [JsonProperty("id")] + public object Id { get; private set; } + + [JsonProperty("jsonrpc")] + public string JsonRpcVersion { get; private set; } + + [JsonProperty("result")] + public JToken Result { get; private set; } + + [JsonProperty("error")] + public RpcError Error { get; protected set; } + + [JsonIgnore] + public bool HasError => this.Error != null; +} + +public class RpcResponse +{ + [JsonProperty("jsonrpc")] + public string Jsonrpc { get; set; } + + [JsonProperty("id")] + public int Id { get; set; } + + [JsonProperty("result")] + public T Result { get; set; } + + [JsonProperty("error")] + public RpcError Error { get; set; } +} + +public class RpcRequest +{ + [JsonProperty("jsonrpc")] + public string Jsonrpc { get; set; } = "2.0"; + + [JsonProperty("method")] + public string Method { get; set; } + + [JsonProperty("params")] + public object[] Params { get; set; } + + [JsonProperty("id")] + public int Id { get; set; } +} + +[JsonObject] +public class RpcRequestMessage +{ + [JsonConstructor] + private RpcRequestMessage() { } + + public RpcRequestMessage(object id, string method, params object[] parameterList) + { + this.Id = id; + this.JsonRpcVersion = "2.0"; + this.Method = method; + this.RawParameters = parameterList; + } + + [JsonProperty("id")] + public object Id { get; set; } + + [JsonProperty("jsonrpc")] + public string JsonRpcVersion { get; private set; } + + [JsonProperty("method")] + public string Method { get; private set; } + + [JsonProperty("params")] + [JsonConverter(typeof(RpcParameterJsonConverter))] + public object RawParameters { get; private set; } +} + +public class RpcParameterJsonConverter : JsonConverter +{ + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + serializer.Serialize(writer, value); + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + switch (reader.TokenType) + { + case JsonToken.StartObject: + try + { + var jObject = JObject.Load(reader); + return jObject.ToObject>(); + } + catch (Exception) + { + throw new Exception("Request parameters can only be an associative array, list or null."); + } + case JsonToken.StartArray: + return JArray.Load(reader).ToObject(serializer); + case JsonToken.Null: + case JsonToken.None: + case JsonToken.StartConstructor: + case JsonToken.PropertyName: + case JsonToken.Comment: + case JsonToken.Raw: + case JsonToken.Integer: + case JsonToken.Float: + case JsonToken.String: + case JsonToken.Boolean: + case JsonToken.Undefined: + case JsonToken.EndObject: + case JsonToken.EndArray: + case JsonToken.EndConstructor: + case JsonToken.Date: + case JsonToken.Bytes: + default: + throw new Exception("Request parameters can only be an associative array, list or null."); + } + } + + public override bool CanConvert(Type objectType) + { + return true; + } +} diff --git a/Thirdweb/Thirdweb.RPC/ThirdwebRPC.cs b/Thirdweb/Thirdweb.RPC/ThirdwebRPC.cs index a3449566..b0dda211 100644 --- a/Thirdweb/Thirdweb.RPC/ThirdwebRPC.cs +++ b/Thirdweb/Thirdweb.RPC/ThirdwebRPC.cs @@ -2,6 +2,7 @@ using System.Numerics; using System.Text; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Thirdweb.Tests")] @@ -206,7 +207,7 @@ private async Task SendBatchAsync(List batch) } catch { - revertMsg = rpcResponse.Error.Data is string ? rpcResponse.Error.Data.ToString() : JsonConvert.SerializeObject(rpcResponse.Error.Data); + revertMsg = rpcResponse.Error.Data.Type == JTokenType.String ? rpcResponse.Error.Data.ToString() : JsonConvert.SerializeObject(rpcResponse.Error.Data); } } tcs.SetException(new Exception($"RPC Error for request {rpcResponse.Id}: {rpcResponse.Error.Message} {revertMsg}")); diff --git a/Thirdweb/Thirdweb.Storage/StorageTypes.cs b/Thirdweb/Thirdweb.Storage/ThirdwebStorage.Types.cs similarity index 100% rename from Thirdweb/Thirdweb.Storage/StorageTypes.cs rename to Thirdweb/Thirdweb.Storage/ThirdwebStorage.Types.cs diff --git a/Thirdweb/Thirdweb.Transactions/ThirdwebTransactionInput.cs b/Thirdweb/Thirdweb.Transactions/ThirdwebTransaction.Types.cs similarity index 70% rename from Thirdweb/Thirdweb.Transactions/ThirdwebTransactionInput.cs rename to Thirdweb/Thirdweb.Transactions/ThirdwebTransaction.Types.cs index 03ec1d3e..e8eb5582 100644 --- a/Thirdweb/Thirdweb.Transactions/ThirdwebTransactionInput.cs +++ b/Thirdweb/Thirdweb.Transactions/ThirdwebTransaction.Types.cs @@ -2,6 +2,7 @@ using Nethereum.Hex.HexConvertors.Extensions; using Nethereum.Hex.HexTypes; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; namespace Thirdweb; @@ -60,7 +61,7 @@ public ThirdwebTransactionInput( /// Gets or sets the sender address of the transaction. /// [JsonProperty(PropertyName = "from")] - internal string From + public string From { get => this._from.EnsureHexPrefix(); set => this._from = value; @@ -120,7 +121,7 @@ public string Data /// Gets or sets the chain ID for the transaction. /// [JsonProperty(PropertyName = "chainId")] - internal HexBigInteger ChainId { get; set; } + public HexBigInteger ChainId { get; set; } /// /// Gets or sets the zkSync options for the transaction. @@ -219,3 +220,104 @@ public EIP7702Authorization(BigInteger chainId, string address, BigInteger nonce this.S = s.BytesToHex(); } } + +/// +/// Represents the receipt of a transaction. +/// +public class ThirdwebTransactionReceipt +{ + /// + /// Gets or sets the transaction hash. + /// + [JsonProperty(PropertyName = "transactionHash")] + public string TransactionHash { get; set; } + + /// + /// Gets or sets the transaction index within the block. + /// + [JsonProperty(PropertyName = "transactionIndex")] + public HexBigInteger TransactionIndex { get; set; } + + /// + /// Gets or sets the hash of the block containing the transaction. + /// + [JsonProperty(PropertyName = "blockHash")] + public string BlockHash { get; set; } + + /// + /// Gets or sets the number of the block containing the transaction. + /// + [JsonProperty(PropertyName = "blockNumber")] + public HexBigInteger BlockNumber { get; set; } + + /// + /// Gets or sets the address of the sender. + /// + [JsonProperty(PropertyName = "from")] + public string From { get; set; } + + /// + /// Gets or sets the address of the recipient. + /// + [JsonProperty(PropertyName = "to")] + public string To { get; set; } + + /// + /// Gets or sets the cumulative gas used by the transaction. + /// + [JsonProperty(PropertyName = "cumulativeGasUsed")] + public HexBigInteger CumulativeGasUsed { get; set; } + + /// + /// Gets or sets the gas used by the transaction. + /// + [JsonProperty(PropertyName = "gasUsed")] + public HexBigInteger GasUsed { get; set; } + + /// + /// Gets or sets the effective gas price for the transaction. + /// + [JsonProperty(PropertyName = "effectiveGasPrice")] + public HexBigInteger EffectiveGasPrice { get; set; } + + /// + /// Gets or sets the contract address created by the transaction, if applicable. + /// + [JsonProperty(PropertyName = "contractAddress")] + public string ContractAddress { get; set; } + + /// + /// Gets or sets the status of the transaction. + /// + [JsonProperty(PropertyName = "status")] + public HexBigInteger Status { get; set; } + + /// + /// Gets or sets the logs generated by the transaction. + /// + [JsonProperty(PropertyName = "logs")] + public JArray Logs { get; set; } + + /// + /// Gets or sets the transaction type. + /// + [JsonProperty(PropertyName = "type")] + public HexBigInteger Type { get; set; } + + /// + /// Gets or sets the logs bloom filter. + /// + [JsonProperty(PropertyName = "logsBloom")] + public string LogsBloom { get; set; } + + /// + /// Gets or sets the root of the transaction. + /// + [JsonProperty(PropertyName = "root")] + public string Root { get; set; } + + public override string ToString() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } +} diff --git a/Thirdweb/Thirdweb.Transactions/ThirdwebTransaction.cs b/Thirdweb/Thirdweb.Transactions/ThirdwebTransaction.cs index 40089fe8..935abb6c 100644 --- a/Thirdweb/Thirdweb.Transactions/ThirdwebTransaction.cs +++ b/Thirdweb/Thirdweb.Transactions/ThirdwebTransaction.cs @@ -1,6 +1,4 @@ using System.Numerics; -using Nethereum.ABI.FunctionEncoding; -using Nethereum.Hex.HexConvertors.Extensions; using Nethereum.Hex.HexTypes; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -28,7 +26,7 @@ public struct TotalCosts /// public class ThirdwebTransaction { - public ThirdwebTransactionInput Input { get; } + public ThirdwebTransactionInput Input { get; set; } internal readonly IThirdwebWallet Wallet; @@ -424,7 +422,7 @@ public static async Task WaitForTransactionReceipt(T receipt = await rpc.SendRequestAsync("eth_getTransactionReceipt", txHash).ConfigureAwait(false); if (receipt == null) { - await ThirdwebTask.Delay(100, cancellationToken).ConfigureAwait(false); + await ThirdwebTask.Delay(100, cts.Token).ConfigureAwait(false); } } while (receipt == null && !cts.Token.IsCancellationRequested); @@ -437,29 +435,6 @@ public static async Task WaitForTransactionReceipt(T { throw new Exception($"Transaction {txHash} execution reverted."); } - - var userOpEvent = receipt.DecodeAllEvents(); - if (userOpEvent != null && userOpEvent.Count > 0 && !userOpEvent[0].Event.Success) - { - var revertReasonEvent = receipt.DecodeAllEvents(); - var postOpRevertReasonEvent = receipt.DecodeAllEvents(); - if (revertReasonEvent != null && revertReasonEvent.Count > 0) - { - var revertReason = revertReasonEvent[0].Event.RevertReason; - var revertReasonString = new FunctionCallDecoder().DecodeFunctionErrorMessage(revertReason.ToHex(true)); - throw new Exception($"Transaction {txHash} execution silently reverted: {revertReasonString}"); - } - else if (postOpRevertReasonEvent != null && postOpRevertReasonEvent.Count > 0) - { - var revertReason = postOpRevertReasonEvent[0].Event.RevertReason; - var revertReasonString = new FunctionCallDecoder().DecodeFunctionErrorMessage(revertReason.ToHex(true)); - throw new Exception($"Transaction {txHash} execution silently reverted: {revertReasonString}"); - } - else - { - throw new Exception($"Transaction {txHash} execution silently reverted with no reason string"); - } - } } catch (OperationCanceledException) { @@ -537,7 +512,7 @@ public static async Task WaitForTransactionHash(ThirdwebClient client, s Paymaster = transaction.Input.ZkSync.Value.Paymaster, Nonce = transaction.Input.Nonce ?? new HexBigInteger(await GetNonce(transaction).ConfigureAwait(false)), Value = transaction.Input.Value?.Value ?? 0, - Data = transaction.Input.Data?.HexToByteArray() ?? Array.Empty(), + Data = transaction.Input.Data?.HexToBytes() ?? Array.Empty(), FactoryDeps = transaction.Input.ZkSync.Value.FactoryDeps, PaymasterInput = transaction.Input.ZkSync.Value.PaymasterInput, }; diff --git a/Thirdweb/Thirdweb.Transactions/ThirdwebTransactionReceipt.cs b/Thirdweb/Thirdweb.Transactions/ThirdwebTransactionReceipt.cs deleted file mode 100644 index 2d20c60c..00000000 --- a/Thirdweb/Thirdweb.Transactions/ThirdwebTransactionReceipt.cs +++ /dev/null @@ -1,106 +0,0 @@ -using Nethereum.Hex.HexTypes; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Thirdweb; - -/// -/// Represents the receipt of a transaction. -/// -public class ThirdwebTransactionReceipt -{ - /// - /// Gets or sets the transaction hash. - /// - [JsonProperty(PropertyName = "transactionHash")] - public string TransactionHash { get; set; } - - /// - /// Gets or sets the transaction index within the block. - /// - [JsonProperty(PropertyName = "transactionIndex")] - public HexBigInteger TransactionIndex { get; set; } - - /// - /// Gets or sets the hash of the block containing the transaction. - /// - [JsonProperty(PropertyName = "blockHash")] - public string BlockHash { get; set; } - - /// - /// Gets or sets the number of the block containing the transaction. - /// - [JsonProperty(PropertyName = "blockNumber")] - public HexBigInteger BlockNumber { get; set; } - - /// - /// Gets or sets the address of the sender. - /// - [JsonProperty(PropertyName = "from")] - public string From { get; set; } - - /// - /// Gets or sets the address of the recipient. - /// - [JsonProperty(PropertyName = "to")] - public string To { get; set; } - - /// - /// Gets or sets the cumulative gas used by the transaction. - /// - [JsonProperty(PropertyName = "cumulativeGasUsed")] - public HexBigInteger CumulativeGasUsed { get; set; } - - /// - /// Gets or sets the gas used by the transaction. - /// - [JsonProperty(PropertyName = "gasUsed")] - public HexBigInteger GasUsed { get; set; } - - /// - /// Gets or sets the effective gas price for the transaction. - /// - [JsonProperty(PropertyName = "effectiveGasPrice")] - public HexBigInteger EffectiveGasPrice { get; set; } - - /// - /// Gets or sets the contract address created by the transaction, if applicable. - /// - [JsonProperty(PropertyName = "contractAddress")] - public string ContractAddress { get; set; } - - /// - /// Gets or sets the status of the transaction. - /// - [JsonProperty(PropertyName = "status")] - public HexBigInteger Status { get; set; } - - /// - /// Gets or sets the logs generated by the transaction. - /// - [JsonProperty(PropertyName = "logs")] - public JArray Logs { get; set; } - - /// - /// Gets or sets the transaction type. - /// - [JsonProperty(PropertyName = "type")] - public HexBigInteger Type { get; set; } - - /// - /// Gets or sets the logs bloom filter. - /// - [JsonProperty(PropertyName = "logsBloom")] - public string LogsBloom { get; set; } - - /// - /// Gets or sets the root of the transaction. - /// - [JsonProperty(PropertyName = "root")] - public string Root { get; set; } - - public override string ToString() - { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } -} diff --git a/Thirdweb/Thirdweb.Utils/Constants.cs b/Thirdweb/Thirdweb.Utils/Constants.cs index d537444a..a2b50f15 100644 --- a/Thirdweb/Thirdweb.Utils/Constants.cs +++ b/Thirdweb/Thirdweb.Utils/Constants.cs @@ -4,14 +4,10 @@ public static class Constants { public const string VERSION = "2.25.2"; - internal const string BRIDGE_API_URL = "https://bridge.thirdweb.com"; - internal const string INSIGHT_API_URL = "https://insight.thirdweb.com"; internal const string SOCIAL_API_URL = "https://social.thirdweb.com"; internal const string PIN_URI = "https://storage.thirdweb.com/ipfs/upload"; internal const string FALLBACK_IPFS_GATEWAY = "https://ipfs.io/ipfs/"; - internal const string NEBULA_API_URL = "https://nebula-api.thirdweb.com"; internal const string ENGINE_API_URL = "https://engine.thirdweb.com"; - internal const string NEBULA_DEFAULT_MODEL = "t0-003"; internal const int DEFAULT_FETCH_TIMEOUT = 120000; public const string ADDRESS_ZERO = "0x0000000000000000000000000000000000000000"; diff --git a/Thirdweb/Thirdweb.Wallets/EIP712.cs b/Thirdweb/Thirdweb.Utils/EIP712.cs similarity index 89% rename from Thirdweb/Thirdweb.Wallets/EIP712.cs rename to Thirdweb/Thirdweb.Utils/EIP712.cs index 0867bd43..dcd8e466 100644 --- a/Thirdweb/Thirdweb.Wallets/EIP712.cs +++ b/Thirdweb/Thirdweb.Utils/EIP712.cs @@ -1,8 +1,6 @@ using System.Numerics; using Nethereum.ABI.EIP712; -using Nethereum.Hex.HexConvertors.Extensions; using Nethereum.Model; -using Nethereum.RLP; using Nethereum.Signer; namespace Thirdweb; @@ -129,29 +127,6 @@ IThirdwebWallet signer return SerializeEip712(transaction, signatureRaw, chainId); } - /// - /// Generates a signature for a minimal forwarder request. - /// - /// The domain name. - /// The version. - /// The chain ID. - /// The verifying contract. - /// The forward request. - /// The wallet signer. - /// The generated signature. - public static async Task GenerateSignature_MinimalForwarder( - string domainName, - string version, - BigInteger chainId, - string verifyingContract, - Forwarder_ForwardRequest forwardRequest, - IThirdwebWallet signer - ) - { - var typedData = GetTypedDefinition_MinimalForwarder(domainName, version, chainId, verifyingContract); - return await signer.SignTypedDataV4(forwardRequest, typedData); - } - /// /// Generates a signature for an ERC20 token mint request. /// @@ -422,30 +397,6 @@ public static TypedData GetTypedDefinition_TokenERC1155(string domainNam }; } - /// - /// Gets the typed data definition for a minimal forwarder request. - /// - /// The domain name. - /// The version. - /// The chain ID. - /// The verifying contract. - /// The typed data definition. - public static TypedData GetTypedDefinition_MinimalForwarder(string domainName, string version, BigInteger chainId, string verifyingContract) - { - return new TypedData - { - Domain = new Domain - { - Name = domainName, - Version = version, - ChainId = chainId, - VerifyingContract = verifyingContract, - }, - Types = MemberDescriptionFactory.GetTypesMemberDescription(typeof(Domain), typeof(Forwarder_ForwardRequest)), - PrimaryType = "ForwardRequest", - }; - } - #endregion #region Helpers @@ -483,14 +434,14 @@ private static string SerializeEip712(AccountAbstraction.ZkSyncAATransaction tra // Add meta transaction.GasPerPubdataByteLimit.ToByteArray(isUnsigned: true, isBigEndian: true), Array.Empty(), // TODO: FactoryDeps - signature.CreateStringSignature().HexToByteArray(), + signature.CreateStringSignature().HexToBytes(), // add array of rlp encoded paymaster/paymasterinput transaction.Paymaster != 0 ? RLP.EncodeElement(transaction.Paymaster.ToByteArray(isUnsigned: true, isBigEndian: true)).Concat(RLP.EncodeElement(transaction.PaymasterInput)).ToArray() : new byte[] { 0xc0 }, }; - return "0x71" + RLP.EncodeDataItemsAsElementOrListAndCombineAsList(fields.ToArray(), _indexOfListDataItems).ToHex(); + return "0x71" + RLP.EncodeDataItemsAsElementOrListAndCombineAsList(fields.ToArray(), _indexOfListDataItems).BytesToHex(false); } #endregion diff --git a/Thirdweb/Thirdweb.Wallets/EIP712Encoder.cs b/Thirdweb/Thirdweb.Utils/EIP712Encoder.cs similarity index 98% rename from Thirdweb/Thirdweb.Wallets/EIP712Encoder.cs rename to Thirdweb/Thirdweb.Utils/EIP712Encoder.cs index c9b04059..28027b21 100644 --- a/Thirdweb/Thirdweb.Wallets/EIP712Encoder.cs +++ b/Thirdweb/Thirdweb.Utils/EIP712Encoder.cs @@ -4,7 +4,6 @@ using Nethereum.ABI; using Nethereum.ABI.EIP712; using Nethereum.ABI.FunctionEncoding; -using Nethereum.Hex.HexConvertors.Extensions; using Nethereum.Util; namespace Thirdweb; @@ -64,7 +63,7 @@ public byte[] EncodeTypedDataRaw(TypedDataRaw typedData) { using var memoryStream = new MemoryStream(); using var writer = new BinaryWriter(memoryStream); - writer.Write("1901".HexToByteArray()); + writer.Write("1901".HexToBytes()); writer.Write(this.HashStruct(typedData.Types, "EIP712Domain", typedData.DomainRawValues)); writer.Write(this.HashStruct(typedData.Types, typedData.PrimaryType, typedData.Message)); @@ -186,7 +185,7 @@ private void EncodeData(BinaryWriter writer, IDictionary + /// Reason for threshold according to Vitalik Buterin: + /// - 56 bytes maximizes the benefit of both options + /// - if we went with 60 then we would have only had 4 slots for long strings + /// so RLP would not have been able to store objects above 4gb + /// - if we went with 48 then RLP would be fine for 2^128 space, but that's way too much + /// - so 56 and 2^64 space seems like the right place to put the cutoff + /// - also, that's where Bitcoin's varint does the cutof + /// + private const int SIZE_THRESHOLD = 56; + + /* RLP encoding rules are defined as follows: + * For a single byte whose value is in the [0x00, 0x7f] range, that byte is + * its own RLP encoding. + */ + + /// + /// [0x80] + /// If a string is 0-55 bytes long, the RLP encoding consists of a single + /// byte with value 0x80 plus the length of the string followed by the + /// string. The range of the first byte is thus [0x80, 0xb7]. + /// + private const byte OFFSET_SHORT_ITEM = 0x80; + + /// + /// [0xb7] + /// If a string is more than 55 bytes long, the RLP encoding consists of a + /// single byte with value 0xb7 plus the length of the length of the string + /// in binary form, followed by the length of the string, followed by the + /// string. For example, a length-1024 string would be encoded as + /// \xb9\x04\x00 followed by the string. The range of the first byte is thus + /// [0xb8, 0xbf]. + /// + private const byte OFFSET_LONG_ITEM = 0xb7; + + /// + /// [0xc0] + /// If the total payload of a list (i.e. the combined length of all its + /// items) is 0-55 bytes long, the RLP encoding consists of a single byte + /// with value 0xc0 plus the length of the list followed by the concatenation + /// of the RLP encodings of the items. The range of the first byte is thus + /// [0xc0, 0xf7]. + /// + public const byte OFFSET_SHORT_LIST = 0xc0; + + /// + /// [0xf7] + /// If the total payload of a list is more than 55 bytes long, the RLP + /// encoding consists of a single byte with value 0xf7 plus the length of the + /// length of the list in binary form, followed by the length of the list, + /// followed by the concatenation of the RLP encodings of the items. The + /// range of the first byte is thus [0xf8, 0xff]. + /// + private const byte OFFSET_LONG_LIST = 0xf7; + + public static readonly byte[] EMPTY_BYTE_ARRAY = Array.Empty(); + public static readonly byte[] ZERO_BYTE_ARRAY = { 0 }; + + public static int ByteArrayToInt(byte[] bytes) + { + if (BitConverter.IsLittleEndian) + { + Array.Reverse(bytes); + } + + return BitConverter.ToInt32(bytes, 0); + } + + public static byte[] EncodeByte(byte singleByte) + { + if (singleByte == 0) + { + return new[] { OFFSET_SHORT_ITEM }; + } + + if (singleByte <= 0x7F) + { + return new[] { singleByte }; + } + + return new[] { (byte)(OFFSET_SHORT_ITEM + 1), singleByte }; + } + + public static byte[] EncodeElement(byte[] srcData) + { + // null or empty + if (srcData == null || srcData.Length == 0) + { + return new[] { OFFSET_SHORT_ITEM }; + } + + // single zero + if (srcData.Length == 1 && srcData[0] == 0) + { + return srcData; + } + + if (srcData.Length == 1 && srcData[0] < 0x80) + { + return srcData; + } + + if (srcData.Length < SIZE_THRESHOLD) + { + // length = 8X + var length = (byte)(OFFSET_SHORT_ITEM + srcData.Length); + var data = new byte[srcData.Length + 1]; + Array.Copy(srcData, 0, data, 1, srcData.Length); + data[0] = length; + + return data; + } + else + { + // length of length = BX + // prefix = [BX, [length]] + var tmpLength = srcData.Length; + byte byteNum = 0; + while (tmpLength != 0) + { + ++byteNum; + tmpLength >>= 8; + } + var lenBytes = new byte[byteNum]; + for (var i = 0; i < byteNum; ++i) + { + lenBytes[byteNum - 1 - i] = (byte)(srcData.Length >> (8 * i)); + } + // first byte = F7 + bytes.length + var data = new byte[srcData.Length + 1 + byteNum]; + Array.Copy(srcData, 0, data, 1 + byteNum, srcData.Length); + data[0] = (byte)(OFFSET_LONG_ITEM + byteNum); + Array.Copy(lenBytes, 0, data, 1, lenBytes.Length); + + return data; + } + } + + public static byte[] EncodeDataItemsAsElementOrListAndCombineAsList(byte[][] dataItems, int[] indexOfListDataItems = null) + { + if (indexOfListDataItems == null) + { + return EncodeList(dataItems.Select(EncodeElement).ToArray()); + } + + var encodedData = new List(); + + for (var i = 0; i < dataItems.Length; i++) + { + if (indexOfListDataItems.Contains(i)) + { + var item = dataItems[i]; + encodedData.Add(EncodeList(item)); + } + else + { + encodedData.Add(EncodeElement(dataItems[i])); + } + } + + return EncodeList(encodedData.ToArray()); + } + + public static byte[] EncodeList(params byte[][] items) + { + if (items == null || (items.Length == 1 && items[0] == null)) + { + return new[] { OFFSET_SHORT_LIST }; + } + + var totalLength = 0; + for (var i = 0; i < items.Length; i++) + { + totalLength += items[i].Length; + } + + byte[] data; + + int copyPos; + + if (totalLength < SIZE_THRESHOLD) + { + var dataLength = 1 + totalLength; + data = new byte[dataLength]; + + //single byte length + data[0] = (byte)(OFFSET_SHORT_LIST + totalLength); + copyPos = 1; + } + else + { + // length of length = BX + // prefix = [BX, [length]] + var tmpLength = totalLength; + byte byteNum = 0; + + while (tmpLength != 0) + { + ++byteNum; + tmpLength >>= 8; + } + + tmpLength = totalLength; + + var lenBytes = new byte[byteNum]; + for (var i = 0; i < byteNum; ++i) + { + lenBytes[byteNum - 1 - i] = (byte)(tmpLength >> (8 * i)); + } + // first byte = F7 + bytes.length + data = new byte[1 + lenBytes.Length + totalLength]; + + data[0] = (byte)(OFFSET_LONG_LIST + byteNum); + Array.Copy(lenBytes, 0, data, 1, lenBytes.Length); + + copyPos = lenBytes.Length + 1; + } + + //Combine all elements + foreach (var item in items) + { + Array.Copy(item, 0, data, copyPos, item.Length); + copyPos += item.Length; + } + return data; + } +} diff --git a/Thirdweb/Thirdweb.Utils/Utils.cs b/Thirdweb/Thirdweb.Utils/Utils.cs index 28064672..d1d0651a 100644 --- a/Thirdweb/Thirdweb.Utils/Utils.cs +++ b/Thirdweb/Thirdweb.Utils/Utils.cs @@ -9,11 +9,8 @@ using Nethereum.ABI.FunctionEncoding; using Nethereum.ABI.FunctionEncoding.Attributes; using Nethereum.ABI.Model; -using Nethereum.Contracts; using Nethereum.Hex.HexConvertors.Extensions; using Nethereum.Hex.HexTypes; -using Nethereum.Model; -using Nethereum.RLP; using Nethereum.Signer; using Nethereum.Util; using Newtonsoft.Json; @@ -117,10 +114,11 @@ public static string HashMessage(this string message) /// Converts the given bytes to a hex string. /// /// The bytes to convert. + /// Whether to add the "0x" prefix. /// The hex string. - public static string BytesToHex(this byte[] bytes) + public static string BytesToHex(this byte[] bytes, bool addPrefix = true) { - return bytes.ToHex(true); + return bytes.ToHex(addPrefix); } /// @@ -389,18 +387,6 @@ public static string ToChecksumAddress(this string address) return new AddressUtil().ConvertToChecksumAddress(address); } - /// - /// Decodes all events of the specified type from the transaction receipt logs. - /// - /// The event DTO type. - /// The transaction receipt. - /// A list of decoded events. - public static List> DecodeAllEvents(this ThirdwebTransactionReceipt transactionReceipt) - where TEventDTO : new() - { - return transactionReceipt.Logs.DecodeAllEvents(); - } - /// /// Adjusts the value's decimals. /// @@ -1111,103 +1097,6 @@ public static byte[] TrimZeroes(this byte[] bytes) return trimmed.ToArray(); } - /// - /// Decodes the given RLP-encoded transaction data. - /// - /// The RLP-encoded signed transaction data. - /// The decoded transaction input and signature. - public static (ThirdwebTransactionInput transactionInput, string signature) DecodeTransaction(string signedRlpData) - { - return DecodeTransaction(signedRlpData.HexToBytes()); - } - - /// - /// Decodes the given RLP-encoded transaction data. - /// - /// The RLP-encoded signed transaction data. - /// The decoded transaction input and signature. - public static (ThirdwebTransactionInput transactionInput, string signature) DecodeTransaction(byte[] signedRlpData) - { - var txType = signedRlpData[0]; - if (txType is 0x04 or 0x02) - { - signedRlpData = signedRlpData.Skip(1).ToArray(); - } - - var decodedList = RLP.Decode(signedRlpData); - var decodedElements = (RLPCollection)decodedList; - var chainId = decodedElements[0].RLPData.ToBigIntegerFromRLPDecoded(); - var nonce = decodedElements[1].RLPData.ToBigIntegerFromRLPDecoded(); - var maxPriorityFeePerGas = decodedElements[2].RLPData.ToBigIntegerFromRLPDecoded(); - var maxFeePerGas = decodedElements[3].RLPData.ToBigIntegerFromRLPDecoded(); - var gasLimit = decodedElements[4].RLPData.ToBigIntegerFromRLPDecoded(); - var receiverAddress = decodedElements[5].RLPData?.BytesToHex(); - var amount = decodedElements[6].RLPData.ToBigIntegerFromRLPDecoded(); - var data = decodedElements[7].RLPData?.BytesToHex(); - // 8th decoded element is access list - var authorizations = txType == 0x04 ? DecodeAutorizationList(decodedElements[9]?.RLPData) : null; - - var signature = RLPSignedDataDecoder.DecodeSignature(decodedElements, txType == 0x04 ? 10 : 9); - return ( - new ThirdwebTransactionInput( - chainId: chainId, - to: receiverAddress.ToChecksumAddress(), - nonce: nonce, - gas: gasLimit, - value: amount, - data: data, - maxFeePerGas: maxFeePerGas, - maxPriorityFeePerGas: maxPriorityFeePerGas - ) - { - AuthorizationList = authorizations, - }, - signature.CreateStringSignature() - ); - } - - /// - /// Decodes the given RLP-encoded authorization list. - /// - public static List DecodeAutorizationList(byte[] authorizationListEncoded) - { - if (authorizationListEncoded == null || authorizationListEncoded.Length == 0 || authorizationListEncoded[0] == RLP.OFFSET_SHORT_LIST) - { - return null; - } - - var decodedList = (RLPCollection)RLP.Decode(authorizationListEncoded); - - var authorizationLists = new List(); - foreach (var rlpElement in decodedList) - { - var decodedItem = (RLPCollection)rlpElement; - var signature = RLPSignedDataDecoder.DecodeSignature(decodedItem, 3); - var authorizationListItem = new EIP7702Authorization - { - ChainId = new HexBigInteger(decodedItem[0].RLPData.ToBigIntegerFromRLPDecoded()).HexValue, - Address = decodedItem[1].RLPData.BytesToHex().ToChecksumAddress(), - Nonce = new HexBigInteger(decodedItem[2].RLPData.ToBigIntegerFromRLPDecoded()).HexValue, - YParity = signature.V.BytesToHex(), - R = signature.R.BytesToHex(), - S = signature.S.BytesToHex(), - }; - authorizationLists.Add(authorizationListItem); - } - - return authorizationLists; - } - - internal static byte[] ToByteArrayForRLPEncoding(this BigInteger value) - { - if (value == 0) - { - return Array.Empty(); - } - - return value.ToBytesForRLPEncoding(); - } - public static async void TrackTransaction(ThirdwebTransaction transaction, string transactionHash) { try @@ -1287,7 +1176,7 @@ public static async Task WaitForTransactionReceipt(T receipt = await rpc.SendRequestAsync("eth_getTransactionReceipt", txHash).ConfigureAwait(false); if (receipt == null) { - await ThirdwebTask.Delay(100, cancellationToken).ConfigureAwait(false); + await ThirdwebTask.Delay(100, cts.Token).ConfigureAwait(false); } } while (receipt == null && !cts.Token.IsCancellationRequested); @@ -1300,29 +1189,6 @@ public static async Task WaitForTransactionReceipt(T { throw new Exception($"Transaction {txHash} execution reverted."); } - - var userOpEvent = receipt.DecodeAllEvents(); - if (userOpEvent != null && userOpEvent.Count > 0 && !userOpEvent[0].Event.Success) - { - var revertReasonEvent = receipt.DecodeAllEvents(); - var postOpRevertReasonEvent = receipt.DecodeAllEvents(); - if (revertReasonEvent != null && revertReasonEvent.Count > 0) - { - var revertReason = revertReasonEvent[0].Event.RevertReason; - var revertReasonString = new FunctionCallDecoder().DecodeFunctionErrorMessage(revertReason.ToHex(true)); - throw new Exception($"Transaction {txHash} execution silently reverted: {revertReasonString}"); - } - else if (postOpRevertReasonEvent != null && postOpRevertReasonEvent.Count > 0) - { - var revertReason = postOpRevertReasonEvent[0].Event.RevertReason; - var revertReasonString = new FunctionCallDecoder().DecodeFunctionErrorMessage(revertReason.ToHex(true)); - throw new Exception($"Transaction {txHash} execution silently reverted: {revertReasonString}"); - } - else - { - throw new Exception($"Transaction {txHash} execution silently reverted with no reason string"); - } - } } catch (OperationCanceledException) { diff --git a/Thirdweb/Thirdweb.Wallets/EngineWallet/EngineWallet.cs b/Thirdweb/Thirdweb.Wallets/EngineWallet/EngineWallet.cs deleted file mode 100644 index 282057ca..00000000 --- a/Thirdweb/Thirdweb.Wallets/EngineWallet/EngineWallet.cs +++ /dev/null @@ -1,415 +0,0 @@ -using System.Numerics; -using System.Text; -using Nethereum.ABI.EIP712; -using Nethereum.Signer; -using Nethereum.Signer.EIP712; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Thirdweb; - -/// -/// Enclave based secure cross ecosystem wallet. -/// -[Obsolete("The EngineWallet is deprecated and will be removed in a future version. Please use ServerWallet instead.")] -public partial class EngineWallet : IThirdwebWallet -{ - public ThirdwebClient Client { get; } - public ThirdwebAccountType AccountType => ThirdwebAccountType.ExternalAccount; - public string WalletId => "engine"; - - private readonly string _engineUrl; - private readonly string _walletAddress; - private readonly IThirdwebHttpClient _engineClient; - private readonly int? _timeoutSeconds; - private readonly bool _forwardLocalGasFees; - - internal EngineWallet(ThirdwebClient client, IThirdwebHttpClient engineClient, string engineUrl, string walletAddress, int? timeoutSeconds, bool forwardLocalGasFees) - { - this.Client = client; - this._engineUrl = engineUrl; - this._walletAddress = walletAddress; - this._engineClient = engineClient; - this._timeoutSeconds = timeoutSeconds; - this._forwardLocalGasFees = forwardLocalGasFees; - } - - #region Creation - - /// - /// Creates an instance of the EngineWallet. - /// - /// The Thirdweb client. - /// The URL of the engine. - /// The access token to use for the engine. - /// The backend wallet address to use. - /// The timeout in seconds for the transaction. Defaults to no timeout. - /// Additional headers to include in requests. Authorization and X-Backend-Wallet-Address automatically included. - /// Whether to forward locally calculated gas price/fees to the engine. Defaults to false. - public static EngineWallet Create( - ThirdwebClient client, - string engineUrl, - string authToken, - string walletAddress, - int? timeoutSeconds = null, - Dictionary additionalHeaders = null, - bool forwardLocalGasFees = false - ) - { - if (client == null) - { - throw new ArgumentNullException(nameof(client), "Client cannot be null."); - } - - if (string.IsNullOrWhiteSpace(engineUrl)) - { - throw new ArgumentNullException(nameof(engineUrl), "Engine URL cannot be null or empty."); - } - - if (string.IsNullOrWhiteSpace(authToken)) - { - throw new ArgumentNullException(nameof(authToken), "Auth token cannot be null or empty."); - } - - if (string.IsNullOrWhiteSpace(walletAddress)) - { - throw new ArgumentNullException(nameof(walletAddress), "Wallet address cannot be null or empty."); - } - - if (engineUrl.EndsWith('/')) - { - engineUrl = engineUrl[..^1]; - } - - walletAddress = walletAddress.ToChecksumAddress(); - - var engineClient = Utils.ReconstructHttpClient(client.HttpClient, new Dictionary { { "Authorization", $"Bearer {authToken}" } }); - engineClient.AddHeader("X-Backend-Wallet-Address", walletAddress); - if (additionalHeaders != null) - { - foreach (var header in additionalHeaders) - { - engineClient.AddHeader(header.Key, header.Value); - } - } - var wallet = new EngineWallet(client, engineClient, engineUrl, walletAddress, timeoutSeconds, forwardLocalGasFees); - Utils.TrackConnection(wallet); - return wallet; - } - - #endregion - - #region Wallet Specific - - public static async Task WaitForQueueId(IThirdwebHttpClient httpClient, string engineUrl, string queueId) - { - var transactionHash = string.Empty; - while (string.IsNullOrEmpty(transactionHash)) - { - await ThirdwebTask.Delay(100); - - var statusResponse = await httpClient.GetAsync($"{engineUrl}/transaction/status/{queueId}"); - var content = await statusResponse.Content.ReadAsStringAsync(); - var response = JObject.Parse(content); - - var isErrored = response["result"]?["status"]?.ToString() is "errored" or "cancelled"; - if (isErrored) - { - throw new Exception($"Failed to send transaction: {response["result"]?["errorMessage"]?.ToString()}"); - } - - transactionHash = response["result"]?["transactionHash"]?.ToString(); - } - return transactionHash; - } - - private object ToEngineTransaction(ThirdwebTransactionInput transaction) - { - if (transaction == null) - { - throw new ArgumentNullException(nameof(transaction)); - } - - return new - { - toAddress = transaction.To, - data = transaction.Data, - value = transaction.Value?.HexValue ?? "0x00", - authorizationList = transaction.AuthorizationList != null && transaction.AuthorizationList.Count > 0 - ? transaction - .AuthorizationList.Select(authorization => new - { - chainId = authorization.ChainId.HexToNumber(), - address = authorization.Address, - nonce = authorization.Nonce.HexToNumber(), - yParity = authorization.YParity.HexToNumber(), - r = authorization.R, - s = authorization.S, - }) - .ToArray() - : null, - txOverrides = this._timeoutSeconds != null || transaction.Gas != null || transaction.GasPrice != null || transaction.MaxFeePerGas != null || transaction.MaxPriorityFeePerGas != null - ? new - { - gas = transaction.Gas?.Value.ToString(), - gasPrice = this._forwardLocalGasFees ? transaction.GasPrice?.Value.ToString() : null, - maxFeePerGas = this._forwardLocalGasFees ? transaction.MaxFeePerGas?.Value.ToString() : null, - maxPriorityFeePerGas = this._forwardLocalGasFees ? transaction.MaxPriorityFeePerGas?.Value.ToString() : null, - timeoutSeconds = this._timeoutSeconds, - } - : null, - }; - } - - #endregion - - #region IThirdwebWallet - - public Task GetAddress() - { - if (!string.IsNullOrEmpty(this._walletAddress)) - { - return Task.FromResult(this._walletAddress.ToChecksumAddress()); - } - else - { - return Task.FromResult(this._walletAddress); - } - } - - public Task EthSign(byte[] rawMessage) - { - if (rawMessage == null) - { - throw new ArgumentNullException(nameof(rawMessage), "Message to sign cannot be null."); - } - - throw new NotImplementedException(); - } - - public Task EthSign(string message) - { - if (message == null) - { - throw new ArgumentNullException(nameof(message), "Message to sign cannot be null."); - } - - throw new NotImplementedException(); - } - - public async Task PersonalSign(byte[] rawMessage) - { - if (rawMessage == null) - { - throw new ArgumentNullException(nameof(rawMessage), "Message to sign cannot be null."); - } - - var url = $"{this._engineUrl}/backend-wallet/sign-message"; - var payload = new { messagePayload = new { message = rawMessage.BytesToHex(), isBytes = true } }; - - var requestContent = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"); - - var response = await this._engineClient.PostAsync(url, requestContent).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - - var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - return JObject.Parse(content)["result"].Value(); - } - - public async Task PersonalSign(string message) - { - if (string.IsNullOrEmpty(message)) - { - throw new ArgumentNullException(nameof(message), "Message to sign cannot be null."); - } - - var url = $"{this._engineUrl}/backend-wallet/sign-message"; - var payload = new { messagePayload = new { message, isBytes = false } }; - - var requestContent = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"); - - var response = await this._engineClient.PostAsync(url, requestContent).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - - var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - return JObject.Parse(content)["result"].Value(); - } - - public async Task SignTypedDataV4(string json) - { - if (string.IsNullOrEmpty(json)) - { - throw new ArgumentNullException(nameof(json), "Json to sign cannot be null."); - } - - var processedJson = Utils.PreprocessTypedDataJson(json); - // TODO: remove this sanitization when engine is upgraded to match spec - processedJson = processedJson.Replace("message", "value"); - var tempObj = JObject.Parse(processedJson); - _ = tempObj["types"].Value().Remove("EIP712Domain"); - processedJson = tempObj.ToString(); - - var url = $"{this._engineUrl}/backend-wallet/sign-typed-data"; - - var requestContent = new StringContent(processedJson, Encoding.UTF8, "application/json"); - - var response = await this._engineClient.PostAsync(url, requestContent).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - - var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - return JObject.Parse(content)["result"].Value(); - } - - public async Task SignTypedDataV4(T data, TypedData typedData) - where TDomain : IDomain - { - if (data == null) - { - throw new ArgumentNullException(nameof(data), "Data to sign cannot be null."); - } - - var safeJson = Utils.ToJsonExternalWalletFriendly(typedData, data); - return await this.SignTypedDataV4(safeJson).ConfigureAwait(false); - } - - public async Task SignTransaction(ThirdwebTransactionInput transaction) - { - if (transaction == null) - { - throw new ArgumentNullException(nameof(transaction)); - } - - object payload = new { transaction = this.ToEngineTransaction(transaction) }; - - var url = $"{this._engineUrl}/backend-wallet/sign-transaction"; - - var requestContent = new StringContent(JsonConvert.SerializeObject(payload, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }), Encoding.UTF8, "application/json"); - - var response = await this._engineClient.PostAsync(url, requestContent).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - - var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - return JObject.Parse(content)["result"].Value(); - } - - public Task IsConnected() - { - return Task.FromResult(this._walletAddress != null); - } - - public async Task SendTransaction(ThirdwebTransactionInput transaction) - { - if (transaction == null) - { - throw new ArgumentNullException(nameof(transaction)); - } - - var payload = this.ToEngineTransaction(transaction); - - var url = $"{this._engineUrl}/backend-wallet/{transaction.ChainId.Value}/send-transaction"; - - var requestContent = new StringContent(JsonConvert.SerializeObject(payload, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }), Encoding.UTF8, "application/json"); - - var response = await this._engineClient.PostAsync(url, requestContent).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - - var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - var queueId = JObject.Parse(content)["result"]?["queueId"]?.ToString() ?? throw new Exception("Failed to queue the transaction"); - return await WaitForQueueId(this._engineClient, this._engineUrl, queueId).ConfigureAwait(false); - } - - public async Task ExecuteTransaction(ThirdwebTransactionInput transactionInput) - { - var hash = await this.SendTransaction(transactionInput); - return await ThirdwebTransaction.WaitForTransactionReceipt(this.Client, transactionInput.ChainId.Value, hash).ConfigureAwait(false); - } - - public Task Disconnect() - { - return Task.CompletedTask; - } - - public virtual Task RecoverAddressFromEthSign(string message, string signature) - { - throw new InvalidOperationException(); - } - - public virtual Task RecoverAddressFromPersonalSign(string message, string signature) - { - if (string.IsNullOrEmpty(message)) - { - throw new ArgumentNullException(nameof(message), "Message to sign cannot be null."); - } - - if (string.IsNullOrEmpty(signature)) - { - throw new ArgumentNullException(nameof(signature), "Signature cannot be null."); - } - - var signer = new EthereumMessageSigner(); - var address = signer.EncodeUTF8AndEcRecover(message, signature); - return Task.FromResult(address); - } - - public virtual Task RecoverAddressFromTypedDataV4(T data, TypedData typedData, string signature) - where TDomain : IDomain - { - if (data == null) - { - throw new ArgumentNullException(nameof(data), "Data to sign cannot be null."); - } - - if (typedData == null) - { - throw new ArgumentNullException(nameof(typedData), "Typed data cannot be null."); - } - - if (signature == null) - { - throw new ArgumentNullException(nameof(signature), "Signature cannot be null."); - } - - var signer = new Eip712TypedDataSigner(); - var address = signer.RecoverFromSignatureV4(data, typedData, signature); - return Task.FromResult(address); - } - - public Task SignAuthorization(BigInteger chainId, string contractAddress, bool willSelfExecute) - { - throw new NotImplementedException(); - } - - public Task SwitchNetwork(BigInteger chainId) - { - return Task.CompletedTask; - } - - public Task> LinkAccount( - IThirdwebWallet walletToLink, - string otp = null, - bool? isMobile = null, - Action browserOpenAction = null, - string mobileRedirectScheme = "thirdweb://", - IThirdwebBrowser browser = null, - BigInteger? chainId = null, - string jwt = null, - string payload = null, - string defaultSessionIdOverride = null, - List forceWalletIds = null - ) - { - throw new NotImplementedException(); - } - - public Task> UnlinkAccount(LinkedAccount accountToUnlink) - { - throw new NotImplementedException(); - } - - public Task> GetLinkedAccounts() - { - throw new NotImplementedException(); - } - - #endregion -} diff --git a/Thirdweb/Thirdweb.Wallets/IThirdwebWallet.cs b/Thirdweb/Thirdweb.Wallets/IThirdwebWallet.cs index 44663513..390b40c9 100644 --- a/Thirdweb/Thirdweb.Wallets/IThirdwebWallet.cs +++ b/Thirdweb/Thirdweb.Wallets/IThirdwebWallet.cs @@ -30,28 +30,6 @@ public interface IThirdwebWallet /// The wallet address. public Task GetAddress(); - /// - /// Signs a raw message using Ethereum's signing method. - /// - /// The raw message to sign. - /// The signed message. - public Task EthSign(byte[] rawMessage); - - /// - /// Signs a message using Ethereum's signing method. - /// - /// The message to sign. - /// The signed message. - public Task EthSign(string message); - - /// - /// Recovers the address from a signed message using Ethereum's signing method. - /// - /// The UTF-8 encoded message. - /// The signature. - /// The recovered address. - public Task RecoverAddressFromEthSign(string message, string signature); - /// /// Signs a raw message using personal signing. /// @@ -66,14 +44,6 @@ public interface IThirdwebWallet /// The signed message. public Task PersonalSign(string message); - /// - /// Recovers the address from a signed message using personal signing. - /// - /// The UTF-8 encoded and prefixed message. - /// The signature. - /// The recovered address. - public Task RecoverAddressFromPersonalSign(string message, string signature); - /// /// Signs typed data (version 4). /// @@ -92,18 +62,6 @@ public interface IThirdwebWallet public Task SignTypedDataV4(T data, TypedData typedData) where TDomain : IDomain; - /// - /// Recovers the address from a signed message using typed data (version 4). - /// - /// - /// - /// The data to sign. - /// The typed data. - /// The signature. - /// The recovered address. - public Task RecoverAddressFromTypedDataV4(T data, TypedData typedData, string signature) - where TDomain : IDomain; - /// /// Checks if the wallet is connected. /// @@ -149,7 +107,6 @@ public Task RecoverAddressFromTypedDataV4(T data, TypedData< /// The JWT token if linking custom JWT auth. /// The login payload if linking custom AuthEndpoint auth. /// The default session ID override if linking Guest auth. - /// The wallet IDs to force display if linking using SiweExternal auth. /// A list of objects. public Task> LinkAccount( IThirdwebWallet walletToLink, @@ -161,8 +118,7 @@ public Task> LinkAccount( BigInteger? chainId = null, string jwt = null, string payload = null, - string defaultSessionIdOverride = null, - List forceWalletIds = null + string defaultSessionIdOverride = null ); /// diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EcosystemWallet/EcosystemWallet.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/EcosystemWallet/EcosystemWallet.cs index 9ff34068..2af51ebd 100644 --- a/Thirdweb/Thirdweb.Wallets/InAppWallet/EcosystemWallet/EcosystemWallet.cs +++ b/Thirdweb/Thirdweb.Wallets/InAppWallet/EcosystemWallet/EcosystemWallet.cs @@ -2,8 +2,6 @@ using System.Text; using System.Web; using Nethereum.ABI.EIP712; -using Nethereum.Signer; -using Nethereum.Signer.EIP712; using Nethereum.Util; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -34,7 +32,6 @@ public partial class EcosystemWallet : IThirdwebWallet internal readonly string Email; internal readonly string PhoneNumber; internal readonly string AuthProvider; - internal readonly string LegacyEncryptionKey; internal readonly string WalletSecret; internal string Address; @@ -59,7 +56,6 @@ internal EcosystemWallet( string phoneNumber, string authProvider, IThirdwebWallet siweSigner, - string legacyEncryptionKey, string walletSecret, ExecutionMode executionMode, string delegationContractAddress @@ -68,7 +64,6 @@ string delegationContractAddress this.Client = client; this._ecosystemId = ecosystemId; this._ecosystemPartnerId = ecosystemPartnerId; - this.LegacyEncryptionKey = legacyEncryptionKey; this.EmbeddedWallet = embeddedWallet; this.HttpClient = httpClient; this.Email = email; @@ -94,7 +89,6 @@ string delegationContractAddress /// The authentication provider to use. /// The path to the storage directory. /// The SIWE signer wallet for SIWE authentication. - /// The encryption key that is no longer required but was used in the past. Only pass this if you had used custom auth before this was deprecated. /// The wallet secret for Backend authentication. /// The auth token to use for the session. This will automatically connect using a raw thirdweb auth token. /// The execution mode for the wallet. EOA represents traditional direct calls, EIP7702 represents upgraded account self sponsored calls, and EIP7702Sponsored represents upgraded account calls with managed/sponsored execution. @@ -102,14 +96,13 @@ string delegationContractAddress /// Thrown when required parameters are not provided. public static async Task Create( ThirdwebClient client, - string ecosystemId, + string ecosystemId = null, string ecosystemPartnerId = null, string email = null, string phoneNumber = null, AuthProvider authProvider = Thirdweb.AuthProvider.Default, string storageDirectoryPath = null, IThirdwebWallet siweSigner = null, - string legacyEncryptionKey = null, string walletSecret = null, string twAuthTokenOverride = null, ExecutionMode executionMode = ExecutionMode.EOA @@ -120,7 +113,7 @@ public static async Task Create( throw new ArgumentNullException(nameof(client), "Client cannot be null."); } - var delegationContractResponse = await BundlerClient.TwGetDelegationContract(client: client, url: $"https://1.bundler.thirdweb.com", requestId: 7702); + var delegationContractResponse = await ThirdwebBundler.TwGetDelegationContract(client: client, url: $"https://1.bundler.thirdweb.com", requestId: 7702); if (string.IsNullOrEmpty(email) && string.IsNullOrEmpty(phoneNumber) && authProvider == Thirdweb.AuthProvider.Default) { @@ -147,7 +140,6 @@ public static async Task Create( Thirdweb.AuthProvider.Twitch => "Twitch", Thirdweb.AuthProvider.Steam => "Steam", Thirdweb.AuthProvider.Backend => "Backend", - Thirdweb.AuthProvider.SiweExternal => "SiweExternal", Thirdweb.AuthProvider.Default => string.IsNullOrEmpty(email) ? "Phone" : "Email", _ => throw new ArgumentException("Invalid AuthProvider"), }; @@ -195,7 +187,6 @@ public static async Task Create( phoneNumber, authproviderStr, siweSigner, - legacyEncryptionKey, walletSecret, executionMode, delegationContractResponse.DelegationContract @@ -217,7 +208,6 @@ public static async Task Create( phoneNumber, authproviderStr, siweSigner, - legacyEncryptionKey, walletSecret, executionMode, delegationContractResponse.DelegationContract @@ -304,7 +294,7 @@ private async Task PostAuth(Server.VerifyResult result) } else { - address = await this.MigrateShardToEnclave(result).ConfigureAwait(false); + throw new InvalidOperationException("Existing user does not have an enclave wallet."); } } @@ -321,29 +311,6 @@ private async Task PostAuth(Server.VerifyResult result) } } - private async Task MigrateShardToEnclave(Server.VerifyResult authResult) - { - var (address, encryptedPrivateKeyB64, ivB64, kmsCiphertextB64) = await this - .EmbeddedWallet.GenerateEncryptionDataAsync(authResult.AuthToken, this.LegacyEncryptionKey ?? authResult.RecoveryCode) - .ConfigureAwait(false); - - var url = $"{ENCLAVE_PATH}/migrate"; - var payload = new - { - address, - encryptedPrivateKeyB64, - ivB64, - kmsCiphertextB64, - }; - var requestContent = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"); - - var response = await this.HttpClient.PostAsync(url, requestContent).ConfigureAwait(false); - _ = response.EnsureSuccessStatusCode(); - - var userStatus = await GetUserStatus(this.HttpClient).ConfigureAwait(false); - return userStatus.Wallets[0].Address; - } - #endregion #region Wallet Specific @@ -668,8 +635,7 @@ public async Task> LinkAccount( BigInteger? chainId = null, string jwt = null, string payload = null, - string defaultSessionIdOverride = null, - List forceWalletIds = null + string defaultSessionIdOverride = null ) { if (!await this.IsConnected().ConfigureAwait(false)) @@ -740,9 +706,6 @@ public async Task> LinkAccount( case "Guest": serverRes = await ecosystemWallet.PreAuth_Guest(defaultSessionIdOverride).ConfigureAwait(false); break; - case "SiweExternal": - serverRes = await ecosystemWallet.PreAuth_SiweExternal(isMobile ?? false, browserOpenAction, forceWalletIds, mobileRedirectScheme, browser).ConfigureAwait(false); - break; case "Google": case "Apple": case "Facebook": @@ -927,7 +890,7 @@ public async Task LoginWithOtp(string otp) authResultJson = queryDict["authResult"]; } - var serverRes = await this.EmbeddedWallet.SignInWithOauthAsync(authResultJson).ConfigureAwait(false); + var serverRes = this.EmbeddedWallet.SignInWithOauthAsync(authResultJson); return serverRes; } @@ -945,81 +908,6 @@ public async Task LoginWithOauth( #endregion - #region SiweExternal - - private async Task PreAuth_SiweExternal( - bool isMobile, - Action browserOpenAction, - List forceWalletIds = null, - string mobileRedirectScheme = "thirdweb://", - IThirdwebBrowser browser = null, - CancellationToken cancellationToken = default - ) - { - var redirectUrl = isMobile ? mobileRedirectScheme : "http://localhost:8789/"; - var loginUrl = $"https://static.thirdweb.com/auth/siwe?redirectUrl={redirectUrl}"; - if (forceWalletIds != null && forceWalletIds.Count > 0) - { - loginUrl += $"&wallets={string.Join(",", forceWalletIds)}"; - } - - browser ??= new InAppWalletBrowser(); - var browserResult = await browser.Login(this.Client, loginUrl, redirectUrl, browserOpenAction, cancellationToken).ConfigureAwait(false); - switch (browserResult.Status) - { - case BrowserStatus.Success: - break; - case BrowserStatus.UserCanceled: - throw new TaskCanceledException(browserResult.Error ?? "LoginWithSiwe was cancelled."); - case BrowserStatus.Timeout: - throw new TimeoutException(browserResult.Error ?? "LoginWithSiwe timed out."); - case BrowserStatus.UnknownError: - default: - throw new Exception($"Failed to login with {this.AuthProvider}: {browserResult.Status} | {browserResult.Error}"); - } - var callbackUrl = - browserResult.Status != BrowserStatus.Success - ? throw new Exception($"Failed to login with {this.AuthProvider}: {browserResult.Status} | {browserResult.Error}") - : browserResult.CallbackUrl; - - while (string.IsNullOrEmpty(callbackUrl)) - { - if (cancellationToken.IsCancellationRequested) - { - throw new TaskCanceledException("LoginWithSiwe was cancelled."); - } - await ThirdwebTask.Delay(100, cancellationToken).ConfigureAwait(false); - } - - string signature; - string payload; - var decodedUrl = HttpUtility.UrlDecode(callbackUrl); - Uri uri = new(decodedUrl); - var queryString = uri.Query; - var queryDict = HttpUtility.ParseQueryString(queryString); - signature = queryDict["signature"]; - payload = HttpUtility.UrlDecode(queryDict["payload"]); - var payloadData = JsonConvert.DeserializeObject(payload); - - var serverRes = await this.EmbeddedWallet.SignInWithSiweExternalRawAsync(payloadData, signature).ConfigureAwait(false); - return serverRes; - } - - public async Task LoginWithSiweExternal( - bool isMobile, - Action browserOpenAction, - List forceWalletIds = null, - string mobileRedirectScheme = "thirdweb://", - IThirdwebBrowser browser = null, - CancellationToken cancellationToken = default - ) - { - var serverRes = await this.PreAuth_SiweExternal(isMobile, browserOpenAction, forceWalletIds, mobileRedirectScheme, browser, cancellationToken).ConfigureAwait(false); - return await this.PostAuth(serverRes).ConfigureAwait(false); - } - - #endregion - #region Siwe private async Task PreAuth_Siwe(IThirdwebWallet siweSigner, BigInteger chainId) @@ -1139,26 +1027,6 @@ public Task GetAddress() } } - public Task EthSign(byte[] rawMessage) - { - if (rawMessage == null) - { - throw new ArgumentNullException(nameof(rawMessage), "Message to sign cannot be null."); - } - - throw new NotImplementedException(); - } - - public Task EthSign(string message) - { - if (message == null) - { - throw new ArgumentNullException(nameof(message), "Message to sign cannot be null."); - } - - throw new NotImplementedException(); - } - public async Task PersonalSign(byte[] rawMessage) { if (rawMessage == null) @@ -1336,7 +1204,7 @@ public async Task SendTransaction(ThirdwebTransactionInput transaction) case ExecutionMode.EIP7702Sponsored: var wrappedCalls = new WrappedCalls() { Calls = calls, Uid = Guid.NewGuid().ToByteArray().PadTo32Bytes() }; var signature = await EIP712.GenerateSignature_SmartAccount_7702_WrappedCalls("MinimalAccount", "1", transaction.ChainId, userWalletAddress, wrappedCalls, this); - var response = await BundlerClient.TwExecute( + var response = await ThirdwebBundler.TwExecute( client: this.Client, url: $"https://{transaction.ChainId}.bundler.thirdweb.com", requestId: 7702, @@ -1354,7 +1222,7 @@ public async Task SendTransaction(ThirdwebTransactionInput transaction) { ct.Token.ThrowIfCancellationRequested(); - var hashResponse = await BundlerClient + var hashResponse = await ThirdwebBundler .TwGetTransactionHash(client: this.Client, url: $"https://{transaction.ChainId}.bundler.thirdweb.com", requestId: 7702, queueId) .ConfigureAwait(false); @@ -1384,51 +1252,6 @@ public async Task Disconnect() await this.EmbeddedWallet.SignOutAsync().ConfigureAwait(false); } - public virtual Task RecoverAddressFromEthSign(string message, string signature) - { - throw new InvalidOperationException(); - } - - public virtual Task RecoverAddressFromPersonalSign(string message, string signature) - { - if (string.IsNullOrEmpty(message)) - { - throw new ArgumentNullException(nameof(message), "Message to sign cannot be null."); - } - - if (string.IsNullOrEmpty(signature)) - { - throw new ArgumentNullException(nameof(signature), "Signature cannot be null."); - } - - var signer = new EthereumMessageSigner(); - var address = signer.EncodeUTF8AndEcRecover(message, signature); - return Task.FromResult(address); - } - - public virtual Task RecoverAddressFromTypedDataV4(T data, TypedData typedData, string signature) - where TDomain : IDomain - { - if (data == null) - { - throw new ArgumentNullException(nameof(data), "Data to sign cannot be null."); - } - - if (typedData == null) - { - throw new ArgumentNullException(nameof(typedData), "Typed data cannot be null."); - } - - if (signature == null) - { - throw new ArgumentNullException(nameof(signature), "Signature cannot be null."); - } - - var signer = new Eip712TypedDataSigner(); - var address = signer.RecoverFromSignatureV4(data, typedData, signature); - return Task.FromResult(address); - } - public async Task SignAuthorization(BigInteger chainId, string contractAddress, bool willSelfExecute) { var nonce = await this.GetTransactionCount(chainId); diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Authentication/AWS.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Authentication/AWS.cs deleted file mode 100644 index d66a26e3..00000000 --- a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Authentication/AWS.cs +++ /dev/null @@ -1,300 +0,0 @@ -using System.Security.Cryptography; -using System.Text; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Thirdweb.EWS; - -internal class AWS -{ - private const string AWS_REGION = "us-west-2"; - - private static readonly string _recoverySharePasswordLambdaFunctionNameV2 = $"arn:aws:lambda:{AWS_REGION}:324457261097:function:lambda-thirdweb-auth-enc-key-prod-ThirdwebAuthEncKeyFunction"; - private static readonly string _migrationKeyId = $"arn:aws:kms:{AWS_REGION}:324457261097:key/ccfb9ecd-f45d-4f37-864a-25fe72dcb49e"; - - internal static async Task InvokeRecoverySharePasswordLambdaAsync(string identityId, string token, string invokePayload, IThirdwebHttpClient httpClient) - { - var credentials = await GetTemporaryCredentialsAsync(identityId, token, httpClient).ConfigureAwait(false); - return await InvokeLambdaWithTemporaryCredentialsAsync(credentials, invokePayload, httpClient, _recoverySharePasswordLambdaFunctionNameV2).ConfigureAwait(false); - } - - internal static async Task GenerateDataKey(string identityId, string token, IThirdwebHttpClient httpClient) - { - var credentials = await GetTemporaryCredentialsAsync(identityId, token, httpClient).ConfigureAwait(false); - return await GenerateDataKey(credentials, httpClient).ConfigureAwait(false); - } - - private static async Task GetTemporaryCredentialsAsync(string identityId, string token, IThirdwebHttpClient httpClient) - { - var client = Utils.ReconstructHttpClient(httpClient); - var endpoint = $"https://cognito-identity.{AWS_REGION}.amazonaws.com/"; - - var payloadForGetCredentials = new { IdentityId = identityId, Logins = new Dictionary { { "cognito-identity.amazonaws.com", token } } }; - - var content = new StringContent(JsonConvert.SerializeObject(payloadForGetCredentials), Encoding.UTF8, "application/x-amz-json-1.1"); - - client.AddHeader("X-Amz-Target", "AWSCognitoIdentityService.GetCredentialsForIdentity"); - - var response = await client.PostAsync(endpoint, content).ConfigureAwait(false); - var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - - if (!response.IsSuccessStatusCode) - { - throw new Exception($"Failed to get credentials: {responseContent}"); - } - - var credentialsResponse = JsonConvert.DeserializeObject(responseContent); - - return new AwsCredentials - { - AccessKeyId = credentialsResponse.Credentials.AccessKeyId, - SecretAccessKey = credentialsResponse.Credentials.SecretKey, - SessionToken = credentialsResponse.Credentials.SessionToken, - }; - } - - private static async Task GenerateDataKey(AwsCredentials credentials, IThirdwebHttpClient httpClient) - { - var endpoint = $"https://kms.{AWS_REGION}.amazonaws.com/"; - - var payloadForGenerateDataKey = new { KeyId = _migrationKeyId, KeySpec = "AES_256" }; - var requestBodyString = JsonConvert.SerializeObject(payloadForGenerateDataKey); - - var contentType = "application/x-amz-json-1.1"; - - var extraHeaders = new Dictionary { { "X-Amz-Target", "TrentService.GenerateDataKey" } }; - - var responseContent = await PostAwsRequestWithDateOverride(credentials, httpClient, AWS_REGION, "kms", endpoint, "/", "", requestBodyString, contentType, extraHeaders).ConfigureAwait(false); - - var responseObject = JToken.Parse(responseContent); - var plaintextKeyBlob = responseObject["Plaintext"]; - var cipherTextBlob = responseObject["CiphertextBlob"]; - - if (plaintextKeyBlob == null || cipherTextBlob == null) - { - throw new Exception("No migration key found. Please try again."); - } - - return responseObject; - } - - private static async Task InvokeLambdaWithTemporaryCredentialsAsync(AwsCredentials credentials, string invokePayload, IThirdwebHttpClient httpClient, string lambdaFunction) - { - var endpoint = $"https://lambda.{AWS_REGION}.amazonaws.com/2015-03-31/functions/{lambdaFunction}/invocations"; - var contentType = "application/json"; - - var canonicalUri = $"/2015-03-31/functions/{Uri.EscapeDataString(lambdaFunction)}/invocations"; - var canonicalQueryString = ""; - - var extraHeaders = new Dictionary(); - - var responseContent = await PostAwsRequestWithDateOverride( - credentials, - httpClient, - AWS_REGION, - "lambda", - endpoint, - canonicalUri, - canonicalQueryString, - invokePayload, - contentType, - extraHeaders - ) - .ConfigureAwait(false); - - var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(responseContent)); - return memoryStream; - } - - private static async Task PostAwsRequestWithDateOverride( - AwsCredentials credentials, - IThirdwebHttpClient httpClient, - string region, - string service, - string endpoint, - string canonicalUri, - string canonicalQueryString, - string requestBodyString, - string contentType, - Dictionary extraHeaders, - DateTime? dateOverride = null - ) - { - var client = Utils.ReconstructHttpClient(httpClient); - - if (extraHeaders != null) - { - foreach (var kvp in extraHeaders) - { - client.AddHeader(kvp.Key, kvp.Value); - } - } - - var dateTimeNow = dateOverride ?? DateTime.UtcNow; - var amzDateFormat = "yyyyMMddTHHmmssZ"; - var amzDate = dateTimeNow.ToString(amzDateFormat, System.Globalization.CultureInfo.InvariantCulture); - var dateStamp = dateTimeNow.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture); - - var canonicalHeaders = $"host:{new Uri(endpoint).Host}\n" + $"x-amz-date:{amzDate}\n"; - var signedHeaders = "host;x-amz-date"; - -#if NETSTANDARD - using var sha256 = SHA256.Create(); - var payloadHash = ToHexString(sha256.ComputeHash(Encoding.UTF8.GetBytes(requestBodyString))); -#else - var payloadHash = ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(requestBodyString))); -#endif - - var canonicalRequest = $"POST\n{canonicalUri}\n{canonicalQueryString}\n{canonicalHeaders}\n{signedHeaders}\n{payloadHash}"; - - var algorithm = "AWS4-HMAC-SHA256"; - var credentialScope = $"{dateStamp}/{region}/{service}/aws4_request"; -#if NETSTANDARD - var stringToSign = $"{algorithm}\n{amzDate}\n{credentialScope}\n{ToHexString(sha256.ComputeHash(Encoding.UTF8.GetBytes(canonicalRequest)))}"; -#else - var stringToSign = $"{algorithm}\n{amzDate}\n{credentialScope}\n{ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(canonicalRequest)))}"; -#endif - - var signingKey = GetSignatureKey(credentials.SecretAccessKey, dateStamp, region, service); - var signature = ToHexString(HMACSHA256(signingKey, stringToSign)); - - var authorizationHeader = $"{algorithm} Credential={credentials.AccessKeyId}/{credentialScope}, SignedHeaders={signedHeaders}, Signature={signature}"; - - client.AddHeader("x-amz-date", amzDate); - client.AddHeader("Authorization", authorizationHeader); - - if (!string.IsNullOrEmpty(credentials.SessionToken)) - { - client.AddHeader("x-amz-security-token", credentials.SessionToken); - } - - var content = new StringContent(requestBodyString, Encoding.UTF8, contentType); - - var response = await client.PostAsync(endpoint, content).ConfigureAwait(false); - var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - - if (!response.IsSuccessStatusCode) - { - if (dateOverride == null && responseContent.Contains("Signature expired")) - { - var idx = responseContent.LastIndexOf('('); - if (idx > -1) - { - var parsedTimeString = responseContent.Substring(idx + 1, amzDate.Length); - var serverTime = DateTime.ParseExact(parsedTimeString, amzDateFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal); - - return await PostAwsRequestWithDateOverride( - credentials, - httpClient, - region, - service, - endpoint, - canonicalUri, - canonicalQueryString, - requestBodyString, - contentType, - extraHeaders, - serverTime - ) - .ConfigureAwait(false); - } - } - - throw new Exception($"AWS request failed: {responseContent}"); - } - - return responseContent; - } - - private static byte[] HMACSHA256(byte[] key, string data) - { - using var hmac = new HMACSHA256(key); - return hmac.ComputeHash(Encoding.UTF8.GetBytes(data)); - } - - private static byte[] GetSignatureKey(string key, string dateStamp, string regionName, string serviceName) - { - var kDate = HMACSHA256(Encoding.UTF8.GetBytes("AWS4" + key), dateStamp); - var kRegion = HMACSHA256(kDate, regionName); - var kService = HMACSHA256(kRegion, serviceName); - var kSigning = HMACSHA256(kService, "aws4_request"); - return kSigning; - } - - private static string ToHexString(byte[] bytes) - { - var hex = new StringBuilder(bytes.Length * 2); - foreach (var b in bytes) - { - _ = hex.AppendFormat("{0:x2}", b); - } - return hex.ToString(); - } - - internal class GetIdResponse - { - public string IdentityId { get; set; } - } - - internal class GetCredentialsForIdentityResponse - { - public Credentials Credentials { get; set; } - } - - internal class Credentials - { - public string AccessKeyId { get; set; } - public string SecretKey { get; set; } - public string SessionToken { get; set; } - } - - internal class AwsCredentials - { - public string AccessKeyId { get; set; } - public string SecretAccessKey { get; set; } - public string SessionToken { get; set; } - } - - internal class CredentialsResponse - { - public Credentials Credentials { get; set; } - } - - internal class StartAuthResponse - { - public string Session { get; set; } - } - - internal class FinishAuthResponse - { - public AuthenticationResult AuthenticationResult { get; set; } - } - - internal class AuthenticationResult - { - public string AccessToken { get; set; } - public string IdToken { get; set; } - public string RefreshToken { get; set; } - } - - internal class ErrorResponse - { - [JsonProperty("__type")] - public string Type { get; set; } - public string Message { get; set; } - } - - internal class TokenCollection - { - internal TokenCollection(string accessToken, string idToken, string refreshToken) - { - this.AccessToken = accessToken; - this.IdToken = idToken; - this.RefreshToken = refreshToken; - } - - public string AccessToken { get; } - public string IdToken { get; } - public string RefreshToken { get; } - } -} diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Encryption/EmbeddedWallet.Cryptography.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Encryption/EmbeddedWallet.Cryptography.cs deleted file mode 100644 index 075d9ae4..00000000 --- a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Encryption/EmbeddedWallet.Cryptography.cs +++ /dev/null @@ -1,128 +0,0 @@ -using System.Security.Cryptography; -using System.Text; -using Nethereum.Web3.Accounts; -using Org.BouncyCastle.Crypto.Digests; -using Org.BouncyCastle.Crypto.Engines; -using Org.BouncyCastle.Crypto.Generators; -using Org.BouncyCastle.Crypto.Modes; -using Org.BouncyCastle.Crypto.Parameters; - -namespace Thirdweb.EWS; - -internal partial class EmbeddedWallet -{ - private static async Task DecryptShareAsync(string encryptedShare, string password) - { - var parts = encryptedShare.Split(ENCRYPTION_SEPARATOR); - var ciphertextWithTag = Convert.FromBase64String(parts[0]); - var iv = Convert.FromBase64String(parts[1]); - var salt = Convert.FromBase64String(parts[2]); - - var iterationCount = parts.Length > 3 && int.TryParse(parts[3], out var parsedIterationCount) ? parsedIterationCount : DEPRECATED_ITERATION_COUNT; - var key = await GetEncryptionKeyAsync(password, salt, iterationCount).ConfigureAwait(false); - - byte[] encodedShare; - try - { - // Bouncy Castle expects the authentication tag after the ciphertext. - GcmBlockCipher cipher = new(new AesEngine()); - cipher.Init(forEncryption: false, new AeadParameters(new KeyParameter(key), 8 * TAG_SIZE, iv)); - encodedShare = new byte[cipher.GetOutputSize(ciphertextWithTag.Length)]; - var offset = cipher.ProcessBytes(ciphertextWithTag, 0, ciphertextWithTag.Length, encodedShare, 0); - cipher.DoFinal(encodedShare, offset); - } - catch - { - try - { - var ciphertextSize = ciphertextWithTag.Length - TAG_SIZE; - var ciphertext = new byte[ciphertextSize]; - Array.Copy(ciphertextWithTag, ciphertext, ciphertext.Length); - var tag = new byte[TAG_SIZE]; - Array.Copy(ciphertextWithTag, ciphertextSize, tag, 0, tag.Length); - encodedShare = new byte[ciphertext.Length]; -#if NET8_0_OR_GREATER - using AesGcm crypto = new(key, TAG_SIZE); -#else - using AesGcm crypto = new(key); -#endif - crypto.Decrypt(iv, ciphertext, tag, encodedShare); - } - catch (CryptographicException) - { - throw new VerificationException(true); - } - } - var share = Encoding.ASCII.GetString(encodedShare); - return share; - } - - private async Task EncryptShareAsync(string share, string password) - { - const int saltSize = 16; - var salt = new byte[saltSize]; - RandomNumberGenerator.Fill(salt); - - var key = await GetEncryptionKeyAsync(password, salt, CURRENT_ITERATION_COUNT).ConfigureAwait(false); - var encodedShare = Encoding.ASCII.GetBytes(share); - const int ivSize = 12; - var iv = new byte[ivSize]; - await this._ivGenerator.ComputeIvAsync(iv).ConfigureAwait(false); - byte[] encryptedShare; - try - { - // Bouncy Castle includes the authentication tag after the ciphertext. - GcmBlockCipher cipher = new(new AesEngine()); - cipher.Init(forEncryption: true, new AeadParameters(new KeyParameter(key), 8 * TAG_SIZE, iv)); - encryptedShare = new byte[cipher.GetOutputSize(encodedShare.Length)]; - var offset = cipher.ProcessBytes(encodedShare, 0, encodedShare.Length, encryptedShare, 0); - cipher.DoFinal(encryptedShare, offset); - } - catch - { - var tag = new byte[TAG_SIZE]; - encryptedShare = new byte[encodedShare.Length]; -#if NET8_0_OR_GREATER - using AesGcm crypto = new(key, TAG_SIZE); -#else - using AesGcm crypto = new(key); -#endif - crypto.Encrypt(iv, encodedShare, encryptedShare, tag); - encryptedShare = encryptedShare.Concat(tag).ToArray(); - } - var rv = - $"{Convert.ToBase64String(encryptedShare)}{ENCRYPTION_SEPARATOR}{Convert.ToBase64String(iv)}{ENCRYPTION_SEPARATOR}{Convert.ToBase64String(salt)}{ENCRYPTION_SEPARATOR}{CURRENT_ITERATION_COUNT}"; - return rv; - } - - private static (string deviceShare, string recoveryShare, string authShare) CreateShares(string secret) - { - Secrets secrets = new(); - secret = $"{WALLET_PRIVATE_KEY_PREFIX}{secret}"; - var encodedSecret = Secrets.GetHexString(Encoding.ASCII.GetBytes(secret)); - var shares = secrets.Share(encodedSecret, 3, 2); - return (shares[0], shares[1], shares[2]); - } - - private static async Task GetEncryptionKeyAsync(string password, byte[] salt, int iterationCount) - { - return await Task.Run(() => - { - var generator = new Pkcs5S2ParametersGenerator(new Sha256Digest()); - var keyLength = KEY_SIZE * 8; // will be redivided by 8 internally - generator.Init(Encoding.UTF8.GetBytes(password), salt, iterationCount); - var keyParam = (KeyParameter)generator.GenerateDerivedMacParameters(keyLength); - return keyParam.GetKey(); - }) - .ConfigureAwait(false); - } - - private static Account MakeAccountFromShares(params string[] shares) - { - Secrets secrets = new(); - var encodedSecret = secrets.Combine(shares); - var secret = Encoding.ASCII.GetString(Secrets.GetBytes(encodedSecret)); - - return !secret.StartsWith(WALLET_PRIVATE_KEY_PREFIX) ? throw new InvalidOperationException($"Corrupted share encountered {secret}") : new Account(secret.Split(WALLET_PRIVATE_KEY_PREFIX)[1]); - } -} diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Encryption/IvGenerator.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Encryption/IvGenerator.cs deleted file mode 100644 index 74936531..00000000 --- a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Encryption/IvGenerator.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System.Security.Cryptography; - -namespace Thirdweb.EWS; - -internal abstract class IvGeneratorBase -{ - internal abstract Task ComputeIvAsync(byte[] iv); -} - -internal class IvGenerator : IvGeneratorBase -{ - private const int NPrbsBits = 48; - private const long PrbsPeriod = (1L << NPrbsBits) - 1; - - private long _prbsValue; - private readonly string _ivFilePath; - private static readonly long _taps = new int[] { NPrbsBits, 47, 21, 20 }.Aggregate(0L, (a, b) => a + (1L << (NPrbsBits - b))); // https://docs.xilinx.com/v/u/en-US/xapp052, page 5 - - internal IvGenerator(string storageDirectoryPath) - { - storageDirectoryPath = Path.Combine(storageDirectoryPath, "IV"); - _ = Directory.CreateDirectory(storageDirectoryPath); - this._ivFilePath = Path.Combine(storageDirectoryPath, "iv.txt"); - try - { - this._prbsValue = long.Parse(File.ReadAllText(this._ivFilePath)); - } - catch (Exception) - { - this._prbsValue = (0x434a49445a27 ^ DateTime.Now.Ticks) & PrbsPeriod; - } - } - - /// - /// Compute IV using half LFSR-generated and half random bytes. - /// - /// https://crypto.stackexchange.com/questions/84357/what-are-the-rules-for-using-aes-gcm-correctly - /// The IV byte array to fill. This must be twelve bytes in size. - internal override async Task ComputeIvAsync(byte[] iv) - { - RandomNumberGenerator.Fill(iv); - this._prbsValue = ComputeNextPrbsValue(this._prbsValue); - await File.WriteAllTextAsync(this._ivFilePath, this._prbsValue.ToString()).ConfigureAwait(false); - var prbsBytes = Enumerable.Range(0, NPrbsBits / 8).Select((i) => (byte)(this._prbsValue >> (8 * i))).ToArray(); - Array.Copy(prbsBytes, iv, prbsBytes.Length); - } - - /// - /// Compute the next value of a PRBS using a 48-bit Galois LFSR. - /// - /// https://en.wikipedia.org/wiki/Linear-feedback_shift_register - /// The current PRBS value. - /// The next value. - private static long ComputeNextPrbsValue(long prbsValue) - { - prbsValue <<= 1; - if ((prbsValue & (1L << NPrbsBits)) != 0) - { - prbsValue ^= _taps; - prbsValue &= PrbsPeriod; - } - return prbsValue; - } -} diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Encryption/Secrets.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Encryption/Secrets.cs deleted file mode 100644 index a55c0868..00000000 --- a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Encryption/Secrets.cs +++ /dev/null @@ -1,470 +0,0 @@ -using System.Globalization; -using System.Security.Cryptography; -using System.Text; -using System.Text.RegularExpressions; - -namespace Thirdweb.EWS; - -internal class Secrets -{ - private Config _config = new(Defaults.NBits); - private const int NHexDigitBits = 4; - private readonly Func _getRandomInt32 = (nBits) => RandomNumberGenerator.GetInt32(1, 1 << nBits); - private static readonly string _padding = string.Join("", Enumerable.Repeat("0", Defaults.MaxPaddingMultiple)); - private static readonly string[] _nybbles = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" }; - - /// - /// Reconsitute a secret from . - /// - /// - /// The return value will not be the original secret if the number of shares provided is less than the threshold - /// number of shares. - /// Duplicate shares do not count toward the threshold. - /// - /// The shares used to reconstitute the secret. - /// The reconstituted secret. - public string Combine(IReadOnlyList shares) - { - return this.Combine(shares, 0); - } - - /// - /// Convert a string of hexadecimal digits into a byte array. - /// - /// The string of hexadecimal digits to convert. - /// A byte array. - public static byte[] GetBytes(string s) - { - var bytes = Enumerable.Range(0, s.Length / 2).Select((i) => byte.Parse(s.Substring(i * 2, 2), NumberStyles.HexNumber)).ToArray(); - return bytes; - } - - /// - /// Convert a byte array into a string of hexadecimal digits. - /// - /// The byte array to convert. - /// A string of hexadecimal digits. - public static string GetHexString(byte[] bytes) - { - return BitConverter.ToString(bytes).Replace("-", "").ToLowerInvariant(); - } - - /// - /// Generate a new share identified as . - /// - /// - /// The return value will be invalid if the number of shares provided is less than the threshold number of shares. - /// If is the identifier of a share in and the number of shares - /// provided is at least the threshold number of shares, the return value will be the same as the identified share. - /// Duplicate shares do not count toward the threshold. - /// - /// The identifier of the share to generate. - /// The shares from which to generate the new share. - /// A hexadecimal string of the new share. - /// - /// - public string NewShare(int shareId, IReadOnlyList shares) - { - if (shareId <= 0) - { - throw new ArgumentOutOfRangeException(nameof(shareId), $"{nameof(shareId)} must be greater than zero."); - } - else if (shares == null || !shares.Any() || string.IsNullOrEmpty(shares[0])) - { - throw new ArgumentException($"{nameof(shares)} cannot be empty.", nameof(shares)); - } - var share = ExtractShareComponents(shares[0]); - return ConstructPublicShareString(share.NBits, Convert.ToString(shareId, Defaults.Radix), this.Combine(shares, shareId)); - } - - /// - /// Generate a random value expressed as a string of hexadecimal digits that contains bytes using a - /// secure random number generator. - /// - /// The number of bytes of output. - /// A hexadecimal string of the value. - /// - public static string Random(int nBytes) - { - const int maxnBytes = (1 << 16) / 8; - if (nBytes is < 1 or > maxnBytes) - { - throw new ArgumentOutOfRangeException(nameof(nBytes), $"{nameof(nBytes)} must be in the range [1, {maxnBytes}]."); - } - var bytes = new byte[nBytes]; - RandomNumberGenerator.Fill(bytes); - var rv = GetHexString(bytes); - return rv; - } - - /// - /// Divide a into - /// shares, requiring shares to - /// reconstruct the secret. Optionally, initialize with . Optionally, zero-pad the secret to a length - /// that is a multiple of (default 128) before sharing. - /// - /// A secret value expressed as a string of hexadecimal digits. - /// The number of shares to produce. - /// The number of shares required to reconstruct the secret. - /// The number of bits to use to create the shares. - /// The amount of zero-padding to apply to the secret before sharing. - /// A list of strings of hexadecimal digits. - /// - /// - public List Share(string secret, int nShares, int threshold, int nBits = 0, int paddingMultiple = 128) - { - // Initialize based on nBits if it's specified. - if (nBits != 0) - { - if (nBits is < Defaults.MinnBits or > Defaults.MaxnBits) - { - throw new ArgumentOutOfRangeException(nameof(nBits), $"{nameof(nBits)} must be in the range [{Defaults.MinnBits}, {Defaults.MaxnBits}]."); - } - this._config = new(nBits); - } - - // Validate the parameters. - if (string.IsNullOrEmpty(secret)) - { - throw new ArgumentException($"{nameof(secret)} cannot be empty.", nameof(secret)); - } - else if (!secret.All((ch) => char.IsDigit(ch) || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'))) - { - throw new ArgumentException($"{nameof(secret)} must consist only of hexadecimal digits.", nameof(secret)); - } - else if (nShares < 2 || nShares > Math.Min(this._config.MaxnShares, Defaults.MaxnShares)) - { - if (nShares > Defaults.MaxnShares) - { - throw new ArgumentOutOfRangeException(nameof(nShares), $"The maximum number of shares is {Defaults.MaxnShares} since the maximum bit count is {Defaults.MaxnBits}."); - } - else if (nShares > this._config.MaxnShares) - { - throw new ArgumentOutOfRangeException( - nameof(nShares), - $"{nameof(nShares)} must be in the range [2, {this._config.MaxnShares}]. To create {nShares} shares, specify at least {Math.Ceiling(Math.Log(nShares + 1, 2))} bits." - ); - } - throw new ArgumentOutOfRangeException(nameof(nShares), $"{nameof(nShares)} must be in the range [2, {this._config.MaxnShares}]."); - } - else if (threshold < 2 || threshold > nShares) - { - throw new ArgumentOutOfRangeException(nameof(threshold), $"{nameof(threshold)} must be in the range [2, {nShares}]."); - } - else if (paddingMultiple is < 0 or > 1024) - { - throw new ArgumentOutOfRangeException(nameof(paddingMultiple), $"{nameof(paddingMultiple)} must be in the range [0, {Defaults.MaxPaddingMultiple}]."); - } - - // Prepend a 1 as a marker to preserve the correct number of leading zeros in the secret. - secret = "1" + Hex2bin(secret); - - // Create the shares. For additional security, pad in multiples of 128 bits by default. This is a small trade-off in larger - // share size to help prevent leakage of information about small secrets and increase the difficulty of attacking them. - var l = this.SplitNumStringToIntArray(secret, paddingMultiple); - var x = new string[nShares]; - var y = new string[nShares]; - foreach (var value in l) - { - var subShares = this.GetShares(value, nShares, threshold); - for (var i = 0; i < nShares; ++i) - { - x[i] = Convert.ToString(subShares[i].x, Defaults.Radix); - y[i] = PadLeft(Convert.ToString(subShares[i].y, 2), this._config.NBits) + (y[i] ?? ""); - } - } - for (var i = 0; i < nShares; ++i) - { - x[i] = ConstructPublicShareString(this._config.NBits, x[i], Bin2hex(y[i])); - } - return x.ToList(); - } - - private static string Bin2hex(string value) - { - value = PadLeft(value, NHexDigitBits); - StringBuilder sb = new(); - for (var i = 0; i < value.Length; i += NHexDigitBits) - { - var num = Convert.ToInt32(value.Substring(i, NHexDigitBits), 2); - _ = sb.Append(Convert.ToString(num, 16)); - } - return sb.ToString(); - } - - private string Combine(IReadOnlyList shares, int shareId) - { - // Zip distinct shares. E.g. - // [ [ 193, 186, 29, 177, 196 ], - // [ 53, 105, 139, 127, 149 ], - // [ 146, 211, 249, 206, 81 ] ] - // becomes - // [ [ 193, 53, 146 ], - // [ 186, 105, 211 ], - // [ 29, 139, 249 ], - // [ 177, 127, 206 ], - // [ 196, 149, 81 ] ] - var nBits = 0; - List x = new(); - List> y = new(); - foreach (var share in shares.Select(ExtractShareComponents)) - { - // All shares must have the same bits settings. - if (nBits == 0) - { - nBits = share.NBits; - - // Reconfigure based on the bits settings of the shares. - if (this._config.NBits != nBits) - { - this._config = new(nBits); - } - } - else if (share.NBits != nBits) - { - throw new ArgumentException("Shares are mismatched due to different bits settings.", nameof(shares)); - } - - // Spread the share across the arrays if the share.id is not already in array `x`. - if (x.IndexOf(share.Id) == -1) - { - x.Add(share.Id); - var splitShare = this.SplitNumStringToIntArray(Hex2bin(share.Data)); - for (int i = 0, n = splitShare.Count; i < n; ++i) - { - if (i >= y.Count) - { - y.Add([]); - } - y[i].Add(splitShare[i]); - } - } - } - - // Extract the secret from the zipped share data. - StringBuilder sb = new(); - foreach (var y_ in y) - { - _ = sb.Insert(0, PadLeft(Convert.ToString(this.Lagrange(shareId, x, y_), 2), nBits)); - } - var result = sb.ToString(); - - // If `shareId` is not zero, NewShare invoked Combine. In this case, return the new share data directly. Otherwise, find - // the first '1' which was added in the Share method as a padding marker and return only the data after the padding and the - // marker. Convert the binary string, which is the derived secret, to hexadecimal. - return Bin2hex(shareId >= 1 ? result : result[(result.IndexOf('1') + 1)..]); - } - - private static string ConstructPublicShareString(int nBits, string shareId, string data) - { - var id = Convert.ToInt32(shareId, Defaults.Radix); - var base36Bits = char.ConvertFromUtf32(nBits > 9 ? nBits - 10 + 'A' : nBits + '0'); - var idMax = (1 << nBits) - 1; - var paddingMultiple = Convert.ToString(idMax, Defaults.Radix).Length; - var hexId = PadLeft(Convert.ToString(id, Defaults.Radix), paddingMultiple); - if (id < 1 || id > idMax) - { - throw new ArgumentOutOfRangeException(nameof(shareId), $"{nameof(shareId)} must be in the range [1, {idMax}]."); - } - var share = base36Bits + hexId + data; - return share; - } - - private static ShareComponents ExtractShareComponents(string share) - { - // Extract the first character which represents the number of bits in base 36. - var nBits = GetLargeBaseValue(share[0]); - if (nBits is < Defaults.MinnBits or > Defaults.MaxnBits) - { - throw new ArgumentException($"Unexpected {nBits}-bit share outside of the range [{Defaults.MinnBits}, {Defaults.MaxnBits}].", nameof(share)); - } - - // Calculate the maximum number of shares allowed for the given number of bits. - var maxnShares = (1 << nBits) - 1; - - // Derive the identifier length from the bit count. - var idLength = Convert.ToString(maxnShares, Defaults.Radix).Length; - - // Extract all the parts now that the segment sizes are known. - var rx = new Regex("^([3-9A-Ka-k]{1})([0-9A-Fa-f]{" + idLength + "})([0-9A-Fa-f]+)$"); - var shareComponents = rx.Matches(share); - var groups = shareComponents.FirstOrDefault()?.Groups; - if (groups == null || groups.Count != 4) - { - throw new ArgumentException("Malformed share", nameof(share)); - } - - // Convert the identifier from a string of hexadecimal digits into an integer. - var id = Convert.ToInt32(groups[2].Value, Defaults.Radix); - - // Return the components of the share. - ShareComponents rv = new(nBits, id, groups[3].Value); - return rv; - } - - private static int GetLargeBaseValue(char ch) - { - var rv = - ch >= 'a' ? ch - 'a' + 10 - : ch >= 'A' ? ch - 'A' + 10 - : ch - '0'; - return rv; - } - - private (int x, int y)[] GetShares(int secret, int nShares, int threshold) - { - var coefficients = Enumerable.Range(0, threshold - 1).Select((i) => this._getRandomInt32(this._config.NBits)).Concat(new[] { secret }).ToArray(); - var shares = Enumerable.Range(1, nShares).Select((i) => (i, this.Horner(i, coefficients))).ToArray(); - return shares; - } - - private static string Hex2bin(string value) - { - StringBuilder sb = new(); - foreach (var ch in value) - { - _ = sb.Append(_nybbles[GetLargeBaseValue(ch)]); - } - return sb.ToString(); - } - - // Evaluate the polynomial at `x` using Horner's Method. - // NOTE: fx = fx * x + coefficients[i] -> exp(log(fx) + log(x)) + coefficients[i], so if fx is zero, set fx to coefficients[i] - // since using the exponential or logarithmic form will result in an incorrect value. - private int Horner(int x, IEnumerable coefficients) - { - var logx = this._config.Logarithms[x]; - var fx = 0; - foreach (var coefficient in coefficients) - { - fx = fx == 0 ? coefficient : this._config.Exponents[(logx + this._config.Logarithms[fx]) % this._config.MaxnShares] ^ coefficient; - } - return fx; - } - - // Evaluate the Lagrange interpolation polynomial at x = `shareId` using x and y arrays that are of the same length, with - // corresponding elements constituting points on the polynomial. - private int Lagrange(int shareId, IReadOnlyList x, IReadOnlyList y) - { - var sum = 0; - foreach (var i in Enumerable.Range(0, x.Count)) - { - if (i < y.Count && y[i] != 0) - { - var product = this._config.Logarithms[y[i]]; - foreach (var j in Enumerable.Range(0, x.Count).Where((j) => i != j)) - { - if (shareId == x[j]) - { - // This happens when computing a share that is in the list of shares used to compute it. - product = -1; - break; - } - - // Ensure it's not negative. - product = (product + this._config.Logarithms[shareId ^ x[j]] - this._config.Logarithms[x[i] ^ x[j]] + this._config.MaxnShares) % this._config.MaxnShares; - } - sum = product == -1 ? sum : sum ^ this._config.Exponents[product]; - } - } - return sum; - } - - private static string PadLeft(string value, int paddingMultiple) - { - if (paddingMultiple == 1) - { - return value; - } - else if (paddingMultiple is < 2 or > Defaults.MaxPaddingMultiple) - { - throw new ArgumentOutOfRangeException(nameof(paddingMultiple), $"{nameof(paddingMultiple)} must be in the range [0, {Defaults.MaxPaddingMultiple}]."); - } - if (value.Length != 0) - { - var extra = value.Length % paddingMultiple; - if (extra > 0) - { - var s = _padding + value; - value = s[^(paddingMultiple - extra + value.Length)..]; - } - } - return value; - } - - private List SplitNumStringToIntArray(string value, int paddingMultiple = 0) - { - if (paddingMultiple > 0) - { - value = PadLeft(value, paddingMultiple); - } - List parts = new(); - int i; - for (i = value.Length; i > this._config.NBits; i -= this._config.NBits) - { - parts.Add(Convert.ToInt32(value.Substring(i - this._config.NBits, this._config.NBits), 2)); - } - parts.Add(Convert.ToInt32(value[..i], 2)); - return parts; - } - - private class Config - { - internal readonly int[] Exponents; - internal readonly int[] Logarithms; - internal readonly int MaxnShares; - internal readonly int NBits; - - internal Config(int nBits) - { - // Set the scalar values. - this.NBits = nBits; - var size = 1 << nBits; - this.MaxnShares = size - 1; - - // Construct the exponent and logarithm tables for multiplication. - var primitive = Defaults.PrimitivePolynomialCoefficients[nBits]; - this.Exponents = new int[size]; - this.Logarithms = new int[size]; - for (int x = 1, i = 0; i < size; ++i) - { - this.Exponents[i] = x; - this.Logarithms[x] = i; - x <<= 1; - if (x >= size) - { - x ^= primitive; - x &= this.MaxnShares; - } - } - } - } - - private class Defaults - { - internal const int MinnBits = 3; - internal const int MaxnBits = 20; // up to 1,048,575 shares - internal const int MaxnShares = (1 << MaxnBits) - 1; - internal const int MaxPaddingMultiple = 1024; - internal const int NBits = 8; - internal const int Radix = 16; // hexadecimal - - // These are primitive polynomial coefficients for Galois Fields GF(2^n) for 2 <= n <= 20. The index of each term in the - // array corresponds to the n for that polynomial. - internal static readonly int[] PrimitivePolynomialCoefficients = { -1, -1, 1, 3, 3, 5, 3, 3, 29, 17, 9, 5, 83, 27, 43, 3, 45, 9, 39, 39, 9 }; - } - - private class ShareComponents - { - internal int NBits; - internal int Id; - internal string Data; - - internal ShareComponents(int nBits, int id, string data) - { - this.NBits = nBits; - this.Id = id; - this.Data = data; - } - } -} diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Exceptions/VerificationException.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Exceptions/VerificationException.cs deleted file mode 100644 index 4aee8932..00000000 --- a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Exceptions/VerificationException.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Thirdweb.EWS; - -internal class VerificationException(bool canRetry) : Exception -{ - internal bool CanRetry { get; } = canRetry; -} diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Models/User.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Models/User.cs deleted file mode 100644 index cd418091..00000000 --- a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Models/User.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Nethereum.Web3.Accounts; - -namespace Thirdweb.EWS; - -internal class User -{ - internal User(Account account, string emailAddress, string phoneNumber) - { - this.Account = account; - this.EmailAddress = emailAddress; - this.PhoneNumber = phoneNumber; - } - - public Account Account { get; internal set; } - public string EmailAddress { get; internal set; } - public string PhoneNumber { get; internal set; } -} diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Models/UserStatus.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Models/UserStatus.cs deleted file mode 100644 index 69196402..00000000 --- a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Models/UserStatus.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Thirdweb.EWS; - -internal enum UserStatus -{ - SignedOut = 10, - SignedInWalletUninitialized = 31, - SignedInNewDevice = 21, - SignedInWalletInitialized = 29, -} diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Storage/LocalStorage.Types.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Storage/LocalStorage.Types.cs deleted file mode 100644 index 9ddff19f..00000000 --- a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Storage/LocalStorage.Types.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System.Runtime.Serialization; - -namespace Thirdweb.EWS; - -internal partial class LocalStorage : LocalStorageBase -{ - [DataContract] - internal class DataStorage - { - internal string AuthToken => this._authToken; - internal string DeviceShare => this._deviceShare; - internal string EmailAddress => this._emailAddress; - internal string PhoneNumber => this._phoneNumber; - internal string WalletUserId => this._walletUserId; - internal string AuthProvider => this._authProvider; - internal string AuthIdentifier => this._authIdentifier; - - [DataMember(Name = "authToken")] - private string _authToken; - - [DataMember(Name = "deviceShare")] - private string _deviceShare; - - [DataMember(Name = "emailAddress")] - private string _emailAddress; - - [DataMember(Name = "phoneNumber")] - private string _phoneNumber; - - [DataMember(Name = "walletUserId")] - private string _walletUserId; - - [DataMember(Name = "authProvider")] - private string _authProvider; - - [DataMember(Name = "authIdentifier")] - private string _authIdentifier; - - internal DataStorage(string authToken, string deviceShare, string emailAddress, string phoneNumber, string walletUserId, string authProvider, string authIdentifier) - { - this._authToken = authToken; - this._deviceShare = deviceShare; - this._emailAddress = emailAddress; - this._phoneNumber = phoneNumber; - this._walletUserId = walletUserId; - this._authProvider = authProvider; - this._authIdentifier = authIdentifier; - } - } - - [DataContract] - private class Storage - { - [DataMember] - internal DataStorage Data { get; set; } - } -} diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.Misc.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.Misc.cs deleted file mode 100644 index da16e79c..00000000 --- a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.Misc.cs +++ /dev/null @@ -1,111 +0,0 @@ -using System.Security.Cryptography; -using Nethereum.Web3.Accounts; - -namespace Thirdweb.EWS; - -internal partial class EmbeddedWallet -{ - internal LocalStorage.DataStorage GetSessionData() - { - return this._localStorage.Data ?? null; - } - - internal async void UpdateSessionData(LocalStorage.DataStorage data) - { - await this._localStorage.SaveDataAsync(data).ConfigureAwait(false); - } - - public async Task SignOutAsync() - { - await this._localStorage.SaveDataAsync(new LocalStorage.DataStorage(null, null, null, null, null, null, null)).ConfigureAwait(false); - } - - internal async Task<(Account account, string deviceShare)> RecoverAccountAsync(string authToken, string recoveryCode) - { - (var authShare, var encryptedRecoveryShare) = await this._server.FetchAuthAndRecoverySharesAsync(authToken).ConfigureAwait(false); - - var recoveryShare = await DecryptShareAsync(encryptedRecoveryShare, recoveryCode).ConfigureAwait(false); - - var account = MakeAccountFromShares(authShare, recoveryShare); - Secrets secrets = new(); - var deviceShare = secrets.NewShare(DEVICE_SHARE_ID, new[] { authShare, recoveryShare }); - return (account, deviceShare); - } - - internal async Task<(string address, string encryptedPrivateKeyB64, string ivB64, string kmsCiphertextB64)> GenerateEncryptionDataAsync(string authToken, string recoveryCode) - { - var (account, _) = await this.RecoverAccountAsync(authToken, recoveryCode).ConfigureAwait(false); - var address = account.Address; - - var encryptedKeyResult = await this._server.GenerateEncryptedKeyResultAsync(authToken).ConfigureAwait(false); - - var plainTextBase64 = encryptedKeyResult["Plaintext"]?.ToString(); - var cipherTextBlobBase64 = encryptedKeyResult["CiphertextBlob"]?.ToString(); - - if (string.IsNullOrEmpty(plainTextBase64) || string.IsNullOrEmpty(cipherTextBlobBase64)) - { - throw new InvalidOperationException("No migration key found. Please try again."); - } - - var iv = new byte[16]; - using (var rng = RandomNumberGenerator.Create()) - { - rng.GetBytes(iv); - } - - var privateKey = account.PrivateKey; - if (privateKey.Length == 64) - { - privateKey = privateKey.Insert(2, "00"); - } - var utf8WithoutBom = new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: true); - var privateKeyBytes = utf8WithoutBom.GetBytes(privateKey); - - byte[] encryptedPrivateKeyBytes; - try - { - using var aes = Aes.Create(); - aes.KeySize = 256; - aes.BlockSize = 128; - aes.Key = Convert.FromBase64String(plainTextBase64); - aes.IV = iv; - aes.Mode = CipherMode.CBC; - aes.Padding = PaddingMode.PKCS7; - - using var encryptor = aes.CreateEncryptor(); - encryptedPrivateKeyBytes = encryptor.TransformFinalBlock(privateKeyBytes, 0, privateKeyBytes.Length); - } - catch (Exception ex) - { - throw new InvalidOperationException("Encryption failed.", ex); - } - - var encryptedData = new byte[iv.Length + encryptedPrivateKeyBytes.Length]; - iv.CopyTo(encryptedData, 0); - encryptedPrivateKeyBytes.CopyTo(encryptedData, iv.Length); - - var encryptedDataB64 = Convert.ToBase64String(encryptedData); - var ivB64 = Convert.ToBase64String(iv); - - return (address, encryptedDataB64, ivB64, cipherTextBlobBase64); - } - - public class VerifyResult - { - public User User { get; } - public bool CanRetry { get; } - public string MainRecoveryCode { get; } - public bool? WasEmailed { get; } - - public VerifyResult(User user, string mainRecoveryCode) - { - this.User = user; - this.MainRecoveryCode = mainRecoveryCode; - } - - public VerifyResult(bool canRetry) - { - this.CanRetry = canRetry; - } - } -} diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/InAppWallet.Types.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/InAppWallet.Types.cs index 7d41e57b..d9dade24 100644 --- a/Thirdweb/Thirdweb.Wallets/InAppWallet/InAppWallet.Types.cs +++ b/Thirdweb/Thirdweb.Wallets/InAppWallet/InAppWallet.Types.cs @@ -26,7 +26,6 @@ public enum AuthProvider Twitch, Steam, Backend, - SiweExternal, } /// diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/InAppWallet.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/InAppWallet.cs index ced62c0e..231054a2 100644 --- a/Thirdweb/Thirdweb.Wallets/InAppWallet/InAppWallet.cs +++ b/Thirdweb/Thirdweb.Wallets/InAppWallet/InAppWallet.cs @@ -18,12 +18,11 @@ internal InAppWallet( string authProvider, IThirdwebWallet siweSigner, string address, - string legacyEncryptionKey, string walletSecret, ExecutionMode executionMode, string delegationContractAddress ) - : base(null, null, client, embeddedWallet, httpClient, email, phoneNumber, authProvider, siweSigner, legacyEncryptionKey, walletSecret, executionMode, delegationContractAddress) + : base(null, null, client, embeddedWallet, httpClient, email, phoneNumber, authProvider, siweSigner, walletSecret, executionMode, delegationContractAddress) { this.Address = address; } @@ -37,7 +36,6 @@ string delegationContractAddress /// The authentication provider to use. /// The path to the storage directory. /// The SIWE signer wallet for SIWE authentication. - /// The encryption key that is no longer required but was used in the past. Only pass this if you had used custom auth before this was deprecated. /// The wallet secret for backend authentication. /// The auth token to use for the session. This will automatically connect using a raw thirdweb auth token. /// The execution mode for the wallet. EOA represents traditional direct calls, EIP7702 represents upgraded account self sponsored calls, and EIP7702Sponsored represents upgraded account calls with managed/sponsored execution. @@ -50,14 +48,13 @@ public static async Task Create( AuthProvider authProvider = Thirdweb.AuthProvider.Default, string storageDirectoryPath = null, IThirdwebWallet siweSigner = null, - string legacyEncryptionKey = null, string walletSecret = null, string twAuthTokenOverride = null, ExecutionMode executionMode = ExecutionMode.EOA ) { storageDirectoryPath ??= Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Thirdweb", "InAppWallet"); - var ecoWallet = await Create(client, null, null, email, phoneNumber, authProvider, storageDirectoryPath, siweSigner, legacyEncryptionKey, walletSecret, twAuthTokenOverride, executionMode); + var ecoWallet = await Create(client, null, null, email, phoneNumber, authProvider, storageDirectoryPath, siweSigner, walletSecret, twAuthTokenOverride, executionMode); return new InAppWallet( ecoWallet.Client, ecoWallet.EmbeddedWallet, @@ -67,7 +64,6 @@ public static async Task Create( ecoWallet.AuthProvider, ecoWallet.SiweSigner, ecoWallet.Address, - ecoWallet.LegacyEncryptionKey, ecoWallet.WalletSecret, ecoWallet.ExecutionMode, ecoWallet.DelegationContractAddress diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Authentication/Server.Types.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet.Authentication/Server.Types.cs similarity index 96% rename from Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Authentication/Server.Types.cs rename to Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet.Authentication/Server.Types.cs index 06bcdfa7..80438380 100644 --- a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Authentication/Server.Types.cs +++ b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet.Authentication/Server.Types.cs @@ -6,13 +6,12 @@ internal partial class Server { internal class VerifyResult { - internal VerifyResult(string authProvider, bool isNewUser, string authToken, string walletUserId, string recoveryCode, string email, string phoneNumber, string authIdentifier) + internal VerifyResult(string authProvider, bool isNewUser, string authToken, string walletUserId, string email, string phoneNumber, string authIdentifier) { this.AuthProvider = authProvider; this.IsNewUser = isNewUser; this.AuthToken = authToken; this.WalletUserId = walletUserId; - this.RecoveryCode = recoveryCode; this.Email = email; this.PhoneNumber = phoneNumber; this.AuthIdentifier = authIdentifier; @@ -22,7 +21,6 @@ internal VerifyResult(string authProvider, bool isNewUser, string authToken, str internal bool IsNewUser { get; } internal string AuthToken { get; } internal string WalletUserId { get; } - internal string RecoveryCode { get; } internal string Email { get; } internal string PhoneNumber { get; } internal string AuthIdentifier { get; } diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Authentication/Server.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet.Authentication/Server.cs similarity index 82% rename from Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Authentication/Server.cs rename to Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet.Authentication/Server.cs index 6669fcf4..384e9b45 100644 --- a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Authentication/Server.cs +++ b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet.Authentication/Server.cs @@ -1,6 +1,5 @@ using System.Net.Http.Headers; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; namespace Thirdweb.EWS; @@ -15,7 +14,6 @@ internal abstract class ServerBase internal abstract Task FetchSiwePayloadAsync(string address, string chainId); internal abstract Task VerifySiweAsync(LoginPayloadData payload, string signature); - internal abstract Task VerifySiweExternalAsync(LoginPayloadData payload, string signature); internal abstract Task VerifyBackendAsync(string walletSecret); @@ -30,11 +28,9 @@ internal abstract class ServerBase internal abstract Task VerifyJwtAsync(string jwtToken); internal abstract Task FetchHeadlessOauthLoginLinkAsync(string authProvider, string platform); - internal abstract Task VerifyOAuthAsync(string authResultStr); + internal abstract Server.VerifyResult VerifyOAuthAsync(string authResultStr); internal abstract Task VerifyAuthEndpointAsync(string payload); - - internal abstract Task GenerateEncryptedKeyResultAsync(string authToken); } internal partial class Server : ServerBase @@ -121,15 +117,6 @@ private async Task FetchRemoteSharesAsync(string authToken, b return rv; } - // login/web-token-exchange - private async Task FetchCognitoIdTokenAsync(string authToken) - { - var uri = MakeUri2024("/login/web-token-exchange"); - var response = await this.SendHttpWithAuthAsync(uri, authToken).ConfigureAwait(false); - await CheckStatusCodeAsync(response).ConfigureAwait(false); - return await DeserializeAsync(response).ConfigureAwait(false); - } - // login/siwe internal override async Task FetchSiwePayloadAsync(string address, string chainId) { @@ -149,27 +136,7 @@ internal override async Task VerifySiweAsync(LoginPayloadData payl await CheckStatusCodeAsync(response).ConfigureAwait(false); var authResult = await DeserializeAsync(response).ConfigureAwait(false); - return await this.InvokeAuthResultLambdaAsync(authResult).ConfigureAwait(false); - } - - internal override async Task VerifySiweExternalAsync(LoginPayloadData payload, string signature) - { - var uri = MakeUri2024("/login/siwe/callback"); - var content = MakeHttpContent(new { signature, payload }); - this._httpClient.AddHeader("origin", payload.Domain); - ThirdwebHttpResponseMessage response = null; - try - { - response = await this._httpClient.PostAsync(uri.ToString(), content).ConfigureAwait(false); - } - finally - { - this._httpClient.RemoveHeader("origin"); - } - await CheckStatusCodeAsync(response).ConfigureAwait(false); - - var authResult = await DeserializeAsync(response).ConfigureAwait(false); - return await this.InvokeAuthResultLambdaAsync(authResult).ConfigureAwait(false); + return this.ToVerifyResult(authResult); } // login/backend @@ -181,7 +148,7 @@ internal override async Task VerifyBackendAsync(string walletSecre await CheckStatusCodeAsync(response).ConfigureAwait(false); var authResult = await DeserializeAsync(response).ConfigureAwait(false); - return await this.InvokeAuthResultLambdaAsync(authResult).ConfigureAwait(false); + return this.ToVerifyResult(authResult); } // login/guest @@ -194,7 +161,7 @@ internal override async Task VerifyGuestAsync(string sessionId) var authResult = await DeserializeAsync(response).ConfigureAwait(false); authResult.StoredToken.AuthDetails.AuthIdentifier = sessionId; - return await this.InvokeAuthResultLambdaAsync(authResult).ConfigureAwait(false); + return this.ToVerifyResult(authResult); } // login/oauthprovider @@ -224,7 +191,7 @@ internal override async Task VerifyEmailOtpAsync(string emailAddre await CheckStatusCodeAsync(response).ConfigureAwait(false); var authResult = await DeserializeAsync(response).ConfigureAwait(false); - return await this.InvokeAuthResultLambdaAsync(authResult).ConfigureAwait(false); + return this.ToVerifyResult(authResult); } // login/phone @@ -248,7 +215,7 @@ internal override async Task VerifyPhoneOtpAsync(string phoneNumbe await CheckStatusCodeAsync(response).ConfigureAwait(false); var authResult = await DeserializeAsync(response).ConfigureAwait(false); - return await this.InvokeAuthResultLambdaAsync(authResult).ConfigureAwait(false); + return this.ToVerifyResult(authResult); } // embedded-wallet/validate-custom-jwt @@ -266,7 +233,6 @@ internal override async Task VerifyJwtAsync(string jwtToken) authVerifiedToken.VerifiedToken.IsNewUser, authVerifiedToken.VerifiedTokenJwtString, authVerifiedToken.VerifiedToken.AuthDetails.UserWalletId, - authVerifiedToken.VerifiedToken.AuthDetails.RecoveryCode, authVerifiedToken.VerifiedToken.AuthDetails.Email, authVerifiedToken.VerifiedToken.AuthDetails.PhoneNumber, authVerifiedToken.VerifiedToken.AuthDetails.AuthIdentifier @@ -288,44 +254,27 @@ internal override async Task VerifyAuthEndpointAsync(string payloa authVerifiedToken.VerifiedToken.IsNewUser, authVerifiedToken.VerifiedTokenJwtString, authVerifiedToken.VerifiedToken.AuthDetails.UserWalletId, - authVerifiedToken.VerifiedToken.AuthDetails.RecoveryCode, authVerifiedToken.VerifiedToken.AuthDetails.Email, authVerifiedToken.VerifiedToken.AuthDetails.PhoneNumber, authVerifiedToken.VerifiedToken.AuthDetails.AuthIdentifier ); } - internal override async Task VerifyOAuthAsync(string authResultStr) + internal override VerifyResult VerifyOAuthAsync(string authResultStr) { var authResult = JsonConvert.DeserializeObject(authResultStr); - return await this.InvokeAuthResultLambdaAsync(authResult).ConfigureAwait(false); + return this.ToVerifyResult(authResult); } #region Misc - internal override async Task GenerateEncryptedKeyResultAsync(string authToken) - { - var webExchangeResult = await this.FetchCognitoIdTokenAsync(authToken).ConfigureAwait(false); - return await AWS.GenerateDataKey(webExchangeResult.IdentityId, webExchangeResult.Token, this._httpClient).ConfigureAwait(false); - } - - private async Task InvokeAuthResultLambdaAsync(AuthResultType authResult) + private VerifyResult ToVerifyResult(AuthResultType authResult) { - var authToken = authResult.StoredToken.CookieString; - var idTokenResponse = await this.FetchCognitoIdTokenAsync(authToken).ConfigureAwait(false); - - var invokePayload = Serialize(new { token = idTokenResponse.LambdaToken }); - var responsePayload = await AWS.InvokeRecoverySharePasswordLambdaAsync(idTokenResponse.IdentityId, idTokenResponse.Token, invokePayload, this._httpClient).ConfigureAwait(false); - - var jsonSerializer = new JsonSerializer(); - var payload = jsonSerializer.Deserialize(new JsonTextReader(new StreamReader(responsePayload))); - payload = jsonSerializer.Deserialize(new JsonTextReader(new StringReader(payload.Body))); return new VerifyResult( authResult.StoredToken.AuthProvider, authResult.StoredToken.IsNewUser, - authToken, + authResult.StoredToken.CookieString, authResult.StoredToken.AuthDetails.UserWalletId, - payload.RecoverySharePassword, authResult.StoredToken.AuthDetails.Email, authResult.StoredToken.AuthDetails.PhoneNumber, authResult.StoredToken.AuthDetails.AuthIdentifier diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet.Storage/LocalStorage.Types.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet.Storage/LocalStorage.Types.cs new file mode 100644 index 00000000..6e0e331a --- /dev/null +++ b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet.Storage/LocalStorage.Types.cs @@ -0,0 +1,49 @@ +using System.Runtime.Serialization; + +namespace Thirdweb.EWS; + +internal partial class LocalStorage : LocalStorageBase +{ + [DataContract] + internal class DataStorage + { + [field: DataMember(Name = "authToken")] + internal string AuthToken { get; } + + [field: DataMember(Name = "deviceShare")] + internal string DeviceShare { get; } + + [field: DataMember(Name = "emailAddress")] + internal string EmailAddress { get; } + + [field: DataMember(Name = "phoneNumber")] + internal string PhoneNumber { get; } + + [field: DataMember(Name = "walletUserId")] + internal string WalletUserId { get; } + + [field: DataMember(Name = "authProvider")] + internal string AuthProvider { get; } + + [field: DataMember(Name = "authIdentifier")] + internal string AuthIdentifier { get; } + + internal DataStorage(string authToken, string deviceShare, string emailAddress, string phoneNumber, string walletUserId, string authProvider, string authIdentifier) + { + this.AuthToken = authToken; + this.DeviceShare = deviceShare; + this.EmailAddress = emailAddress; + this.PhoneNumber = phoneNumber; + this.WalletUserId = walletUserId; + this.AuthProvider = authProvider; + this.AuthIdentifier = authIdentifier; + } + } + + [DataContract] + private class Storage + { + [DataMember] + internal DataStorage Data { get; set; } + } +} diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Storage/LocalStorage.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet.Storage/LocalStorage.cs similarity index 100% rename from Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet.Storage/LocalStorage.cs rename to Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet.Storage/LocalStorage.cs diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.AccountLinking.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.AccountLinking.cs similarity index 100% rename from Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.AccountLinking.cs rename to Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.AccountLinking.cs diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.AuthEndpoint.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.AuthEndpoint.cs similarity index 100% rename from Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.AuthEndpoint.cs rename to Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.AuthEndpoint.cs diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.Backend.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.Backend.cs similarity index 100% rename from Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.Backend.cs rename to Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.Backend.cs diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.EmailOTP.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.EmailOTP.cs similarity index 100% rename from Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.EmailOTP.cs rename to Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.EmailOTP.cs diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.Guest.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.Guest.cs similarity index 100% rename from Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.Guest.cs rename to Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.Guest.cs diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.JWT.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.JWT.cs similarity index 100% rename from Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.JWT.cs rename to Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.JWT.cs diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.Misc.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.Misc.cs new file mode 100644 index 00000000..9a44fd73 --- /dev/null +++ b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.Misc.cs @@ -0,0 +1,19 @@ +namespace Thirdweb.EWS; + +internal partial class EmbeddedWallet +{ + internal LocalStorage.DataStorage GetSessionData() + { + return this._localStorage.Data ?? null; + } + + internal async void UpdateSessionData(LocalStorage.DataStorage data) + { + await this._localStorage.SaveDataAsync(data).ConfigureAwait(false); + } + + public async Task SignOutAsync() + { + await this._localStorage.SaveDataAsync(new LocalStorage.DataStorage(null, null, null, null, null, null, null)).ConfigureAwait(false); + } +} diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.OAuth.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.OAuth.cs similarity index 64% rename from Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.OAuth.cs rename to Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.OAuth.cs index ca120d80..49bca00f 100644 --- a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.OAuth.cs +++ b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.OAuth.cs @@ -2,9 +2,9 @@ namespace Thirdweb.EWS; internal partial class EmbeddedWallet { - public async Task SignInWithOauthAsync(string authResult) + public Server.VerifyResult SignInWithOauthAsync(string authResult) { - return await this._server.VerifyOAuthAsync(authResult).ConfigureAwait(false); + return this._server.VerifyOAuthAsync(authResult); } public async Task FetchHeadlessOauthLoginLinkAsync(string authProvider, string platform) diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.PhoneOTP.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.PhoneOTP.cs similarity index 100% rename from Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.PhoneOTP.cs rename to Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.PhoneOTP.cs diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.SIWE.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.SIWE.cs similarity index 73% rename from Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.SIWE.cs rename to Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.SIWE.cs index 988d5b9b..a36d873b 100644 --- a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.SIWE.cs +++ b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.SIWE.cs @@ -13,9 +13,4 @@ internal partial class EmbeddedWallet return await this._server.VerifySiweAsync(payload, signature).ConfigureAwait(false); } - - public async Task SignInWithSiweExternalRawAsync(LoginPayloadData payload, string signature) - { - return await this._server.VerifySiweExternalAsync(payload, signature).ConfigureAwait(false); - } } diff --git a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.cs b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.cs similarity index 76% rename from Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.cs rename to Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.cs index 8f470942..f32e841f 100644 --- a/Thirdweb/Thirdweb.Wallets/InAppWallet/EmbeddedWallet/EmbeddedWallet.cs +++ b/Thirdweb/Thirdweb.Wallets/InAppWallet/Thirdweb.EWS/EmbeddedWallet/EmbeddedWallet.cs @@ -4,15 +4,6 @@ internal partial class EmbeddedWallet { private readonly LocalStorage _localStorage; private readonly Server _server; - private readonly IvGenerator _ivGenerator; - - private const int DEVICE_SHARE_ID = 1; - private const int KEY_SIZE = 256 / 8; - private const int TAG_SIZE = 16; - private const int CURRENT_ITERATION_COUNT = 650_000; - private const int DEPRECATED_ITERATION_COUNT = 5_000_000; - private const string WALLET_PRIVATE_KEY_PREFIX = "thirdweb_"; - private const string ENCRYPTION_SEPARATOR = ":"; public EmbeddedWallet(ThirdwebClient client, string storageDirectoryPath = null, string ecosystemId = null, string ecosystemPartnerId = null) { @@ -45,7 +36,5 @@ public EmbeddedWallet(ThirdwebClient client, string storageDirectoryPath = null, var ewsHttpClient = Utils.ReconstructHttpClient(client.HttpClient, headers); this._server = new Server(client, ewsHttpClient); - - this._ivGenerator = new IvGenerator(storageDirectoryPath); } } diff --git a/Thirdweb/Thirdweb.Wallets/PrivateKeyWallet/PrivateKeyWallet.cs b/Thirdweb/Thirdweb.Wallets/PrivateKeyWallet/PrivateKeyWallet.cs deleted file mode 100644 index d249044d..00000000 --- a/Thirdweb/Thirdweb.Wallets/PrivateKeyWallet/PrivateKeyWallet.cs +++ /dev/null @@ -1,487 +0,0 @@ -using System.Numerics; -using System.Text; -using Nethereum.ABI.EIP712; -using Nethereum.Hex.HexConvertors.Extensions; -using Nethereum.RLP; -using Nethereum.Signer; -using Nethereum.Signer.EIP712; - -namespace Thirdweb; - -/// -/// Represents a wallet that uses a private key for signing transactions and messages. -/// -public class PrivateKeyWallet : IThirdwebWallet -{ - public ThirdwebClient Client { get; } - - public ThirdwebAccountType AccountType => ThirdwebAccountType.PrivateKeyAccount; - - public string WalletId => "privateKey"; - - protected EthECKey EcKey { get; set; } - - protected PrivateKeyWallet(ThirdwebClient client, EthECKey key) - { - this.Client = client; - this.EcKey = key; - } - - /// - /// Creates a new instance of using the provided private key. - /// - /// The Thirdweb client instance. - /// The private key in hexadecimal format. - /// A new instance of . - /// Thrown when the private key is null or empty. - public static Task Create(ThirdwebClient client, string privateKeyHex) - { - if (client == null) - { - throw new ArgumentNullException(nameof(client)); - } - - if (string.IsNullOrEmpty(privateKeyHex)) - { - throw new ArgumentNullException(nameof(privateKeyHex), "Private key cannot be null or empty."); - } - - var wallet = new PrivateKeyWallet(client, new EthECKey(privateKeyHex)); - Utils.TrackConnection(wallet); - return Task.FromResult(wallet); - } - - #region PrivateKeyWallet Specific - - /// - /// Generates a new instance of with a new private key. - /// - /// The Thirdweb client instance. - /// A new instance of . - /// Thrown when the client is null. - public static Task Generate(ThirdwebClient client) - { - if (client == null) - { - throw new ArgumentNullException(nameof(client)); - } - var wallet = new PrivateKeyWallet(client, EthECKey.GenerateKey()); - Utils.TrackConnection(wallet); - return Task.FromResult(wallet); - } - - /// - /// Loads a saved instance of from the local storage or generates an ephemeral one if not found. - /// - /// The Thirdweb client instance. - /// A new instance of . - /// Thrown when the client is null. - public static async Task LoadOrGenerate(ThirdwebClient client) - { - if (client == null) - { - throw new ArgumentNullException(nameof(client)); - } - - var path = GetSavePath(); - - if (File.Exists(path)) - { - var privateKey = await File.ReadAllTextAsync(path); - var wallet = new PrivateKeyWallet(client, new EthECKey(privateKey)); - Utils.TrackConnection(wallet); - return wallet; - } - else - { - return await Generate(client); - } - } - - /// - /// Gets the path to the file where a PrivateKeyWallet would be saved if PrivateKeyWallet.Save() is called. - /// - /// The path to the file. - public static string GetSavePath() - { - return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Thirdweb", "PrivateKeyWallet", "private_key_wallet.txt"); - } - - /// - /// Saves the private key to the local storage. - /// - /// A task that represents the asynchronous save operation. - /// Thrown when the wallet does not have a private key. - public async Task Save() - { - if (this.EcKey == null) - { - throw new InvalidOperationException("Cannot save wallet without a private key."); - } - - var filePath = GetSavePath(); - var directoryPath = Path.GetDirectoryName(filePath); - - if (!Directory.Exists(directoryPath)) - { - _ = Directory.CreateDirectory(directoryPath); - } - - await File.WriteAllTextAsync(filePath, this.EcKey.GetPrivateKey()); - } - - /// - /// Deletes the saved private key from the local storage if it exists. - /// - /// A task that represents the asynchronous delete operation. - public static void Delete() - { - var path = GetSavePath(); - - if (File.Exists(path)) - { - File.Delete(path); - } - } - - /// - /// Exports the private key as a hexadecimal string. - /// - /// The private key as a hexadecimal string. - /// Thrown when the wallet does not have a private key. - public async Task Export() - { - if (this.EcKey == null) - { - throw new InvalidOperationException("Cannot export private key without a private key."); - } - - return await Task.FromResult(this.EcKey.GetPrivateKey()); - } - - #endregion - - #region IThirdwebWallet - - public virtual Task GetAddress() - { - return Task.FromResult(this.EcKey.GetPublicAddress().ToChecksumAddress()); - } - - public virtual Task EthSign(byte[] rawMessage) - { - if (rawMessage == null) - { - throw new ArgumentNullException(nameof(rawMessage), "Message to sign cannot be null."); - } - - var signer = new MessageSigner(); - var signature = signer.Sign(rawMessage, this.EcKey); - return Task.FromResult(signature); - } - - public virtual Task EthSign(string message) - { - if (message == null) - { - throw new ArgumentNullException(nameof(message), "Message to sign cannot be null."); - } - - var signer = new MessageSigner(); - var signature = signer.Sign(Encoding.UTF8.GetBytes(message), this.EcKey); - return Task.FromResult(signature); - } - - public virtual Task RecoverAddressFromEthSign(string message, string signature) - { - if (message == null) - { - throw new ArgumentNullException(nameof(message), "Message to sign cannot be null."); - } - - if (signature == null) - { - throw new ArgumentNullException(nameof(signature), "Signature cannot be null."); - } - - var signer = new MessageSigner(); - var address = signer.EcRecover(Encoding.UTF8.GetBytes(message), signature); - return Task.FromResult(address); - } - - public virtual Task PersonalSign(byte[] rawMessage) - { - if (rawMessage == null) - { - throw new ArgumentNullException(nameof(rawMessage), "Message to sign cannot be null."); - } - - var signer = new EthereumMessageSigner(); - var signature = signer.Sign(rawMessage, this.EcKey); - return Task.FromResult(signature); - } - - public virtual Task PersonalSign(string message) - { - if (string.IsNullOrEmpty(message)) - { - throw new ArgumentNullException(nameof(message), "Message to sign cannot be null."); - } - - var signer = new EthereumMessageSigner(); - var signature = signer.EncodeUTF8AndSign(message, this.EcKey); - return Task.FromResult(signature); - } - - public virtual Task RecoverAddressFromPersonalSign(string message, string signature) - { - if (string.IsNullOrEmpty(message)) - { - throw new ArgumentNullException(nameof(message), "Message to sign cannot be null."); - } - - if (string.IsNullOrEmpty(signature)) - { - throw new ArgumentNullException(nameof(signature), "Signature cannot be null."); - } - - var signer = new EthereumMessageSigner(); - var address = signer.EncodeUTF8AndEcRecover(message, signature); - return Task.FromResult(address); - } - - public virtual Task SignTypedDataV4(string json) - { - if (string.IsNullOrEmpty(json)) - { - throw new ArgumentNullException(nameof(json), "Json to sign cannot be null."); - } - - var encodedData = EIP712Encoder.Current.EncodeTypedData(json); - var signature = this.EcKey.SignAndCalculateV(Utils.HashMessage(encodedData)); - return Task.FromResult(EthECDSASignature.CreateStringSignature(signature)); - } - - public virtual Task SignTypedDataV4(T data, TypedData typedData) - where TDomain : IDomain - { - if (data == null) - { - throw new ArgumentNullException(nameof(data), "Data to sign cannot be null."); - } - - var encodedData = EIP712Encoder.Current.EncodeTypedData(data, typedData); - var signature = this.EcKey.SignAndCalculateV(Utils.HashMessage(encodedData)); - return Task.FromResult(EthECDSASignature.CreateStringSignature(signature)); - } - - public virtual Task RecoverAddressFromTypedDataV4(T data, TypedData typedData, string signature) - where TDomain : IDomain - { - if (data == null) - { - throw new ArgumentNullException(nameof(data), "Data to sign cannot be null."); - } - - if (typedData == null) - { - throw new ArgumentNullException(nameof(typedData), "Typed data cannot be null."); - } - - if (signature == null) - { - throw new ArgumentNullException(nameof(signature), "Signature cannot be null."); - } - - var signer = new Eip712TypedDataSigner(); - var address = signer.RecoverFromSignatureV4(data, typedData, signature); - return Task.FromResult(address); - } - - public virtual Task SignTransaction(ThirdwebTransactionInput transaction) - { - if (transaction == null) - { - throw new ArgumentNullException(nameof(transaction)); - } - - if (transaction.Nonce == null) - { - throw new ArgumentNullException(nameof(transaction), "Transaction nonce has not been set"); - } - - string signedTransaction; - - if (transaction.GasPrice != null) - { - var legacySigner = new LegacyTransactionSigner(); - signedTransaction = legacySigner.SignTransaction( - this.EcKey.GetPrivateKey(), - transaction.ChainId.Value, - transaction.To, - transaction.Value.Value, - transaction.Nonce.Value, - transaction.GasPrice.Value, - transaction.Gas.Value, - transaction.Data - ); - } - else - { - if (transaction.MaxPriorityFeePerGas == null || transaction.MaxFeePerGas == null) - { - throw new InvalidOperationException("Transaction MaxPriorityFeePerGas and MaxFeePerGas must be set for EIP-1559 transactions"); - } - - var encodedData = new List - { - RLP.EncodeElement(transaction.ChainId.Value.ToByteArrayForRLPEncoding()), - RLP.EncodeElement(transaction.Nonce.Value.ToByteArrayForRLPEncoding()), - RLP.EncodeElement(transaction.MaxPriorityFeePerGas.Value.ToByteArrayForRLPEncoding()), - RLP.EncodeElement(transaction.MaxFeePerGas.Value.ToByteArrayForRLPEncoding()), - RLP.EncodeElement(transaction.Gas.Value.ToByteArrayForRLPEncoding()), - RLP.EncodeElement(transaction.To.HexToBytes()), - RLP.EncodeElement(transaction.Value.Value.ToByteArrayForRLPEncoding()), - RLP.EncodeElement(transaction.Data == null ? Array.Empty() : transaction.Data.HexToBytes()), - new byte[] { 0xc0 }, // AccessList, empty so short list bytes - }; - - if (transaction.AuthorizationList != null) - { - var encodedAuthorizationList = new List(); - foreach (var authorizationList in transaction.AuthorizationList) - { - var encodedItem = new List() - { - RLP.EncodeElement(authorizationList.ChainId.HexToNumber().ToByteArrayForRLPEncoding()), - RLP.EncodeElement(authorizationList.Address.HexToBytes()), - RLP.EncodeElement(authorizationList.Nonce.HexToNumber().ToByteArrayForRLPEncoding()), - RLP.EncodeElement(authorizationList.YParity is "0x00" or "0x0" or "0x" ? Array.Empty() : authorizationList.YParity.HexToBytes()), - RLP.EncodeElement(authorizationList.R.HexToBytes().TrimZeroes()), - RLP.EncodeElement(authorizationList.S.HexToBytes().TrimZeroes()), - }; - encodedAuthorizationList.Add(RLP.EncodeList(encodedItem.ToArray())); - } - encodedData.Add(RLP.EncodeList(encodedAuthorizationList.ToArray())); - } - - var encodedBytes = RLP.EncodeList(encodedData.ToArray()); - var returnBytes = new byte[encodedBytes.Length + 1]; - Array.Copy(encodedBytes, 0, returnBytes, 1, encodedBytes.Length); - returnBytes[0] = transaction.AuthorizationList != null ? (byte)0x04 : (byte)0x02; - - var rawHash = Utils.HashMessage(returnBytes); - var rawSignature = this.EcKey.SignAndCalculateYParityV(rawHash); - - byte[] v; - byte[] r; - byte[] s; - if (rawSignature.V.Length == 0 || rawSignature.V[0] == 0) - { - v = Array.Empty(); - } - else - { - v = rawSignature.V; - } - v = RLP.EncodeElement(v); - r = RLP.EncodeElement(rawSignature.R.TrimZeroes()); - s = RLP.EncodeElement(rawSignature.S.TrimZeroes()); - - encodedData.Add(v); - encodedData.Add(r); - encodedData.Add(s); - - encodedBytes = RLP.EncodeList(encodedData.ToArray()); - returnBytes = new byte[encodedBytes.Length + 1]; - Array.Copy(encodedBytes, 0, returnBytes, 1, encodedBytes.Length); - returnBytes[0] = transaction.AuthorizationList != null ? (byte)0x04 : (byte)0x02; - - // (var tx, var sig) = Utils.DecodeTransaction(returnBytes); - - signedTransaction = returnBytes.ToHex(); - // Console.WriteLine(signedTransaction); - - // (var tx, var sig) = Utils.DecodeTransaction("0x" + signedTransaction); - } - - return Task.FromResult("0x" + signedTransaction); - } - - public virtual Task IsConnected() - { - return Task.FromResult(this.EcKey != null); - } - - public virtual Task Disconnect() - { - this.EcKey = null; - return Task.CompletedTask; - } - - public virtual Task SendTransaction(ThirdwebTransactionInput transaction) - { - throw new InvalidOperationException("SendTransaction is not supported for private key wallets, please use the unified Contract or ThirdwebTransaction APIs."); - } - - public virtual Task ExecuteTransaction(ThirdwebTransactionInput transactionInput) - { - throw new InvalidOperationException("ExecuteTransaction is not supported for private key wallets, please use the unified Contract or ThirdwebTransaction APIs."); - } - - public virtual Task> LinkAccount( - IThirdwebWallet walletToLink, - string otp = null, - bool? isMobile = null, - Action browserOpenAction = null, - string mobileRedirectScheme = "thirdweb://", - IThirdwebBrowser browser = null, - BigInteger? chainId = null, - string jwt = null, - string payload = null, - string defaultSessionIdOverride = null, - List forceWalletIds = null - ) - { - throw new InvalidOperationException("LinkAccount is not supported for private key wallets."); - } - - public virtual Task> GetLinkedAccounts() - { - throw new InvalidOperationException("GetLinkedAccounts is not supported for private key wallets."); - } - - public Task> UnlinkAccount(LinkedAccount accountToUnlink) - { - throw new InvalidOperationException("UnlinkAccount is not supported for private key wallets."); - } - - public async Task SignAuthorization(BigInteger chainId, string contractAddress, bool willSelfExecute) - { - var nonce = await this.GetTransactionCount(chainId); - if (willSelfExecute) - { - nonce++; - } - var encodedData = new List - { - RLP.EncodeElement(chainId.ToByteArrayForRLPEncoding()), - RLP.EncodeElement(contractAddress.HexToBytes()), - RLP.EncodeElement(nonce.ToByteArrayForRLPEncoding()), - }; - var encodedBytes = RLP.EncodeList(encodedData.ToArray()); - var returnElements = new byte[encodedBytes.Length + 1]; - Array.Copy(encodedBytes.ToArray(), 0, returnElements, 1, encodedBytes.Length); - returnElements[0] = 0x05; - var authorizationHash = Utils.HashMessage(returnElements); - var authorizationSignature = this.EcKey.SignAndCalculateYParityV(authorizationHash); - return new EIP7702Authorization(chainId, contractAddress, nonce, authorizationSignature.V, authorizationSignature.R, authorizationSignature.S); - } - - public Task SwitchNetwork(BigInteger chainId) - { - return Task.CompletedTask; - } - - #endregion -} diff --git a/Thirdweb/Thirdweb.Wallets/ServerWallet/ServerWallet.cs b/Thirdweb/Thirdweb.Wallets/ServerWallet/ServerWallet.cs index 26e4a8c5..3e855dbd 100644 --- a/Thirdweb/Thirdweb.Wallets/ServerWallet/ServerWallet.cs +++ b/Thirdweb/Thirdweb.Wallets/ServerWallet/ServerWallet.cs @@ -1,8 +1,6 @@ using System.Numerics; using System.Text; using Nethereum.ABI.EIP712; -using Nethereum.Signer; -using Nethereum.Signer.EIP712; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -196,26 +194,6 @@ public Task GetAddress() } } - public Task EthSign(byte[] rawMessage) - { - if (rawMessage == null) - { - throw new ArgumentNullException(nameof(rawMessage), "Message to sign cannot be null."); - } - - throw new NotImplementedException(); - } - - public Task EthSign(string message) - { - if (message == null) - { - throw new ArgumentNullException(nameof(message), "Message to sign cannot be null."); - } - - throw new NotImplementedException(); - } - public async Task PersonalSign(byte[] rawMessage) { if (rawMessage == null) @@ -369,51 +347,6 @@ public Task Disconnect() return Task.CompletedTask; } - public virtual Task RecoverAddressFromEthSign(string message, string signature) - { - throw new InvalidOperationException(); - } - - public virtual Task RecoverAddressFromPersonalSign(string message, string signature) - { - if (string.IsNullOrEmpty(message)) - { - throw new ArgumentNullException(nameof(message), "Message to sign cannot be null."); - } - - if (string.IsNullOrEmpty(signature)) - { - throw new ArgumentNullException(nameof(signature), "Signature cannot be null."); - } - - var signer = new EthereumMessageSigner(); - var address = signer.EncodeUTF8AndEcRecover(message, signature); - return Task.FromResult(address); - } - - public virtual Task RecoverAddressFromTypedDataV4(T data, TypedData typedData, string signature) - where TDomain : IDomain - { - if (data == null) - { - throw new ArgumentNullException(nameof(data), "Data to sign cannot be null."); - } - - if (typedData == null) - { - throw new ArgumentNullException(nameof(typedData), "Typed data cannot be null."); - } - - if (signature == null) - { - throw new ArgumentNullException(nameof(signature), "Signature cannot be null."); - } - - var signer = new Eip712TypedDataSigner(); - var address = signer.RecoverFromSignatureV4(data, typedData, signature); - return Task.FromResult(address); - } - public Task SignAuthorization(BigInteger chainId, string contractAddress, bool willSelfExecute) { throw new NotImplementedException(); @@ -434,8 +367,7 @@ public Task> LinkAccount( BigInteger? chainId = null, string jwt = null, string payload = null, - string defaultSessionIdOverride = null, - List forceWalletIds = null + string defaultSessionIdOverride = null ) { throw new NotImplementedException(); diff --git a/Thirdweb/Thirdweb.Wallets/SmartWallet/SmartWallet.cs b/Thirdweb/Thirdweb.Wallets/SmartWallet/SmartWallet.cs index 717952df..c31934d7 100644 --- a/Thirdweb/Thirdweb.Wallets/SmartWallet/SmartWallet.cs +++ b/Thirdweb/Thirdweb.Wallets/SmartWallet/SmartWallet.cs @@ -3,8 +3,6 @@ using System.Text; using Nethereum.ABI; using Nethereum.ABI.EIP712; -using Nethereum.Contracts; -using Nethereum.Hex.HexTypes; using Nethereum.Util; using Newtonsoft.Json; using Thirdweb.AccountAbstraction; @@ -281,12 +279,7 @@ public async Task ForceDeploy() throw new InvalidOperationException("SmartAccount.ForceDeploy: Account is already deploying."); } - var input = new ThirdwebTransactionInput(this.ActiveChainId) - { - Data = "0x", - To = this._accountContract.Address, - Value = new HexBigInteger(0), - }; + var input = new ThirdwebTransactionInput(chainId: this.ActiveChainId, data: "0x", to: this._accountContract.Address, value: 0); var txHash = await this.SendTransaction(input).ConfigureAwait(false); _ = await ThirdwebTransaction.WaitForTransactionReceipt(this.Client, this.ActiveChainId, txHash).ConfigureAwait(false); } @@ -438,14 +431,8 @@ string reqValidityEndTimestamp var signature = await EIP712 .GenerateSignature_SmartAccount("Account", "1", this.ActiveChainId, await this.GetAddress().ConfigureAwait(false), request, this._personalAccount) .ConfigureAwait(false); - // Do it this way to avoid triggering an extra sig from estimation - var data = new Contract(null, this._accountContract.Abi, this._accountContract.Address).GetFunction("setPermissionsForSigner").GetData(request, signature.HexToBytes()); - var txInput = new ThirdwebTransactionInput(this.ActiveChainId) - { - To = this._accountContract.Address, - Value = new HexBigInteger(0), - Data = data, - }; + var data = this._accountContract.CreateCallData("setPermissionsForSigner", request, signature.HexToBytes()); + var txInput = new ThirdwebTransactionInput(chainId: this.ActiveChainId, to: this._accountContract.Address, value: 0, data: data); var txHash = await this.SendTransaction(txInput).ConfigureAwait(false); return await ThirdwebTransaction.WaitForTransactionReceipt(this.Client, this.ActiveChainId, txHash).ConfigureAwait(false); } @@ -488,13 +475,8 @@ public async Task AddAdmin(string admin) }; var signature = await EIP712.GenerateSignature_SmartAccount("Account", "1", this.ActiveChainId, await this.GetAddress(), request, this._personalAccount).ConfigureAwait(false); - var data = new Contract(null, this._accountContract.Abi, this._accountContract.Address).GetFunction("setPermissionsForSigner").GetData(request, signature.HexToBytes()); - var txInput = new ThirdwebTransactionInput(this.ActiveChainId) - { - To = this._accountContract.Address, - Value = new HexBigInteger(0), - Data = data, - }; + var data = this._accountContract.CreateCallData("setPermissionsForSigner", request, signature.HexToBytes()); + var txInput = new ThirdwebTransactionInput(chainId: this.ActiveChainId, to: this._accountContract.Address, value: 0, data: data); var txHash = await this.SendTransaction(txInput).ConfigureAwait(false); return await ThirdwebTransaction.WaitForTransactionReceipt(this.Client, this.ActiveChainId, txHash).ConfigureAwait(false); } @@ -527,13 +509,8 @@ public async Task RemoveAdmin(string admin) var signature = await EIP712 .GenerateSignature_SmartAccount("Account", "1", this.ActiveChainId, await this.GetAddress().ConfigureAwait(false), request, this._personalAccount) .ConfigureAwait(false); - var data = new Contract(null, this._accountContract.Abi, this._accountContract.Address).GetFunction("setPermissionsForSigner").GetData(request, signature.HexToBytes()); - var txInput = new ThirdwebTransactionInput(this.ActiveChainId) - { - To = this._accountContract.Address, - Value = new HexBigInteger(0), - Data = data, - }; + var data = this._accountContract.CreateCallData("setPermissionsForSigner", request, signature.HexToBytes()); + var txInput = new ThirdwebTransactionInput(chainId: this.ActiveChainId, to: this._accountContract.Address, value: 0, data: data); var txHash = await this.SendTransaction(txInput).ConfigureAwait(false); return await ThirdwebTransaction.WaitForTransactionReceipt(this.Client, this.ActiveChainId, txHash).ConfigureAwait(false); } @@ -580,9 +557,7 @@ public async Task EstimateUserOperationGas(ThirdwebTransactionInput } var personalAccountAddress = await this._personalAccount.GetAddress().ConfigureAwait(false); - var factoryContract = new Contract(null, this._factoryContract.Abi, this._factoryContract.Address); - var createFunction = factoryContract.GetFunction("createAccount"); - var data = createFunction.GetData(personalAccountAddress, Array.Empty()); + var data = this._factoryContract.CreateCallData("createAccount", personalAccountAddress, Array.Empty()); return (Utils.HexConcat(this._factoryContract.Address, data).HexToBytes(), this._factoryContract.Address, data); } @@ -639,31 +614,30 @@ private async Task SignUserOp(ThirdwebTransactionInput transactionInput, // Create the user operation and its safe (hexified) version - var fees = await BundlerClient.ThirdwebGetUserOperationGasPrice(this.Client, this._bundlerUrl, requestId).ConfigureAwait(false); - var maxFee = new HexBigInteger(fees.MaxFeePerGas).Value; - var maxPriorityFee = new HexBigInteger(fees.MaxPriorityFeePerGas).Value; + var fees = await ThirdwebBundler.ThirdwebGetUserOperationGasPrice(this.Client, this._bundlerUrl, requestId).ConfigureAwait(false); + var maxFee = fees.MaxFeePerGas.HexToNumber(); + var maxPriorityFee = fees.MaxPriorityFeePerGas.HexToNumber(); var entryPointVersion = Utils.GetEntryPointVersion(this._entryPointContract.Address); - if (entryPointVersion == 6) - { #pragma warning disable IDE0078 // Use pattern matching - var executeFn = new ExecuteFunction - { - Target = transactionInput.To, - Value = transactionInput.ChainId.Value == 295 || transactionInput.ChainId.Value == 296 ? transactionInput.Value.Value / BigInteger.Pow(10, 10) : transactionInput.Value.Value, - Calldata = transactionInput.Data.HexToBytes(), - FromAddress = await this.GetAddress().ConfigureAwait(false), - }; + // function execute(address _target, uint256 _value, bytes calldata _calldata) + var executeInput = this._accountContract.CreateCallData( + "execute", + transactionInput.To, + transactionInput.ChainId.Value == 295 || transactionInput.ChainId.Value == 296 ? transactionInput.Value.Value / BigInteger.Pow(10, 10) : transactionInput.Value.Value, + transactionInput.Data.HexToBytes() + ); #pragma warning restore IDE0078 // Use pattern matching - var executeInput = executeFn.CreateTransactionInput(await this.GetAddress().ConfigureAwait(false)); + if (entryPointVersion == 6) + { var partialUserOp = new UserOperationV6() { Sender = this._accountContract.Address, Nonce = await this.GetNonce().ConfigureAwait(false), InitCode = initCode, - CallData = executeInput.Data.HexToBytes(), + CallData = executeInput.HexToBytes(), CallGasLimit = transactionInput.Gas == null ? 0 : 21000 + transactionInput.Gas.Value, VerificationGasLimit = 0, PreVerificationGas = 0, @@ -680,16 +654,16 @@ private async Task SignUserOp(ThirdwebTransactionInput transactionInput, if (pmSponsorResult.VerificationGasLimit == null || pmSponsorResult.PreVerificationGas == null) { - var gasEstimates = await BundlerClient.EthEstimateUserOperationGas(this.Client, this._bundlerUrl, requestId, EncodeUserOperation(partialUserOp), this._entryPointContract.Address); - partialUserOp.CallGasLimit = new HexBigInteger(gasEstimates.CallGasLimit).Value; - partialUserOp.VerificationGasLimit = new HexBigInteger(gasEstimates.VerificationGasLimit).Value; - partialUserOp.PreVerificationGas = new HexBigInteger(gasEstimates.PreVerificationGas).Value; + var gasEstimates = await ThirdwebBundler.EthEstimateUserOperationGas(this.Client, this._bundlerUrl, requestId, EncodeUserOperation(partialUserOp), this._entryPointContract.Address); + partialUserOp.CallGasLimit = gasEstimates.CallGasLimit.HexToNumber(); + partialUserOp.VerificationGasLimit = gasEstimates.VerificationGasLimit.HexToNumber(); + partialUserOp.PreVerificationGas = gasEstimates.PreVerificationGas.HexToNumber(); } else { - partialUserOp.CallGasLimit = new HexBigInteger(pmSponsorResult.CallGasLimit).Value; - partialUserOp.VerificationGasLimit = new HexBigInteger(pmSponsorResult.VerificationGasLimit).Value; - partialUserOp.PreVerificationGas = new HexBigInteger(pmSponsorResult.PreVerificationGas).Value; + partialUserOp.CallGasLimit = pmSponsorResult.CallGasLimit.HexToNumber(); + partialUserOp.VerificationGasLimit = pmSponsorResult.VerificationGasLimit.HexToNumber(); + partialUserOp.PreVerificationGas = pmSponsorResult.PreVerificationGas.HexToNumber(); } // Hash, sign and encode the user operation @@ -703,24 +677,13 @@ private async Task SignUserOp(ThirdwebTransactionInput transactionInput, } else { -#pragma warning disable IDE0078 // Use pattern matching - var executeFn = new ExecuteFunction - { - Target = transactionInput.To, - Value = transactionInput.ChainId.Value == 295 || transactionInput.ChainId.Value == 296 ? transactionInput.Value.Value / BigInteger.Pow(10, 10) : transactionInput.Value.Value, - Calldata = transactionInput.Data.HexToBytes(), - FromAddress = await this.GetAddress().ConfigureAwait(false), - }; -#pragma warning restore IDE0078 // Use pattern matching - var executeInput = executeFn.CreateTransactionInput(await this.GetAddress().ConfigureAwait(false)); - var partialUserOp = new UserOperationV7() { Sender = this._accountContract.Address, Nonce = await this.GetNonce().ConfigureAwait(false), Factory = factory, FactoryData = factoryData.HexToBytes(), - CallData = executeInput.Data.HexToBytes(), + CallData = executeInput.HexToBytes(), CallGasLimit = 0, VerificationGasLimit = 0, PreVerificationGas = 0, @@ -746,28 +709,28 @@ private async Task SignUserOp(ThirdwebTransactionInput transactionInput, var abiEncoder = new ABIEncode(); var slotBytes = abiEncoder.GetABIEncoded(new ABIValue("address", this._accountContract.Address), new ABIValue("uint256", this._erc20PaymasterStorageSlot)); var desiredBalance = BigInteger.Pow(2, 96) - 1; - var storageDict = new Dictionary { { new Sha3Keccack().CalculateHash(slotBytes).BytesToHex(), desiredBalance.ToHexBigInteger().HexValue.HexToBytes32().BytesToHex() } }; + var storageDict = new Dictionary { { new Sha3Keccack().CalculateHash(slotBytes).BytesToHex(), desiredBalance.NumberToHex().HexToBytes32().BytesToHex() } }; stateDict = new Dictionary { { this._erc20PaymasterToken, new { stateDiff = storageDict } } }; } else { - partialUserOp.PreVerificationGas = new HexBigInteger(pmSponsorResult.PreVerificationGas ?? "0x0").Value; - partialUserOp.VerificationGasLimit = new HexBigInteger(pmSponsorResult.VerificationGasLimit ?? "0x0").Value; - partialUserOp.CallGasLimit = new HexBigInteger(pmSponsorResult.CallGasLimit ?? "0x0").Value; - partialUserOp.PaymasterVerificationGasLimit = new HexBigInteger(pmSponsorResult.PaymasterVerificationGasLimit ?? "0x0").Value; - partialUserOp.PaymasterPostOpGasLimit = new HexBigInteger(pmSponsorResult.PaymasterPostOpGasLimit ?? "0x0").Value; + partialUserOp.PreVerificationGas = (pmSponsorResult.PreVerificationGas ?? "0x0").HexToNumber(); + partialUserOp.VerificationGasLimit = (pmSponsorResult.VerificationGasLimit ?? "0x0").HexToNumber(); + partialUserOp.CallGasLimit = (pmSponsorResult.CallGasLimit ?? "0x0").HexToNumber(); + partialUserOp.PaymasterVerificationGasLimit = (pmSponsorResult.PaymasterVerificationGasLimit ?? "0x0").HexToNumber(); + partialUserOp.PaymasterPostOpGasLimit = (pmSponsorResult.PaymasterPostOpGasLimit ?? "0x0").HexToNumber(); } if (partialUserOp.PreVerificationGas == 0 || partialUserOp.VerificationGasLimit == 0) { - var gasEstimates = await BundlerClient + var gasEstimates = await ThirdwebBundler .EthEstimateUserOperationGas(this.Client, this._bundlerUrl, requestId, EncodeUserOperation(partialUserOp), this._entryPointContract.Address, stateDict) .ConfigureAwait(false); - partialUserOp.CallGasLimit = new HexBigInteger(gasEstimates.CallGasLimit).Value; - partialUserOp.VerificationGasLimit = new HexBigInteger(gasEstimates.VerificationGasLimit).Value; - partialUserOp.PreVerificationGas = new HexBigInteger(gasEstimates.PreVerificationGas).Value; - partialUserOp.PaymasterVerificationGasLimit = new HexBigInteger(gasEstimates.PaymasterVerificationGasLimit).Value; - partialUserOp.PaymasterPostOpGasLimit = this.UseERC20Paymaster && !this._isApproving ? 500_000 : new HexBigInteger(gasEstimates.PaymasterPostOpGasLimit).Value; + partialUserOp.CallGasLimit = gasEstimates.CallGasLimit.HexToNumber(); + partialUserOp.VerificationGasLimit = gasEstimates.VerificationGasLimit.HexToNumber(); + partialUserOp.PreVerificationGas = gasEstimates.PreVerificationGas.HexToNumber(); + partialUserOp.PaymasterVerificationGasLimit = gasEstimates.PaymasterVerificationGasLimit.HexToNumber(); + partialUserOp.PaymasterPostOpGasLimit = this.UseERC20Paymaster && !this._isApproving ? 500_000 : gasEstimates.PaymasterPostOpGasLimit.HexToNumber(); } // Hash, sign and encode the user operation @@ -796,7 +759,7 @@ private async Task SendUserOp(object userOperation, int? requestId = nul // Send the user operation - var userOpHash = await BundlerClient.EthSendUserOperation(this.Client, this._bundlerUrl, requestId, encodedOp, this._entryPointContract.Address).ConfigureAwait(false); + var userOpHash = await ThirdwebBundler.EthSendUserOperation(this.Client, this._bundlerUrl, requestId, encodedOp, this._entryPointContract.Address).ConfigureAwait(false); // Wait for the transaction to be mined @@ -808,7 +771,7 @@ private async Task SendUserOp(object userOperation, int? requestId = nul { ct.Token.ThrowIfCancellationRequested(); - var userOpReceipt = await BundlerClient.EthGetUserOperationReceipt(this.Client, this._bundlerUrl, requestId, userOpHash).ConfigureAwait(false); + var userOpReceipt = await ThirdwebBundler.EthGetUserOperationReceipt(this.Client, this._bundlerUrl, requestId, userOpHash).ConfigureAwait(false); txHash = userOpReceipt?.Receipt?.TransactionHash; await ThirdwebTask.Delay(100, ct.Token).ConfigureAwait(false); @@ -836,7 +799,7 @@ private async Task GetNonce() { if (this._gasless) { - var result = await BundlerClient.ZkPaymasterData(this.Client, this._paymasterUrl, 1, transactionInput).ConfigureAwait(false); + var result = await ThirdwebBundler.ZkPaymasterData(this.Client, this._paymasterUrl, 1, transactionInput).ConfigureAwait(false); return (result.Paymaster, result.PaymasterInput); } else @@ -847,7 +810,7 @@ private async Task GetNonce() private async Task ZkBroadcastTransaction(object transactionInput) { - var result = await BundlerClient.ZkBroadcastTransaction(this.Client, this._bundlerUrl, 1, transactionInput).ConfigureAwait(false); + var result = await ThirdwebBundler.ZkBroadcastTransaction(this.Client, this._bundlerUrl, 1, transactionInput).ConfigureAwait(false); return result.TransactionHash; } @@ -865,7 +828,7 @@ private async Task GetPaymasterAndData(object reques else { return this._gasless - ? await BundlerClient.PMSponsorUserOperation(this.Client, this._paymasterUrl, requestId, userOp, this._entryPointContract.Address).ConfigureAwait(false) + ? await ThirdwebBundler.PMSponsorUserOperation(this.Client, this._paymasterUrl, requestId, userOp, this._entryPointContract.Address).ConfigureAwait(false) : new PMSponsorOperationResponse(); } } @@ -888,14 +851,14 @@ private async Task HashAndSignUserOp(UserOperationV7 userOp, ThirdwebCon Buffer.BlockCopy(factoryBytes, 0, initCodeBuffer, 0, factoryBytes.Length); Buffer.BlockCopy(factoryDataBytes, 0, initCodeBuffer, factoryBytes.Length, factoryDataBytes.Length); - var verificationGasLimitBytes = userOp.VerificationGasLimit.ToHexBigInteger().HexValue.HexToBytes().PadBytes(16); - var callGasLimitBytes = userOp.CallGasLimit.ToHexBigInteger().HexValue.HexToBytes().PadBytes(16); + var verificationGasLimitBytes = userOp.VerificationGasLimit.NumberToHex().HexToBytes().PadBytes(16); + var callGasLimitBytes = userOp.CallGasLimit.NumberToHex().HexToBytes().PadBytes(16); var accountGasLimitsBuffer = new byte[32]; Buffer.BlockCopy(verificationGasLimitBytes, 0, accountGasLimitsBuffer, 0, 16); Buffer.BlockCopy(callGasLimitBytes, 0, accountGasLimitsBuffer, 16, 16); - var maxPriorityFeePerGasBytes = userOp.MaxPriorityFeePerGas.ToHexBigInteger().HexValue.HexToBytes().PadBytes(16); - var maxFeePerGasBytes = userOp.MaxFeePerGas.ToHexBigInteger().HexValue.HexToBytes().PadBytes(16); + var maxPriorityFeePerGasBytes = userOp.MaxPriorityFeePerGas.NumberToHex().HexToBytes().PadBytes(16); + var maxFeePerGasBytes = userOp.MaxFeePerGas.NumberToHex().HexToBytes().PadBytes(16); var gasFeesBuffer = new byte[32]; Buffer.BlockCopy(maxPriorityFeePerGasBytes, 0, gasFeesBuffer, 0, 16); Buffer.BlockCopy(maxFeePerGasBytes, 0, gasFeesBuffer, 16, 16); @@ -919,8 +882,8 @@ private async Task HashAndSignUserOp(UserOperationV7 userOp, ThirdwebCon else { var paymasterBytes = userOp.Paymaster.HexToBytes(); - var paymasterVerificationGasLimitBytes = userOp.PaymasterVerificationGasLimit.ToHexBigInteger().HexValue.HexToBytes().PadBytes(16); - var paymasterPostOpGasLimitBytes = userOp.PaymasterPostOpGasLimit.ToHexBigInteger().HexValue.HexToBytes().PadBytes(16); + var paymasterVerificationGasLimitBytes = userOp.PaymasterVerificationGasLimit.NumberToHex().HexToBytes().PadBytes(16); + var paymasterPostOpGasLimitBytes = userOp.PaymasterPostOpGasLimit.NumberToHex().HexToBytes().PadBytes(16); var paymasterDataBytes = userOp.PaymasterData; var paymasterAndDataBuffer = new byte[20 + 16 + 16 + paymasterDataBytes.Length]; Buffer.BlockCopy(paymasterBytes, 0, paymasterAndDataBuffer, 0, 20); @@ -957,14 +920,14 @@ private static UserOperationHexifiedV6 EncodeUserOperation(UserOperationV6 userO return new UserOperationHexifiedV6() { Sender = userOperation.Sender, - Nonce = userOperation.Nonce.ToHexBigInteger().HexValue, + Nonce = userOperation.Nonce.NumberToHex(), InitCode = userOperation.InitCode.BytesToHex(), CallData = userOperation.CallData.BytesToHex(), - CallGasLimit = userOperation.CallGasLimit.ToHexBigInteger().HexValue, - VerificationGasLimit = userOperation.VerificationGasLimit.ToHexBigInteger().HexValue, - PreVerificationGas = userOperation.PreVerificationGas.ToHexBigInteger().HexValue, - MaxFeePerGas = userOperation.MaxFeePerGas.ToHexBigInteger().HexValue, - MaxPriorityFeePerGas = userOperation.MaxPriorityFeePerGas.ToHexBigInteger().HexValue, + CallGasLimit = userOperation.CallGasLimit.NumberToHex(), + VerificationGasLimit = userOperation.VerificationGasLimit.NumberToHex(), + PreVerificationGas = userOperation.PreVerificationGas.NumberToHex(), + MaxFeePerGas = userOperation.MaxFeePerGas.NumberToHex(), + MaxPriorityFeePerGas = userOperation.MaxPriorityFeePerGas.NumberToHex(), PaymasterAndData = userOperation.PaymasterAndData.BytesToHex(), Signature = userOperation.Signature.BytesToHex(), }; @@ -975,18 +938,18 @@ private static UserOperationHexifiedV7 EncodeUserOperation(UserOperationV7 userO return new UserOperationHexifiedV7() { Sender = userOperation.Sender, - Nonce = Utils.HexConcat(Constants.ADDRESS_ZERO, userOperation.Nonce.ToHexBigInteger().HexValue), + Nonce = Utils.HexConcat(Constants.ADDRESS_ZERO, userOperation.Nonce.NumberToHex()), Factory = userOperation.Factory, FactoryData = userOperation.FactoryData.BytesToHex(), CallData = userOperation.CallData.BytesToHex(), - CallGasLimit = userOperation.CallGasLimit.ToHexBigInteger().HexValue, - VerificationGasLimit = userOperation.VerificationGasLimit.ToHexBigInteger().HexValue, - PreVerificationGas = userOperation.PreVerificationGas.ToHexBigInteger().HexValue, - MaxFeePerGas = userOperation.MaxFeePerGas.ToHexBigInteger().HexValue, - MaxPriorityFeePerGas = userOperation.MaxPriorityFeePerGas.ToHexBigInteger().HexValue, + CallGasLimit = userOperation.CallGasLimit.NumberToHex(), + VerificationGasLimit = userOperation.VerificationGasLimit.NumberToHex(), + PreVerificationGas = userOperation.PreVerificationGas.NumberToHex(), + MaxFeePerGas = userOperation.MaxFeePerGas.NumberToHex(), + MaxPriorityFeePerGas = userOperation.MaxPriorityFeePerGas.NumberToHex(), Paymaster = userOperation.Paymaster, - PaymasterVerificationGasLimit = userOperation.PaymasterVerificationGasLimit.ToHexBigInteger().HexValue, - PaymasterPostOpGasLimit = userOperation.PaymasterPostOpGasLimit.ToHexBigInteger().HexValue, + PaymasterVerificationGasLimit = userOperation.PaymasterVerificationGasLimit.NumberToHex(), + PaymasterPostOpGasLimit = userOperation.PaymasterPostOpGasLimit.NumberToHex(), PaymasterData = userOperation.PaymasterData.BytesToHex(), Signature = userOperation.Signature.BytesToHex(), }; @@ -1065,21 +1028,6 @@ public async Task GetAddress() : this._accountContract.Address.ToChecksumAddress(); } - public Task EthSign(byte[] rawMessage) - { - throw new NotImplementedException(); - } - - public Task EthSign(string message) - { - throw new NotImplementedException(); - } - - public Task RecoverAddressFromEthSign(string message, string signature) - { - throw new NotImplementedException(); - } - public Task PersonalSign(byte[] rawMessage) { throw new NotImplementedException(); @@ -1113,13 +1061,6 @@ public async Task PersonalSign(string message) return isValid ? sig : throw new Exception("Invalid signature."); } - public async Task RecoverAddressFromPersonalSign(string message, string signature) - { - return !await this.IsValidSignature(message, signature).ConfigureAwait(false) - ? await this._personalAccount.RecoverAddressFromPersonalSign(message, signature).ConfigureAwait(false) - : await this.GetAddress().ConfigureAwait(false); - } - public Task SignTypedDataV4(string json) { // TODO: Implement wrapped version @@ -1133,12 +1074,6 @@ public Task SignTypedDataV4(T data, TypedData typed return this._personalAccount.SignTypedDataV4(data, typedData); } - public Task RecoverAddressFromTypedDataV4(T data, TypedData typedData, string signature) - where TDomain : IDomain - { - return this._personalAccount.RecoverAddressFromTypedDataV4(data, typedData, signature); - } - public async Task SignTransaction(ThirdwebTransactionInput transaction) { await this.SwitchNetwork(transaction.ChainId.Value).ConfigureAwait(false); @@ -1196,8 +1131,7 @@ public async Task> LinkAccount( BigInteger? chainId = null, string jwt = null, string payload = null, - string defaultSessionIdOverride = null, - List forceWalletIds = null + string defaultSessionIdOverride = null ) { var personalWallet = await this.GetPersonalWallet().ConfigureAwait(false); @@ -1220,7 +1154,7 @@ public async Task> LinkAccount( else { return await personalWallet - .LinkAccount(walletToLink, otp, isMobile, browserOpenAction, mobileRedirectScheme, browser, chainId, jwt, payload, defaultSessionIdOverride, forceWalletIds) + .LinkAccount(walletToLink, otp, isMobile, browserOpenAction, mobileRedirectScheme, browser, chainId, jwt, payload, defaultSessionIdOverride) .ConfigureAwait(false); } } diff --git a/Thirdweb/Thirdweb.Wallets/SmartWallet/Thirdweb.AccountAbstraction/AATypes.cs b/Thirdweb/Thirdweb.Wallets/SmartWallet/Thirdweb.AccountAbstraction/ThirdwebBundler.Types.cs similarity index 98% rename from Thirdweb/Thirdweb.Wallets/SmartWallet/Thirdweb.AccountAbstraction/AATypes.cs rename to Thirdweb/Thirdweb.Wallets/SmartWallet/Thirdweb.AccountAbstraction/ThirdwebBundler.Types.cs index 72e44d1b..8db23e3a 100644 --- a/Thirdweb/Thirdweb.Wallets/SmartWallet/Thirdweb.AccountAbstraction/AATypes.cs +++ b/Thirdweb/Thirdweb.Wallets/SmartWallet/Thirdweb.AccountAbstraction/ThirdwebBundler.Types.cs @@ -1,6 +1,5 @@ using System.Numerics; using Nethereum.ABI.FunctionEncoding.Attributes; -using Nethereum.Contracts; using Newtonsoft.Json; namespace Thirdweb.AccountAbstraction; @@ -203,19 +202,6 @@ public class UserOperationHexifiedV7 public string Signature { get; set; } } -[Function("execute")] -public class ExecuteFunction : FunctionMessage -{ - [Parameter("address", "_target", 1)] - public virtual string Target { get; set; } - - [Parameter("uint256", "_value", 2)] - public virtual BigInteger Value { get; set; } - - [Parameter("bytes", "_calldata", 3)] - public virtual byte[] Calldata { get; set; } -} - public class EthEstimateUserOperationGasResponse { [JsonProperty("preVerificationGas")] diff --git a/Thirdweb/Thirdweb.Wallets/SmartWallet/Thirdweb.AccountAbstraction/BundlerClient.cs b/Thirdweb/Thirdweb.Wallets/SmartWallet/Thirdweb.AccountAbstraction/ThirdwebBundler.cs similarity index 98% rename from Thirdweb/Thirdweb.Wallets/SmartWallet/Thirdweb.AccountAbstraction/BundlerClient.cs rename to Thirdweb/Thirdweb.Wallets/SmartWallet/Thirdweb.AccountAbstraction/ThirdwebBundler.cs index a98a1d82..e718bb1b 100644 --- a/Thirdweb/Thirdweb.Wallets/SmartWallet/Thirdweb.AccountAbstraction/BundlerClient.cs +++ b/Thirdweb/Thirdweb.Wallets/SmartWallet/Thirdweb.AccountAbstraction/ThirdwebBundler.cs @@ -1,9 +1,8 @@ -using Nethereum.JsonRpc.Client.RpcMessages; -using Newtonsoft.Json; +using Newtonsoft.Json; namespace Thirdweb.AccountAbstraction; -public static class BundlerClient +public static class ThirdwebBundler { // EIP 7702 requests public static async Task TwGetDelegationContract(ThirdwebClient client, string url, int requestId) diff --git a/Thirdweb/Thirdweb.csproj b/Thirdweb/Thirdweb.csproj index a184183c..5e0f9f12 100644 --- a/Thirdweb/Thirdweb.csproj +++ b/Thirdweb/Thirdweb.csproj @@ -27,13 +27,10 @@ - - - - - - - + + + + diff --git a/codecov.yml b/codecov.yml index c63bf629..9bd94214 100644 --- a/codecov.yml +++ b/codecov.yml @@ -1,4 +1,3 @@ ignore: - "Thirdweb/Thirdweb.Wallets/InAppWallet" - - "Thirdweb/Thirdweb.Pay" - - "Thirdweb/Thirdweb.Api/GeneratedClient.cs" \ No newline at end of file + - "Thirdweb/Thirdweb.Api" \ No newline at end of file diff --git a/nswag.json b/nswag.json deleted file mode 100644 index 765308fc..00000000 --- a/nswag.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "runtime": "Net80", - "defaultVariables": null, - "documentGenerator": { - "fromDocument": { - "url": "https://api.thirdweb.com/openapi.json", - "output": null - } - }, - "codeGenerators": { - "openApiToCSharpClient": { - "clientBaseClass": null, - "httpClientType": "ThirdwebHttpClientWrapper", - "generateClientClasses": true, - "generateClientInterfaces": false, - "generateDtoTypes": true, - "injectHttpClient": true, - "disposeHttpClient": false, - "generateExceptionClasses": true, - "exceptionClass": "ThirdwebApiException", - "wrapDtoExceptions": true, - "useHttpClientCreationMethod": false, - "useHttpRequestMessageCreationMethod": false, - "useBaseUrl": true, - "generateBaseUrlProperty": true, - "generateSyncMethods": false, - "exposeJsonSerializerSettings": false, - "clientClassAccessModifier": "internal", - "typeAccessModifier": "public", - "generateContractsOutput": false, - "parameterDateTimeFormat": "s", - "generateUpdateJsonSerializerSettingsMethod": true, - "serializeTypeInformation": false, - "queryNullValue": "", - "className": "ThirdwebApiClient", - "operationGenerationMode": "SingleClientFromOperationId", - "generateOptionalParameters": false, - "generateJsonMethods": false, - "parameterArrayType": "System.Collections.Generic.IEnumerable", - "parameterDictionaryType": "System.Collections.Generic.IDictionary", - "responseArrayType": "System.Collections.Generic.List", - "responseDictionaryType": "System.Collections.Generic.Dictionary", - "wrapResponses": false, - "generateResponseClasses": true, - "responseClass": "ApiResponse", - "namespace": "Thirdweb.Api", - "requiredPropertiesMustBeDefined": true, - "dateType": "System.DateTime", - "dateTimeType": "System.DateTime", - "timeType": "System.TimeSpan", - "timeSpanType": "System.TimeSpan", - "arrayType": "System.Collections.Generic.List", - "arrayInstanceType": "System.Collections.Generic.List", - "dictionaryType": "System.Collections.Generic.Dictionary", - "dictionaryInstanceType": "System.Collections.Generic.Dictionary", - "arrayBaseType": "System.Collections.Generic.List", - "dictionaryBaseType": "System.Collections.Generic.Dictionary", - "classStyle": "Poco", - "generateDefaultValues": true, - "generateDataAnnotations": true, - "excludedTypeNames": [], - "handleReferences": false, - "generateImmutableArrayProperties": false, - "generateImmutableDictionaryProperties": false, - "jsonConverters": null, - "anyType": "object", - "output": "Thirdweb/Thirdweb.Api/GeneratedClient.cs" - } - } -} diff --git a/thirdweb.sln b/thirdweb.sln index d2de2199..9f425dc9 100644 --- a/thirdweb.sln +++ b/thirdweb.sln @@ -8,6 +8,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Thirdweb.Console", "Thirdwe EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Thirdweb.Tests", "Thirdweb.Tests\Thirdweb.Tests.csproj", "{7CEBE316-4F2E-433B-8B1D-CBE8F8EE328F}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Thirdweb.Generator", "Thirdweb.Generator\Thirdweb.Generator.csproj", "{FC27BC73-7F36-4658-9CBD-940957EE6795}" +EndProject Global GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -57,5 +59,17 @@ Global {7CEBE316-4F2E-433B-8B1D-CBE8F8EE328F}.Release|x64.Build.0 = Release|Any CPU {7CEBE316-4F2E-433B-8B1D-CBE8F8EE328F}.Release|x86.ActiveCfg = Release|Any CPU {7CEBE316-4F2E-433B-8B1D-CBE8F8EE328F}.Release|x86.Build.0 = Release|Any CPU + {FC27BC73-7F36-4658-9CBD-940957EE6795}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FC27BC73-7F36-4658-9CBD-940957EE6795}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FC27BC73-7F36-4658-9CBD-940957EE6795}.Debug|x64.ActiveCfg = Debug|Any CPU + {FC27BC73-7F36-4658-9CBD-940957EE6795}.Debug|x64.Build.0 = Debug|Any CPU + {FC27BC73-7F36-4658-9CBD-940957EE6795}.Debug|x86.ActiveCfg = Debug|Any CPU + {FC27BC73-7F36-4658-9CBD-940957EE6795}.Debug|x86.Build.0 = Debug|Any CPU + {FC27BC73-7F36-4658-9CBD-940957EE6795}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FC27BC73-7F36-4658-9CBD-940957EE6795}.Release|Any CPU.Build.0 = Release|Any CPU + {FC27BC73-7F36-4658-9CBD-940957EE6795}.Release|x64.ActiveCfg = Release|Any CPU + {FC27BC73-7F36-4658-9CBD-940957EE6795}.Release|x64.Build.0 = Release|Any CPU + {FC27BC73-7F36-4658-9CBD-940957EE6795}.Release|x86.ActiveCfg = Release|Any CPU + {FC27BC73-7F36-4658-9CBD-940957EE6795}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection EndGlobal diff --git a/tw.bat b/tw.bat deleted file mode 100644 index 2c867827..00000000 --- a/tw.bat +++ /dev/null @@ -1,146 +0,0 @@ -@echo off -REM Thirdweb Build Script -REM Usage: tw.bat [command] - -REM Check if command was provided -if "%1"=="" goto help -if "%1"=="help" goto help -if "%1"=="clean-api" goto clean-api -if "%1"=="generate-api" goto generate-api -if "%1"=="build" goto build -if "%1"=="clean" goto clean -if "%1"=="restore" goto restore -if "%1"=="test" goto test -if "%1"=="pack" goto pack -if "%1"=="run" goto run -if "%1"=="lint" goto lint -if "%1"=="fix" goto fix -goto help - -:clean-api -echo Cleaning generated API files... -if exist "Thirdweb\Thirdweb.Api\GeneratedClient.cs" ( - echo Removing generated client file... - del /q "Thirdweb\Thirdweb.Api\GeneratedClient.cs" -) else ( - echo No generated client file to clean -) -echo Clean completed! -goto end - -:generate-api -echo Generating Thirdweb API client with NSwag... - -REM Check if NSwag is installed -nswag version >nul 2>&1 -if errorlevel 1 ( - echo NSwag CLI is not installed. Installing via dotnet tool... - dotnet tool install --global NSwag.ConsoleCore - if errorlevel 1 ( - echo Failed to install NSwag CLI - exit /b 1 - ) -) - -REM Generate API client using NSwag -echo Running NSwag to generate client... -nswag run nswag.json -if errorlevel 1 ( - echo Failed to generate API client - exit /b 1 -) - -echo API client generation complete! -exit /b 0 - -:build -echo Building solution... -REM First generate the API if it doesn't exist -if not exist "Thirdweb\Thirdweb.Api\GeneratedClient.cs" ( - echo API client not found, generating it first... - call :generate-api - if errorlevel 1 goto end -) -dotnet build -goto end - -:clean -echo Cleaning solution... -dotnet clean -goto end - -:restore -echo Restoring packages... -dotnet restore -goto end - -:test -echo Running tests... -dotnet test -goto end - -:pack -echo Creating NuGet packages... -REM Ensure API is generated before packing -if not exist "Thirdweb\Thirdweb.Api\GeneratedClient.cs" ( - echo API client not found, generating it first... - call :generate-api - if errorlevel 1 goto end -) -dotnet build --configuration Release -dotnet pack --configuration Release -goto end - -:run -echo Running console application... -dotnet run --project Thirdweb.Console -goto end - -:lint -echo Checking code formatting with CSharpier... -csharpier --help >nul 2>&1 -if errorlevel 1 ( - echo CSharpier is not installed. Install it with: dotnet tool install -g csharpier - goto end -) -csharpier check . -if errorlevel 1 ( - echo Code formatting issues found! Run 'tw fix' to automatically fix them. - goto end -) -echo Code formatting is correct! -goto end - -:fix -echo Fixing code formatting with CSharpier... -csharpier --help >nul 2>&1 -if errorlevel 1 ( - echo CSharpier is not installed. Install it with: dotnet tool install -g csharpier - goto end -) -csharpier format . -if errorlevel 1 ( - echo CSharpier formatting failed! - goto end -) -echo Code formatting completed! -goto end - -:help -echo Available commands: -echo build - Generate API (if needed) and build the solution -echo clean - Clean build artifacts -echo restore - Restore NuGet packages -echo test - Run tests -echo pack - Generate API (if needed) and create NuGet package -echo run - Run the console application -echo generate-api - Generate API client from OpenAPI spec -echo clean-api - Clean generated API files -echo lint - Check code formatting (dry run) -echo fix - Fix code formatting issues -echo help - Show this help message -echo. -echo Usage: tw.bat [command] -goto end - -:end