From c9bd45035d27d0565453a7e8913692b945e5dff5 Mon Sep 17 00:00:00 2001 From: perror <23651751+perrornet@users.noreply.github.com> Date: Fri, 14 Jun 2024 14:57:45 +0800 Subject: [PATCH] Init --- .github/workflows/release.yaml | 90 + .github/workflows/test.yaml | 45 + .gitignore | 5 + Dockerfile | 25 + README.md | 269 ++ cmd/configs.go | 241 ++ cmd/main.go | 181 + go.mod | 147 + go.sum | 443 +++ internal/daemons/cross_chain/cross_chain.go | 139 + internal/daemons/init.go | 120 + internal/daemons/monitor/monitor.go | 99 + internal/daemons/rebalance/rebalance.go | 336 ++ internal/daemons/token_price/token_price.go | 60 + internal/daemons/utils.go | 72 + internal/db/db.go | 53 + internal/models/order.go | 102 + internal/models/token_price.go | 84 + utils/chains/client.go | 165 + utils/chains/eip712.go | 39 + utils/chains/util.go | 325 ++ utils/configs/config.go | 468 +++ utils/constant/chain.go | 110 + utils/constant/tests_data.go | 20 + utils/constant/token.go | 50 + utils/consts.go | 16 + utils/erc20/erc20.go | 759 ++++ utils/error_types/errors.go | 17 + utils/locks/lock.go | 75 + utils/locks/lock_test.go | 86 + utils/notice/notice.go | 67 + utils/notice/slack.go | 82 + utils/provider/bridge/darwinia/abi.go | 376 ++ utils/provider/bridge/darwinia/consts.go | 77 + .../provider/bridge/darwinia/crab2darwinia.go | 122 + .../bridge/darwinia/crab2darwinia_test.go | 38 + utils/provider/bridge/darwinia/darwinia.go | 310 ++ .../provider/bridge/darwinia/darwinia2crab.go | 117 + .../bridge/darwinia/darwinia2crab_test.go | 38 + .../bridge/darwinia/darwinia2ethereum.go | 112 + .../bridge/darwinia/darwinia2ethereum_test.go | 38 + .../bridge/darwinia/ethereum2darwinia.go | 112 + .../bridge/darwinia/ethereum2darwinia_test.go | 93 + utils/provider/bridge/darwinia/init.go | 10 + utils/provider/bridge/darwinia/utils.go | 348 ++ .../bridge/helix/abi_v2_default/v2-default.go | 213 + .../helix/abi_v2_opposite/v2_opposite.go | 213 + utils/provider/bridge/helix/abi_v3/v3.go | 214 ++ utils/provider/bridge/helix/configs.go | 108 + utils/provider/bridge/helix/helix.go | 230 ++ utils/provider/bridge/helix/init.go | 45 + utils/provider/bridge/helix/lnv2_opposite.go | 70 + .../bridge/helix/lnv2_opposite_test.go | 85 + utils/provider/bridge/helix/utils.go | 417 ++ utils/provider/bridge/helix/v2_default.go | 90 + .../provider/bridge/helix/v2_default_test.go | 194 + utils/provider/bridge/helix/v3.go | 86 + utils/provider/bridge/helix/v3_test.go | 112 + utils/provider/bridge/okx/okx.go | 260 ++ utils/provider/bridge/okx/utils.go | 271 ++ utils/provider/bridge/okx/vars.go | 299 ++ utils/provider/cex/gate/gate.io.go | 418 ++ utils/provider/cex/gate/init.go | 10 + utils/provider/cex/gate/utils.go | 203 + .../dex/snowswap/snow_router/snow_router.go | 776 ++++ utils/provider/dex/snowswap/snowswap.go | 41 + .../dex/uniswap/abi/permit2/permit2.go | 1392 +++++++ .../dex/uniswap/abi/v2Router02/v2Router02.go | 776 ++++ .../uniswap/abi/v3SwapRouter/v3SwapRouter.go | 621 +++ .../abi/v3SwapRouter02/v3SwapRouter02.go | 1136 ++++++ .../v3UniversalRouter/v3UniversalRouter.go | 568 +++ utils/provider/dex/uniswap/configs/configs.go | 247 ++ utils/provider/dex/uniswap/init.go | 10 + utils/provider/dex/uniswap/uniswap.go | 235 ++ utils/provider/dex/uniswap/uniswap_test.go | 218 ++ utils/provider/dex/uniswap/utils.go | 197 + utils/provider/dex/uniswap/utils/execute.go | 289 ++ .../dex/uniswap/utils/execute_test.go | 199 + utils/provider/dex/uniswap/utils/permit2.go | 22 + utils/provider/dex/uniswap/utils/utils.go | 339 ++ utils/provider/init.go | 77 + utils/provider/provider.go | 279 ++ utils/provider/utils.go | 161 + utils/safe_api/all_transactions_schema.go | 206 + utils/safe_api/client/about/about_client.go | 311 ++ .../v1_about_deployments_list_parameters.go | 197 + .../v1_about_deployments_list_responses.go | 166 + .../v1_about_ethereum_rpc_list_parameters.go | 128 + .../v1_about_ethereum_rpc_list_responses.go | 88 + ...ut_ethereum_tracing_rpc_list_parameters.go | 128 + ...out_ethereum_tracing_rpc_list_responses.go | 88 + .../v1_about_indexing_list_parameters.go | 128 + .../about/v1_about_indexing_list_responses.go | 104 + .../client/about/v1_about_list_parameters.go | 128 + .../client/about/v1_about_list_responses.go | 88 + .../v1_about_singletons_list_parameters.go | 128 + .../v1_about_singletons_list_responses.go | 104 + .../client/contracts/contracts_client.go | 147 + .../contracts/v1_contracts_list_parameters.go | 232 ++ .../contracts/v1_contracts_list_responses.go | 277 ++ .../contracts/v1_contracts_read_parameters.go | 151 + .../contracts/v1_contracts_read_responses.go | 106 + .../data_decoder/data_decoder_client.go | 110 + .../v1_data_decoder_create_parameters.go | 150 + .../v1_data_decoder_create_responses.go | 212 + .../client/delegates/delegates_client.go | 360 ++ .../v1_delegates_create_parameters.go | 150 + .../v1_delegates_create_responses.go | 150 + .../v1_delegates_delete_parameters.go | 169 + .../v1_delegates_delete_responses.go | 274 ++ .../delegates/v1_delegates_list_parameters.go | 334 ++ .../delegates/v1_delegates_list_responses.go | 339 ++ .../v2_delegates_create_parameters.go | 150 + .../v2_delegates_create_responses.go | 150 + .../v2_delegates_delete_parameters.go | 169 + .../v2_delegates_delete_responses.go | 274 ++ .../delegates/v2_delegates_list_parameters.go | 334 ++ .../delegates/v2_delegates_list_responses.go | 339 ++ .../client/messages/messages_client.go | 235 ++ .../messages/v1_messages_read_parameters.go | 156 + .../messages/v1_messages_read_responses.go | 106 + ...1_messages_signatures_create_parameters.go | 169 + ...v1_messages_signatures_create_responses.go | 88 + .../v1_safes_messages_create_parameters.go | 169 + .../v1_safes_messages_create_responses.go | 88 + .../v1_safes_messages_list_parameters.go | 251 ++ .../v1_safes_messages_list_responses.go | 277 ++ .../safe_api/client/modules/modules_client.go | 106 + .../v1_modules_safes_list_parameters.go | 148 + .../v1_modules_safes_list_responses.go | 168 + .../notifications/notifications_client.go | 194 + ...notifications_devices_create_parameters.go | 150 + ..._notifications_devices_create_responses.go | 168 + ...notifications_devices_delete_parameters.go | 153 + ..._notifications_devices_delete_responses.go | 88 + ...cations_devices_safes_delete_parameters.go | 172 + ...ications_devices_safes_delete_responses.go | 88 + utils/safe_api/client/nr4337/nr4337_client.go | 277 ++ .../v1_safe_operations_read_parameters.go | 148 + .../v1_safe_operations_read_responses.go | 106 + ...safes_safe_operations_create_parameters.go | 169 + ..._safes_safe_operations_create_responses.go | 88 + ...1_safes_safe_operations_list_parameters.go | 251 ++ ...v1_safes_safe_operations_list_responses.go | 277 ++ ...1_safes_user_operations_list_parameters.go | 251 ++ ...v1_safes_user_operations_list_responses.go | 277 ++ .../v1_user_operations_read_parameters.go | 148 + .../v1_user_operations_read_responses.go | 106 + utils/safe_api/client/owners/owners_client.go | 106 + .../owners/v1_owners_safes_list_parameters.go | 148 + .../owners/v1_owners_safes_list_responses.go | 168 + .../safe_transaction_service_api_client.go | 172 + utils/safe_api/client/safes/safes_client.go | 272 ++ .../v1_safes_balances_list_parameters.go | 231 ++ .../safes/v1_safes_balances_list_responses.go | 228 ++ .../v1_safes_creation_list_parameters.go | 148 + .../safes/v1_safes_creation_list_responses.go | 292 ++ .../v1_safes_delegates_delete_parameters.go | 188 + .../v1_safes_delegates_delete_responses.go | 274 ++ .../client/safes/v1_safes_read_parameters.go | 148 + .../client/safes/v1_safes_read_responses.go | 232 ++ .../v2_safes_collectibles_list_parameters.go | 299 ++ .../v2_safes_collectibles_list_responses.go | 228 ++ utils/safe_api/client/tokens/tokens_client.go | 147 + .../tokens/v1_tokens_list_parameters.go | 470 +++ .../client/tokens/v1_tokens_list_responses.go | 277 ++ .../tokens/v1_tokens_read_parameters.go | 151 + .../client/tokens/v1_tokens_read_responses.go | 106 + .../transactions/transactions_client.go | 599 +++ .../v1_module_transaction_read_parameters.go | 148 + .../v1_module_transaction_read_responses.go | 230 ++ ...actions_confirmations_create_parameters.go | 169 + ...sactions_confirmations_create_responses.go | 212 + ...nsactions_confirmations_list_parameters.go | 217 ++ ...ansactions_confirmations_list_responses.go | 339 ++ ...multisig_transactions_delete_parameters.go | 169 + ..._multisig_transactions_delete_responses.go | 212 + ...1_multisig_transactions_read_parameters.go | 148 + ...v1_multisig_transactions_read_responses.go | 106 + ..._safes_all_transactions_list_parameters.go | 374 ++ ...1_safes_all_transactions_list_responses.go | 168 + ...afes_incoming_transfers_list_parameters.go | 795 ++++ ...safes_incoming_transfers_list_responses.go | 166 + ...fes_module_transactions_list_parameters.go | 557 +++ ...afes_module_transactions_list_responses.go | 401 ++ ...multisig_transactions_create_parameters.go | 169 + ..._multisig_transactions_create_responses.go | 207 + ...nsactions_estimations_create_parameters.go | 169 + ...ansactions_estimations_create_responses.go | 292 ++ ...s_multisig_transactions_list_parameters.go | 1033 +++++ ...es_multisig_transactions_list_responses.go | 401 ++ .../v1_safes_transfers_list_parameters.go | 795 ++++ .../v1_safes_transfers_list_responses.go | 166 + .../client/transfer/transfer_client.go | 106 + .../transfer/v1_transfer_read_parameters.go | 148 + .../transfer/v1_transfer_read_responses.go | 230 ++ utils/safe_api/contract.go | 220 ++ utils/safe_api/contract_abi.go | 110 + utils/safe_api/data_decoder.go | 74 + utils/safe_api/delegate.go | 135 + utils/safe_api/delegate_delete.go | 105 + .../safe_api/delegate_delete_serializer_v2.go | 91 + utils/safe_api/delegate_serializer_v2.go | 135 + utils/safe_api/erc20_info.go | 137 + .../ethereum_tx_with_transfers_response.go | 248 ++ utils/safe_api/firebase_device.go | 256 ++ ..._device_serializer_with_owners_response.go | 290 ++ utils/safe_api/indexing_status.go | 156 + utils/safe_api/master_copy_response.go | 166 + utils/safe_api/modules_response.go | 71 + utils/safe_api/owner_response.go | 71 + utils/safe_api/safe_balance_response.go | 152 + utils/safe_api/safe_collectible_response.go | 269 ++ utils/safe_api/safe_creation_info_response.go | 232 ++ utils/safe_api/safe_delegate_delete.go | 105 + utils/safe_api/safe_delegate_response.go | 132 + utils/safe_api/safe_deployment.go | 151 + utils/safe_api/safe_deployment_contract.go | 93 + utils/safe_api/safe_info_response.go | 212 + utils/safe_api/safe_message.go | 108 + utils/safe_api/safe_message_response.go | 222 ++ utils/safe_api/safe_message_signature.go | 71 + .../safe_module_transaction_response.go | 347 ++ ...ule_transaction_with_transfers_response.go | 429 +++ utils/safe_api/safe_multisig_confirmation.go | 71 + .../safe_multisig_confirmation_response.go | 157 + utils/safe_api/safe_multisig_transaction.go | 291 ++ .../safe_multisig_transaction_delete.go | 88 + .../safe_multisig_transaction_estimate.go | 118 + ..._multisig_transaction_estimate_response.go | 76 + .../safe_multisig_transaction_response.go | 626 +++ ...sig_transaction_with_transfers_response.go | 708 ++++ utils/safe_api/safe_operation.go | 332 ++ utils/safe_api/safe_operation_response.go | 215 ++ ..._operation_with_user_operation_response.go | 266 ++ utils/safe_api/token_info_response.go | 188 + .../transfer_with_token_info_response.go | 283 ++ utils/safe_api/user_operation_response.go | 339 ++ ..._operation_with_safe_operation_response.go | 395 ++ utils/token_price/binance.go | 56 + utils/token_price/bitget.go | 66 + utils/token_price/bybit.go | 66 + utils/token_price/gate.go | 50 + utils/token_price/init.go | 81 + utils/token_price/mexc.go | 46 + utils/token_price/okx.go | 56 + utils/util.go | 192 + utils/util_test.go | 132 + utils/wallet_monitor/monitor.go | 146 + utils/wallets/init.go | 13 + utils/wallets/private_key.go | 190 + utils/wallets/safe/init.go | 11 + utils/wallets/safe/safe.go | 161 + utils/wallets/safe/safe_abi/safe.go | 3412 +++++++++++++++++ utils/wallets/safe/utils.go | 434 +++ utils/wallets/wallets.go | 56 + 256 files changed, 56463 insertions(+) create mode 100644 .github/workflows/release.yaml create mode 100644 .github/workflows/test.yaml create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 README.md create mode 100644 cmd/configs.go create mode 100644 cmd/main.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/daemons/cross_chain/cross_chain.go create mode 100644 internal/daemons/init.go create mode 100644 internal/daemons/monitor/monitor.go create mode 100644 internal/daemons/rebalance/rebalance.go create mode 100644 internal/daemons/token_price/token_price.go create mode 100644 internal/daemons/utils.go create mode 100644 internal/db/db.go create mode 100644 internal/models/order.go create mode 100644 internal/models/token_price.go create mode 100644 utils/chains/client.go create mode 100644 utils/chains/eip712.go create mode 100644 utils/chains/util.go create mode 100644 utils/configs/config.go create mode 100644 utils/constant/chain.go create mode 100644 utils/constant/tests_data.go create mode 100644 utils/constant/token.go create mode 100644 utils/consts.go create mode 100644 utils/erc20/erc20.go create mode 100644 utils/error_types/errors.go create mode 100644 utils/locks/lock.go create mode 100644 utils/locks/lock_test.go create mode 100644 utils/notice/notice.go create mode 100644 utils/notice/slack.go create mode 100644 utils/provider/bridge/darwinia/abi.go create mode 100644 utils/provider/bridge/darwinia/consts.go create mode 100644 utils/provider/bridge/darwinia/crab2darwinia.go create mode 100644 utils/provider/bridge/darwinia/crab2darwinia_test.go create mode 100644 utils/provider/bridge/darwinia/darwinia.go create mode 100644 utils/provider/bridge/darwinia/darwinia2crab.go create mode 100644 utils/provider/bridge/darwinia/darwinia2crab_test.go create mode 100644 utils/provider/bridge/darwinia/darwinia2ethereum.go create mode 100644 utils/provider/bridge/darwinia/darwinia2ethereum_test.go create mode 100644 utils/provider/bridge/darwinia/ethereum2darwinia.go create mode 100644 utils/provider/bridge/darwinia/ethereum2darwinia_test.go create mode 100644 utils/provider/bridge/darwinia/init.go create mode 100644 utils/provider/bridge/darwinia/utils.go create mode 100644 utils/provider/bridge/helix/abi_v2_default/v2-default.go create mode 100644 utils/provider/bridge/helix/abi_v2_opposite/v2_opposite.go create mode 100644 utils/provider/bridge/helix/abi_v3/v3.go create mode 100644 utils/provider/bridge/helix/configs.go create mode 100644 utils/provider/bridge/helix/helix.go create mode 100644 utils/provider/bridge/helix/init.go create mode 100644 utils/provider/bridge/helix/lnv2_opposite.go create mode 100644 utils/provider/bridge/helix/lnv2_opposite_test.go create mode 100644 utils/provider/bridge/helix/utils.go create mode 100644 utils/provider/bridge/helix/v2_default.go create mode 100644 utils/provider/bridge/helix/v2_default_test.go create mode 100644 utils/provider/bridge/helix/v3.go create mode 100644 utils/provider/bridge/helix/v3_test.go create mode 100644 utils/provider/bridge/okx/okx.go create mode 100644 utils/provider/bridge/okx/utils.go create mode 100644 utils/provider/bridge/okx/vars.go create mode 100644 utils/provider/cex/gate/gate.io.go create mode 100644 utils/provider/cex/gate/init.go create mode 100644 utils/provider/cex/gate/utils.go create mode 100644 utils/provider/dex/snowswap/snow_router/snow_router.go create mode 100644 utils/provider/dex/snowswap/snowswap.go create mode 100644 utils/provider/dex/uniswap/abi/permit2/permit2.go create mode 100644 utils/provider/dex/uniswap/abi/v2Router02/v2Router02.go create mode 100644 utils/provider/dex/uniswap/abi/v3SwapRouter/v3SwapRouter.go create mode 100644 utils/provider/dex/uniswap/abi/v3SwapRouter02/v3SwapRouter02.go create mode 100644 utils/provider/dex/uniswap/abi/v3UniversalRouter/v3UniversalRouter.go create mode 100644 utils/provider/dex/uniswap/configs/configs.go create mode 100644 utils/provider/dex/uniswap/init.go create mode 100644 utils/provider/dex/uniswap/uniswap.go create mode 100644 utils/provider/dex/uniswap/uniswap_test.go create mode 100644 utils/provider/dex/uniswap/utils.go create mode 100644 utils/provider/dex/uniswap/utils/execute.go create mode 100644 utils/provider/dex/uniswap/utils/execute_test.go create mode 100644 utils/provider/dex/uniswap/utils/permit2.go create mode 100644 utils/provider/dex/uniswap/utils/utils.go create mode 100644 utils/provider/init.go create mode 100644 utils/provider/provider.go create mode 100644 utils/provider/utils.go create mode 100644 utils/safe_api/all_transactions_schema.go create mode 100644 utils/safe_api/client/about/about_client.go create mode 100644 utils/safe_api/client/about/v1_about_deployments_list_parameters.go create mode 100644 utils/safe_api/client/about/v1_about_deployments_list_responses.go create mode 100644 utils/safe_api/client/about/v1_about_ethereum_rpc_list_parameters.go create mode 100644 utils/safe_api/client/about/v1_about_ethereum_rpc_list_responses.go create mode 100644 utils/safe_api/client/about/v1_about_ethereum_tracing_rpc_list_parameters.go create mode 100644 utils/safe_api/client/about/v1_about_ethereum_tracing_rpc_list_responses.go create mode 100644 utils/safe_api/client/about/v1_about_indexing_list_parameters.go create mode 100644 utils/safe_api/client/about/v1_about_indexing_list_responses.go create mode 100644 utils/safe_api/client/about/v1_about_list_parameters.go create mode 100644 utils/safe_api/client/about/v1_about_list_responses.go create mode 100644 utils/safe_api/client/about/v1_about_singletons_list_parameters.go create mode 100644 utils/safe_api/client/about/v1_about_singletons_list_responses.go create mode 100644 utils/safe_api/client/contracts/contracts_client.go create mode 100644 utils/safe_api/client/contracts/v1_contracts_list_parameters.go create mode 100644 utils/safe_api/client/contracts/v1_contracts_list_responses.go create mode 100644 utils/safe_api/client/contracts/v1_contracts_read_parameters.go create mode 100644 utils/safe_api/client/contracts/v1_contracts_read_responses.go create mode 100644 utils/safe_api/client/data_decoder/data_decoder_client.go create mode 100644 utils/safe_api/client/data_decoder/v1_data_decoder_create_parameters.go create mode 100644 utils/safe_api/client/data_decoder/v1_data_decoder_create_responses.go create mode 100644 utils/safe_api/client/delegates/delegates_client.go create mode 100644 utils/safe_api/client/delegates/v1_delegates_create_parameters.go create mode 100644 utils/safe_api/client/delegates/v1_delegates_create_responses.go create mode 100644 utils/safe_api/client/delegates/v1_delegates_delete_parameters.go create mode 100644 utils/safe_api/client/delegates/v1_delegates_delete_responses.go create mode 100644 utils/safe_api/client/delegates/v1_delegates_list_parameters.go create mode 100644 utils/safe_api/client/delegates/v1_delegates_list_responses.go create mode 100644 utils/safe_api/client/delegates/v2_delegates_create_parameters.go create mode 100644 utils/safe_api/client/delegates/v2_delegates_create_responses.go create mode 100644 utils/safe_api/client/delegates/v2_delegates_delete_parameters.go create mode 100644 utils/safe_api/client/delegates/v2_delegates_delete_responses.go create mode 100644 utils/safe_api/client/delegates/v2_delegates_list_parameters.go create mode 100644 utils/safe_api/client/delegates/v2_delegates_list_responses.go create mode 100644 utils/safe_api/client/messages/messages_client.go create mode 100644 utils/safe_api/client/messages/v1_messages_read_parameters.go create mode 100644 utils/safe_api/client/messages/v1_messages_read_responses.go create mode 100644 utils/safe_api/client/messages/v1_messages_signatures_create_parameters.go create mode 100644 utils/safe_api/client/messages/v1_messages_signatures_create_responses.go create mode 100644 utils/safe_api/client/messages/v1_safes_messages_create_parameters.go create mode 100644 utils/safe_api/client/messages/v1_safes_messages_create_responses.go create mode 100644 utils/safe_api/client/messages/v1_safes_messages_list_parameters.go create mode 100644 utils/safe_api/client/messages/v1_safes_messages_list_responses.go create mode 100644 utils/safe_api/client/modules/modules_client.go create mode 100644 utils/safe_api/client/modules/v1_modules_safes_list_parameters.go create mode 100644 utils/safe_api/client/modules/v1_modules_safes_list_responses.go create mode 100644 utils/safe_api/client/notifications/notifications_client.go create mode 100644 utils/safe_api/client/notifications/v1_notifications_devices_create_parameters.go create mode 100644 utils/safe_api/client/notifications/v1_notifications_devices_create_responses.go create mode 100644 utils/safe_api/client/notifications/v1_notifications_devices_delete_parameters.go create mode 100644 utils/safe_api/client/notifications/v1_notifications_devices_delete_responses.go create mode 100644 utils/safe_api/client/notifications/v1_notifications_devices_safes_delete_parameters.go create mode 100644 utils/safe_api/client/notifications/v1_notifications_devices_safes_delete_responses.go create mode 100644 utils/safe_api/client/nr4337/nr4337_client.go create mode 100644 utils/safe_api/client/nr4337/v1_safe_operations_read_parameters.go create mode 100644 utils/safe_api/client/nr4337/v1_safe_operations_read_responses.go create mode 100644 utils/safe_api/client/nr4337/v1_safes_safe_operations_create_parameters.go create mode 100644 utils/safe_api/client/nr4337/v1_safes_safe_operations_create_responses.go create mode 100644 utils/safe_api/client/nr4337/v1_safes_safe_operations_list_parameters.go create mode 100644 utils/safe_api/client/nr4337/v1_safes_safe_operations_list_responses.go create mode 100644 utils/safe_api/client/nr4337/v1_safes_user_operations_list_parameters.go create mode 100644 utils/safe_api/client/nr4337/v1_safes_user_operations_list_responses.go create mode 100644 utils/safe_api/client/nr4337/v1_user_operations_read_parameters.go create mode 100644 utils/safe_api/client/nr4337/v1_user_operations_read_responses.go create mode 100644 utils/safe_api/client/owners/owners_client.go create mode 100644 utils/safe_api/client/owners/v1_owners_safes_list_parameters.go create mode 100644 utils/safe_api/client/owners/v1_owners_safes_list_responses.go create mode 100644 utils/safe_api/client/safe_transaction_service_api_client.go create mode 100644 utils/safe_api/client/safes/safes_client.go create mode 100644 utils/safe_api/client/safes/v1_safes_balances_list_parameters.go create mode 100644 utils/safe_api/client/safes/v1_safes_balances_list_responses.go create mode 100644 utils/safe_api/client/safes/v1_safes_creation_list_parameters.go create mode 100644 utils/safe_api/client/safes/v1_safes_creation_list_responses.go create mode 100644 utils/safe_api/client/safes/v1_safes_delegates_delete_parameters.go create mode 100644 utils/safe_api/client/safes/v1_safes_delegates_delete_responses.go create mode 100644 utils/safe_api/client/safes/v1_safes_read_parameters.go create mode 100644 utils/safe_api/client/safes/v1_safes_read_responses.go create mode 100644 utils/safe_api/client/safes/v2_safes_collectibles_list_parameters.go create mode 100644 utils/safe_api/client/safes/v2_safes_collectibles_list_responses.go create mode 100644 utils/safe_api/client/tokens/tokens_client.go create mode 100644 utils/safe_api/client/tokens/v1_tokens_list_parameters.go create mode 100644 utils/safe_api/client/tokens/v1_tokens_list_responses.go create mode 100644 utils/safe_api/client/tokens/v1_tokens_read_parameters.go create mode 100644 utils/safe_api/client/tokens/v1_tokens_read_responses.go create mode 100644 utils/safe_api/client/transactions/transactions_client.go create mode 100644 utils/safe_api/client/transactions/v1_module_transaction_read_parameters.go create mode 100644 utils/safe_api/client/transactions/v1_module_transaction_read_responses.go create mode 100644 utils/safe_api/client/transactions/v1_multisig_transactions_confirmations_create_parameters.go create mode 100644 utils/safe_api/client/transactions/v1_multisig_transactions_confirmations_create_responses.go create mode 100644 utils/safe_api/client/transactions/v1_multisig_transactions_confirmations_list_parameters.go create mode 100644 utils/safe_api/client/transactions/v1_multisig_transactions_confirmations_list_responses.go create mode 100644 utils/safe_api/client/transactions/v1_multisig_transactions_delete_parameters.go create mode 100644 utils/safe_api/client/transactions/v1_multisig_transactions_delete_responses.go create mode 100644 utils/safe_api/client/transactions/v1_multisig_transactions_read_parameters.go create mode 100644 utils/safe_api/client/transactions/v1_multisig_transactions_read_responses.go create mode 100644 utils/safe_api/client/transactions/v1_safes_all_transactions_list_parameters.go create mode 100644 utils/safe_api/client/transactions/v1_safes_all_transactions_list_responses.go create mode 100644 utils/safe_api/client/transactions/v1_safes_incoming_transfers_list_parameters.go create mode 100644 utils/safe_api/client/transactions/v1_safes_incoming_transfers_list_responses.go create mode 100644 utils/safe_api/client/transactions/v1_safes_module_transactions_list_parameters.go create mode 100644 utils/safe_api/client/transactions/v1_safes_module_transactions_list_responses.go create mode 100644 utils/safe_api/client/transactions/v1_safes_multisig_transactions_create_parameters.go create mode 100644 utils/safe_api/client/transactions/v1_safes_multisig_transactions_create_responses.go create mode 100644 utils/safe_api/client/transactions/v1_safes_multisig_transactions_estimations_create_parameters.go create mode 100644 utils/safe_api/client/transactions/v1_safes_multisig_transactions_estimations_create_responses.go create mode 100644 utils/safe_api/client/transactions/v1_safes_multisig_transactions_list_parameters.go create mode 100644 utils/safe_api/client/transactions/v1_safes_multisig_transactions_list_responses.go create mode 100644 utils/safe_api/client/transactions/v1_safes_transfers_list_parameters.go create mode 100644 utils/safe_api/client/transactions/v1_safes_transfers_list_responses.go create mode 100644 utils/safe_api/client/transfer/transfer_client.go create mode 100644 utils/safe_api/client/transfer/v1_transfer_read_parameters.go create mode 100644 utils/safe_api/client/transfer/v1_transfer_read_responses.go create mode 100644 utils/safe_api/contract.go create mode 100644 utils/safe_api/contract_abi.go create mode 100644 utils/safe_api/data_decoder.go create mode 100644 utils/safe_api/delegate.go create mode 100644 utils/safe_api/delegate_delete.go create mode 100644 utils/safe_api/delegate_delete_serializer_v2.go create mode 100644 utils/safe_api/delegate_serializer_v2.go create mode 100644 utils/safe_api/erc20_info.go create mode 100644 utils/safe_api/ethereum_tx_with_transfers_response.go create mode 100644 utils/safe_api/firebase_device.go create mode 100644 utils/safe_api/firebase_device_serializer_with_owners_response.go create mode 100644 utils/safe_api/indexing_status.go create mode 100644 utils/safe_api/master_copy_response.go create mode 100644 utils/safe_api/modules_response.go create mode 100644 utils/safe_api/owner_response.go create mode 100644 utils/safe_api/safe_balance_response.go create mode 100644 utils/safe_api/safe_collectible_response.go create mode 100644 utils/safe_api/safe_creation_info_response.go create mode 100644 utils/safe_api/safe_delegate_delete.go create mode 100644 utils/safe_api/safe_delegate_response.go create mode 100644 utils/safe_api/safe_deployment.go create mode 100644 utils/safe_api/safe_deployment_contract.go create mode 100644 utils/safe_api/safe_info_response.go create mode 100644 utils/safe_api/safe_message.go create mode 100644 utils/safe_api/safe_message_response.go create mode 100644 utils/safe_api/safe_message_signature.go create mode 100644 utils/safe_api/safe_module_transaction_response.go create mode 100644 utils/safe_api/safe_module_transaction_with_transfers_response.go create mode 100644 utils/safe_api/safe_multisig_confirmation.go create mode 100644 utils/safe_api/safe_multisig_confirmation_response.go create mode 100644 utils/safe_api/safe_multisig_transaction.go create mode 100644 utils/safe_api/safe_multisig_transaction_delete.go create mode 100644 utils/safe_api/safe_multisig_transaction_estimate.go create mode 100644 utils/safe_api/safe_multisig_transaction_estimate_response.go create mode 100644 utils/safe_api/safe_multisig_transaction_response.go create mode 100644 utils/safe_api/safe_multisig_transaction_with_transfers_response.go create mode 100644 utils/safe_api/safe_operation.go create mode 100644 utils/safe_api/safe_operation_response.go create mode 100644 utils/safe_api/safe_operation_with_user_operation_response.go create mode 100644 utils/safe_api/token_info_response.go create mode 100644 utils/safe_api/transfer_with_token_info_response.go create mode 100644 utils/safe_api/user_operation_response.go create mode 100644 utils/safe_api/user_operation_with_safe_operation_response.go create mode 100644 utils/token_price/binance.go create mode 100644 utils/token_price/bitget.go create mode 100644 utils/token_price/bybit.go create mode 100644 utils/token_price/gate.go create mode 100644 utils/token_price/init.go create mode 100644 utils/token_price/mexc.go create mode 100644 utils/token_price/okx.go create mode 100644 utils/util.go create mode 100644 utils/util_test.go create mode 100644 utils/wallet_monitor/monitor.go create mode 100644 utils/wallets/init.go create mode 100644 utils/wallets/private_key.go create mode 100644 utils/wallets/safe/init.go create mode 100644 utils/wallets/safe/safe.go create mode 100644 utils/wallets/safe/safe_abi/safe.go create mode 100644 utils/wallets/safe/utils.go create mode 100644 utils/wallets/wallets.go diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml new file mode 100644 index 0000000..a0f1afb --- /dev/null +++ b/.github/workflows/release.yaml @@ -0,0 +1,90 @@ +name: Release +on: + release: + types: [created] + +jobs: + build-and-deploy-docker: + name: Build and Deploy + permissions: + contents: read + packages: write + attestations: write + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Log in to Docker Hub + uses: docker/login-action@v2 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - uses: olegtarasov/get-tag@v2.1 + id: tag-name + + - name: Get Git Info + id: git_info + run: | + last_commit_time=$(git log -1 --format=%cd --date=iso) + echo "last_commit_time=$last_commit_time" >> $GITHUB_ENV + echo "Last commit time is $last_commit_time" + + last_commit_message=$(git log -1 --format=%B) + echo "last_commit_message=$last_commit_message" >> $GITHUB_ENV + echo "Last commit message is $last_commit_message" + + - name: Build and push Docker images + uses: docker/build-push-action@v5 + with: + context: . + push: true + build-args: | + VERSION=${{ env.GIT_TAG_NAME }} + COMMIT_TIME=${{ env.last_commit_time }} + COMMIT_MESSAGE="${{ env.last_commit_message }}" + labels: | + org.opencontainers.image.version=${{ env.GIT_TAG_NAME }} + org.opencontainers.image.created=${{ env.last_commit_time }} + org.opencontainers.image.revision="${{ env.last_commit_message }}" + tags: | + ghcr.io/${{ github.repository }}:latest + ghcr.io/${{ github.repository }}:${{ env.GIT_TAG_NAME }} + + + releases-matrix: + name: Release Go Binary + runs-on: ubuntu-latest + strategy: + matrix: + goos: [linux, windows, darwin] + goarch: [amd64, arm64] + exclude: + - goarch: "arm64" + goos: windows + steps: + - uses: actions/checkout@v3 + - name: Get Git Info + id: git_info + run: | + last_commit_time=$(git log -1 --format=%cd --date=iso) + echo "last_commit_time=$last_commit_time" >> $GITHUB_ENV + echo "Last commit time is $last_commit_time" + + last_commit_message=$(git log -1 --format=%B) + echo "last_commit_message=$last_commit_message" >> $GITHUB_ENV + echo "Last commit message is $last_commit_message" + + - uses: wangyoucao577/go-release-action@v1 + env: + RELEASE_NAME: ${{ env.GIT_TAG_NAME }} + with: + github_token: ${{ secrets.TOKEN }} + goos: ${{ matrix.goos }} + goarch: ${{ matrix.goarch }} + goversion: "https://dl.google.com/go/go1.22.0.linux-amd64.tar.gz" + project_path: "./cmd" + executable_compression: upx + sha256sum: true + ldflags: "-X 'main.version=${{ env.GIT_TAG_NAME }}' -X 'main.commitMessage=${{env.last_commit_message}}' -X 'main.commitTime=${{env.last_commit_time}}' -s -w -extldflags '-static'" + binary_name: "omni-balance" diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml new file mode 100644 index 0000000..951ea8b --- /dev/null +++ b/.github/workflows/test.yaml @@ -0,0 +1,45 @@ +name: Release +on: + push: + branches: ["*"] + +jobs: + lint: + name: Lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Setup Golang with cache + uses: magnetikonline/action-golang-cache@v4 + with: + go-version-file: go.mod + - name: golangci-lint + uses: golangci/golangci-lint-action@v3 + with: + args: --timeout=10m + gitleaks: + name: gitleaks + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: init gitleaks + run: | + wget https://github.com/gitleaks/gitleaks/releases/download/v8.18.0/gitleaks_8.18.0_linux_x64.tar.gz + tar -zxvf gitleaks_8.18.0_linux_x64.tar.gz -C /tmp/ + sudo mv /tmp/gitleaks /usr/local/bin/ + - name: gitleaks + run: | + gitleaks detect -v --redact --no-git -i ./.gitleaksignore + test: + name: Test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Setup Golang with cache + uses: magnetikonline/action-golang-cache@v4 + with: + go-version-file: go.mod + + - name: Test + run: go test -v ./... diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..00ca469 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.idea +.vscode +local +.run +./config.yaml diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..a54b02c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,25 @@ +FROM golang:1.22.3-alpine as builder +WORKDIR /app + +COPY go.mod go.sum ./ +RUN go mod download + +ARG VERSION +ARG COMMIT_MESSAGE +ARG COMMIT_TIME + +COPY . . +# garble build +RUN CGO_ENABLED=0 go build -a -ldflags \ + "-X 'main.version=$VERSION' \ + -X 'main.commitMessage=$COMMIT_MESSAGE' \ + -X 'main.commitTime=$COMMIT_TIME' -s -w -extldflags '-static'" \ + -o omni-balance ./cmd + +FROM gruebel/upx:latest as upx +COPY --from=builder /app/omni-balance /omni-balance +RUN upx --best --lzma /omni-balance + +FROM alpine:latest as prod +COPY --from=upx /omni-balance /omni-balance +ENTRYPOINT ["/omni-balance"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..5354299 --- /dev/null +++ b/README.md @@ -0,0 +1,269 @@ +# Omni Balance +Omni Balance is an intelligent liquidity management tool designed to achieve seamless interoperability between decentralized exchanges (DEX), centralized exchanges (CEX), and bridging services. It integrates automated cross-chain operations to help users effortlessly balance their liquidity pools while ensuring token balances across different addresses are replenished. + +## Table of Contents +* [Features](#features) +* [Installation](#installation) +* [Usage](#usage) +* [Configuration](#configuration) + +### Features + +* **Multi-address Monitoring**: Real-time monitoring of specific token balances in different addresses, ensuring continuous supervision. +* **Automatic Token Balance Adjustment**: Allows setting custom balance thresholds, and once below the threshold, it automatically adjusts through the best route, including transfers from DEX, CEX, and bridges. +* **Cross-chain Support**: Enables seamless cross-chain transactions, expanding liquidity options. +* **Address Isolation**: Allows separation of monitoring addresses and operational addresses. +* **Supports Most EVM-compatible Chains** (depending on the provider you choose). + +#### Supported Providers + +| name | swap | cross-chain | +|----------------------------------------------------------------------------------|------|-------------| +| [UniSwap](https://uniswap.org/) | ✅ | | +| [Gate.io](https://gate.io) | ✅ | ✅ | +| [Helix Bridge](https://helixbridge.app/) | ✅ | | +| [Darwinia Bridge](https://bridge.darwinia.network/) | ✅ | | +| [OKX web3](https://www.okx.com/zh-hans/web3/build/docs/waas/dex-crosschain-swap) | ✅ | ✅ | + + +### Installation + +#### Download Binary Files from GitHub Releases + +1. Visit the [Releases](https://github.com/darwinia-network/omni-balance/releases) page. +2. Download the latest version of the binary file for your operating system. + +#### Using Docker + +1. Pull the Docker image: `docker pull ghcr.io/darwinia-network/omni-balance:latest` + +#### Building from Source + +1. Ensure Golang 1.22 or later is installed. +2. Clone the repository: `git clone https://github.com/darwinia-network/omni-balance && cd omni-balance` +3. Build the project: `go build ./cmd` + +#### Using Golang Install + +1. Run the command: `go install github.com/darwinia-network/omni-balance@latest` + +### Usage + +#### Supported Commands + +```sh +COMMANDS: + version, v show version + list list supported providers and docs + tasks list supported tasks + example create a example config file + help, h Shows a list of commands or help for one command + +GLOBAL OPTIONS: + + --conf value, -c value (default: "./config.yaml") + config file path + + --placeholder, -p (default: false) + enable placeholder, you can use placeholder to replace private key, Example: Fill '{{privateKey}}' in config.yaml. Run with -p to enable placeholder: SERVER_PORT=:8080 omni-balance -c ./config.yaml -p. Waiting for 'waiting for placeholder...' log, send placeholder + data according to the prompt. + + --port value (default: ":8080") + When the placeholder parameter is set to true, you can specify and set the + listening address of the HTTP server that receives the placeholder. + + MISC + --help, -h show help +``` +#### Configuration +``` +# Debug mode +debug: true +# Chains +chains: + - # Chain id + id: 1 + # Chain name + name: etnereum + # Native token name, if not set, use the 0x0000000000000000000000000000000000000000 + nativetoken: "ETH" + # RPC endpoints + rpc_endpoints: + - https://api.tatum.io/v3/blockchain/node/ethereum-mainnet + - https://ethereum-rpc.publicnode.com + # Tokens + tokens: + - # Token name + name: ETH + # Token contract address + contract_address: "0x0000000000000000000000000000000000000000" + # Token decimals + decimals: 18 + - # Token name + name: RING + # Token contract address + contract_address: 0x9469D013805bFfB7D3DEBe5E7839237e535ec483 + # Token decimals + decimals: 18 + - # Token name + name: USDT + # Token contract address + contract_address: 0xdAC17F958D2ee523a2206206994597C13D831ec7 + # Token decimals + decimals: 6 + - # Chain id + id: 42161 + # Chain name + name: arbitrum + # Native token name, if not set, use the 0x0000000000000000000000000000000000000000 + nativetoken: "ETH" + # RPC endpoints + rpc_endpoints: + - https://1rpc.io/arb + - https://arbitrum.llamarpc.com + # Tokens + tokens: + - # Token name + name: ETH + # Token contract address + contract_address: "0x0000000000000000000000000000000000000000" + # Token decimals + decimals: 18 + - # Token name + name: USDT + # Token contract address + contract_address: 0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9 + # Token decimals + decimals: 6 + - # Token name + name: RING + # Token contract address + contract_address: 0x9e523234D36973f9e38642886197D023C88e307e + # Token decimals + decimals: 18 +# Source token used to buy other tokens +source_token: + - # Token name + name: USDT + # Chain name + chains: + - etnereum + - arbitrum + - # Token name + name: ETH + # Chain name + chains: + - etnereum + - arbitrum +# Liquidity providers +liquidity_providers: + - # Type liquidity provider type + type: CEX + # LiquidityName liquidity provider name + liquidity_name: gate.io + # Config liquidity provider config, depend on the type + config: + key: + secret: + - # Type liquidity provider type + type: DEX + # LiquidityName liquidity provider name + liquidity_name: uniswap + - # Type liquidity provider type + type: Bridge + # LiquidityName liquidity provider name + liquidity_name: helixbridge + - # Type liquidity provider type + type: Bridge + # LiquidityName liquidity provider name + liquidity_name: darwinia-bridge +# Wallets need to rebalance +wallets: + - # Wallet address + address: 0x43Ef13E84D9992d1461a1f90CAc4653658CEA4FD + # If set, when the 'address' balance is insufficient, the operator address will be used to rebalance + operator: "" + # Tokens to be monitored + tokens: + - # Token name + name: ETH + # The number of each rebalance + amount: "1" + # Threshold when the token balance is less than the threshold, the rebalance will be triggered + threshold: "2" + # The chains need to be monitored + chains: + - ethereum + # Wallet private key. If operator is not empty, private_key is the operator's private key + private_key: + - # Wallet address + address: 0x43Ef13E84D9992d1461a1f90CAc4653658CEA4FD + # If set, when the 'address' balance is insufficient, the operator address will be used to rebalance + operator: "0x178D8546C5f78e01133858958355B06EC3406A1A" + # Tokens to be monitored + tokens: + - # Token name + name: RING + # The number of each rebalance + amount: "20000" + # Threshold when the token balance is less than the threshold, the rebalance will be triggered + threshold: "10000" + # The chains need to be monitored + chains: + - ethereum + - arbitrum + # Wallet private key. If operator is not empty, private_key is the operator's private key + private_key: +# Database config, must set one of them +db: + # MYSQL config + MYSQL: + host: "" + port: "" + user: "" + password: "" + database: "" + # POSTGRESQL config + POSTGRESQL: + host: "" + port: "" + user: "" + password: "" + database: "" + # SQLITE config + SQLITE: + path: /data/omni-balance.db +task_interval: + cross_chain: 1m + get_token_price_in_usdt: 1m + monitor_wallet_balance: 1m + rebalance: 1m +``` + +#### Run +##### Using Docker +1. Run the Docker image: +``` +docker run -d --name omni-balance -p 8080:8080 \ + -v :/data \ + --restart=always \ + --name omni-balance \ + omni-balance:latest -c /data/config.yaml -p +``` +2. Check logs: `docker logs omni-balance` + +##### Using command +1. Run the command: `omni-balance -c -p` + +##### Replacing Placeholders (Optional) +**For security reasons, if you do not want to write private keys in plain text in the configuration file, you can replace placeholders via a POST request** + +1. Run the command: +```shell +curl -X POST http://localhost:8080 \ + -d '{"":"xxxx", "":"xxxx"}' +``` +2. Clear history +```shell +history -c +``` diff --git a/cmd/configs.go b/cmd/configs.go new file mode 100644 index 0000000..2564945 --- /dev/null +++ b/cmd/configs.go @@ -0,0 +1,241 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "github.com/ilyakaznacheev/cleanenv" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "github.com/spf13/cast" + yaml_ncoder "github.com/zwgblue/yaml-encoder" + "net/http" + "omni-balance/internal/daemons" + "omni-balance/utils/configs" + "omni-balance/utils/constant" + "os" + "path/filepath" + "strings" + "sync" + "time" +) + +var ( + placeholder sync.Map + setPlaceholderFinished = make(chan struct{}, 1) +) + +func startHttpServer(ctx context.Context, port string) (func(ctx context.Context) error, error) { + server := &http.Server{ + Addr: port, + Handler: http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if !strings.EqualFold(request.Method, http.MethodPost) { + writer.WriteHeader(http.StatusMethodNotAllowed) + return + } + var args = make(map[string]interface{}) + if err := json.NewDecoder(request.Body).Decode(&args); err != nil { + writer.WriteHeader(http.StatusBadRequest) + return + } + for k, v := range args { + placeholder.Store(k, v) + } + + setPlaceholderFinished <- struct{}{} + }), + } + go func() { + if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + logrus.Panic(err) + } + }() + return server.Shutdown, nil +} + +func waitForPlaceholder(ctx context.Context, configPath, port string) (newConfigPath string, err error) { + data, err := os.ReadFile(configPath) + if err != nil { + return "", err + } + shutdown, err := startHttpServer(ctx, port) + if err != nil { + return "", err + } + defer func() { + _ = shutdown(ctx) + }() + <-setPlaceholderFinished + placeholder.Range(func(key, value interface{}) bool { + data = bytes.ReplaceAll(data, []byte(key.(string)), []byte(cast.ToString(value))) + return true + }) + newConfigPath = filepath.Join(os.TempDir(), ".omni-balance.config.yaml") + if err := os.WriteFile(newConfigPath, data, 0644); err != nil { + return "", err + } + return newConfigPath, err +} + +func initConfig(ctx context.Context, enablePlaceholder bool, configPath, serverPort string) (err error) { + if enablePlaceholder { + ports := strings.Split(serverPort, ":") + if len(ports) < 2 { + ports = append([]string{}, "", "8080") + } + logrus.Infof("waiting for placeholder, you can use `curl -X POST -d '{\"\":\"0x1234567890\"}' http://127.0.0.1:%s` to set placeholder", ports[1]) + configPath, err = waitForPlaceholder(context.Background(), configPath, serverPort) + if err != nil { + return err + } + defer func() { + _ = os.RemoveAll(configPath) + }() + } + if err := cleanenv.ReadConfig(configPath, config); err != nil { + return err + } + config.Init() + return config.Check() +} + +func CreateExampleConfig(exampleConfigPath string) error { + var tasks = make(map[string]time.Duration) + for _, v := range daemons.GetTaskConfig() { + tasks[v.Name] = v.DefaultInterval + } + exampleConfig := configs.Config{ + Debug: true, + Chains: []configs.Chain{ + { + Id: 1, + Name: "etnereum", + RpcEndpoints: []string{ + "https://api.tatum.io/v3/blockchain/node/ethereum-mainnet", + "https://ethereum-rpc.publicnode.com", + }, + Tokens: []configs.Token{ + { + Name: "ETH", + ContractAddress: constant.ZeroAddress.Hex(), + Decimals: 18, + }, + { + Name: "RING", + ContractAddress: "0x9469D013805bFfB7D3DEBe5E7839237e535ec483", + Decimals: 18, + }, + { + Name: "USDT", + ContractAddress: "0xdAC17F958D2ee523a2206206994597C13D831ec7", + Decimals: 6, + }, + }, + }, + { + Id: 42161, + Name: "arbitrum", + RpcEndpoints: []string{ + "https://1rpc.io/arb", + "https://arbitrum.llamarpc.com", + }, + Tokens: []configs.Token{ + { + Name: "ETH", + ContractAddress: constant.ZeroAddress.Hex(), + Decimals: 18, + }, + { + Name: "USDT", + ContractAddress: "0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9", + Decimals: 6, + }, + { + Name: "RING", + ContractAddress: "0x9e523234D36973f9e38642886197D023C88e307e", + Decimals: 18, + }, + }, + }, + }, + SourceToken: []configs.SourceToken{ + { + Name: "USDT", + Chains: []string{"etnereum", "arbitrum"}, + }, + { + Name: "ETH", + Chains: []string{"etnereum", "arbitrum"}, + }, + }, + LiquidityProviders: []configs.LiquidityProvider{ + { + Type: configs.CEX, + LiquidityName: "gate.io", + Config: map[string]interface{}{ + "key": "", + "secret": "", + }, + }, + { + Type: configs.DEX, + LiquidityName: "uniswap", + }, + { + Type: configs.Bridge, + LiquidityName: "helixbridge", + }, + { + Type: configs.Bridge, + LiquidityName: "darwinia-bridge", + }, + }, + Wallets: []configs.Wallet{ + { + Address: "0x43Ef13E84D9992d1461a1f90CAc4653658CEA4FD", + Tokens: []configs.WalletToken{ + { + Name: "ETH", + Amount: decimal.RequireFromString("1"), + Threshold: decimal.RequireFromString("3"), + Chains: []string{"ethereum"}, + }, + }, + PrivateKey: "", + }, + { + Address: "0x178D8546C5f78e01133858958355B06EC3406A1A", + Tokens: []configs.WalletToken{ + { + Name: "RING", + Amount: decimal.RequireFromString("100000"), + Threshold: decimal.RequireFromString("2000000"), + Chains: []string{"ethereum", "arbitrum"}, + }, + }, + PrivateKey: "", + }, + }, + TaskInterval: tasks, + Db: configs.DbConfig{ + Type: configs.SQLite, + SQLite: &configs.Sqlite{Path: "./omni-balance.db"}, + MySQL: new(configs.MysqlConfig), + PostgreSQL: new(configs.MysqlConfig), + }, + } + exampleConfigData, err := yaml_ncoder.NewEncoder(exampleConfig, + yaml_ncoder.WithComments(yaml_ncoder.CommentsOnHead), + yaml_ncoder.WithOmitEmpty(false), + ).Encode() + if err != nil { + return errors.Wrap(err, "encode example config") + } + if err := os.WriteFile(exampleConfigPath, exampleConfigData, 0644); err != nil { + return errors.Wrap(err, "write example config") + } + logrus.Infof("Example config file created: %s. In the example configuration file, some values are enclosed in '<>'."+ + " You can add the -p parameter at runtime and follow the prompts to replace these values.", exampleConfigPath) + return nil +} diff --git a/cmd/main.go b/cmd/main.go new file mode 100644 index 0000000..a94a81a --- /dev/null +++ b/cmd/main.go @@ -0,0 +1,181 @@ +package main + +import ( + "context" + "flag" + "fmt" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + "github.com/urfave/cli/v2" + "omni-balance/internal/daemons" + _ "omni-balance/internal/daemons/cross_chain" + _ "omni-balance/internal/daemons/monitor" + _ "omni-balance/internal/daemons/rebalance" + _ "omni-balance/internal/daemons/token_price" + "omni-balance/internal/db" + "omni-balance/internal/models" + "omni-balance/utils" + "omni-balance/utils/configs" + "omni-balance/utils/notice" + "omni-balance/utils/provider" + _ "omni-balance/utils/provider/bridge/darwinia" + _ "omni-balance/utils/provider/bridge/helix" + _ "omni-balance/utils/provider/bridge/okx" + _ "omni-balance/utils/provider/cex/gate" + _ "omni-balance/utils/provider/dex/uniswap" + _ "omni-balance/utils/wallets/safe" + "os" + "os/signal" + "syscall" + "time" +) + +var ( + config = new(configs.Config) + defaultsUsage = flag.Usage + ctx, cancel = context.WithCancel(context.TODO()) + // fill it when building + version string + commitMessage string + commitTime string +) + +func Usage(_ *cli.Context) error { + defaultsUsage() + fmt.Printf("Supported providers:\n") + for providerType, providerFns := range provider.ListProviders() { + fmt.Printf(" %s:\n", providerType) + for _, fn := range providerFns { + providerObj, err := fn(*config, true) + if err != nil { + logrus.Panicf("init provider error: %v", err) + } + fmt.Printf(" %s:\n", providerObj.Name()) + for _, v := range providerObj.Help() { + fmt.Printf(" %s\n", v) + } + } + } + return nil +} + +func Action(cli *cli.Context) error { + if err := initConfig(ctx, cli.Bool("placeholder"), cli.String("conf"), cli.String("port")); err != nil { + return errors.Wrap(err, "init config") + } + if config.Debug { + logrus.SetReportCaller(true) + logrus.SetLevel(logrus.DebugLevel) + logrus.SetFormatter(&logrus.TextFormatter{ + DisableColors: true, + ForceQuote: true, + DisableLevelTruncation: false, + QuoteEmptyFields: true, + }) + } + + if !config.Debug { + logrus.SetLevel(logrus.InfoLevel) + logrus.SetFormatter(&logrus.JSONFormatter{}) + } + + if err := notice.Init(notice.Type(config.Notice.Type), config.Notice.Config); err != nil { + logrus.Warnf("init notice error: %v", err) + } + + if err := db.InitDb(*config); err != nil { + return errors.Wrap(err, "init db") + } + + if err := db.DB().AutoMigrate( + new(models.Order), + new(models.OrderProcess), + new(models.TokenPrice)); err != nil { + return errors.Wrap(err, "auto migrate db") + } + + if err := daemons.Run(ctx, *config); err != nil { + return errors.Wrap(err, "run daemons") + } + utils.FinishInit() + + quit := make(chan os.Signal, 1) + signal.Notify(quit, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) + <-quit + cancel() + time.Sleep(time.Second * 5) + return nil +} + +func main() { + app := cli.NewApp() + app.Name = "omni-balance" + app.Action = Action + app.Commands = []*cli.Command{ + { + Name: "version", + Usage: "show version", + Aliases: []string{"v"}, + Action: func(c *cli.Context) error { + fmt.Printf("Version: %s\n", version) + fmt.Printf("Commit: %s\n", commitMessage) + fmt.Printf("Build time: %s\n", commitTime) + return nil + }, + }, + { + Name: "list", + Usage: "list supported providers and docs", + Action: Usage, + }, + { + Name: "tasks", + Usage: "list supported tasks", + Action: func(_ *cli.Context) error { + fmt.Println(daemons.Help()) + return nil + }, + }, + { + Name: "example", + Usage: "create a example config file", + Flags: []cli.Flag{ + &cli.StringFlag{ + Name: "output", + Usage: "output file path", + Value: "./config.yaml.example", + Aliases: []string{"o"}, + }, + }, + Action: func(c *cli.Context) error { + if err := CreateExampleConfig(c.String("output")); err != nil { + return errors.Wrap(err, "create example config") + } + return nil + }, + }, + } + app.Flags = []cli.Flag{ + &cli.StringFlag{ + Name: "conf", + Aliases: []string{"c"}, + Usage: "config file path", + Value: "./config.yaml", + }, + &cli.BoolFlag{ + Name: "placeholder", + Usage: fmt.Sprintf("enable placeholder, you can use placeholder to replace private key, Example: Fill '{{privateKey}}' in config.yaml."+ + "Run with -p to enable placeholder, Example: SERVER_PORT=:8080 %s -c ./config.yaml -p"+ + "Waiting for 'waiting for placeholder...' log, send placeholder data according to the prompt.", os.Args[0]), + Aliases: []string{"p"}, + }, + &cli.StringFlag{ + Name: "port", + Usage: "When the placeholder parameter is set to true, you can specify and set the listening address of the HTTP server that receives the placeholder.", + Value: ":8080", + }, + } + if err := app.Run(os.Args); err != nil { + logrus.Error(err) + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..9a3e6d7 --- /dev/null +++ b/go.mod @@ -0,0 +1,147 @@ +module omni-balance + +go 1.22 + +require ( + github.com/antihax/optional v1.0.0 + github.com/ethereum/go-ethereum v1.14.3 + github.com/gateio/gateapi-go/v6 v6.67.0 + github.com/glebarez/sqlite v1.11.0 + github.com/go-openapi/errors v0.22.0 + github.com/go-openapi/runtime v0.28.0 + github.com/go-openapi/strfmt v0.23.0 + github.com/go-openapi/swag v0.23.0 + github.com/go-openapi/validate v0.24.0 + github.com/google/uuid v1.6.0 + github.com/gorilla/websocket v1.5.1 + github.com/ilyakaznacheev/cleanenv v1.5.0 + github.com/jinzhu/copier v0.4.0 + github.com/patrickmn/go-cache v2.1.0+incompatible + github.com/pkg/errors v0.9.1 + github.com/shopspring/decimal v1.4.0 + github.com/sirupsen/logrus v1.9.3 + github.com/spf13/cast v1.6.0 + github.com/stretchr/testify v1.9.0 + github.com/uniswapv3-go/uniswapv3-universal-router-decoder-go v0.3.0 + github.com/urfave/cli/v2 v2.27.2 + github.com/zwgblue/yaml-encoder v0.0.0-20221226083717-a0bdbda0d998 + golang.org/x/exp v0.0.0-20240318143956-a85f2c67cd81 + gorm.io/driver/mysql v1.5.6 + gorm.io/driver/postgres v1.5.7 + gorm.io/gorm v1.25.10 +) + +require ( + filippo.io/edwards25519 v1.1.0 // indirect + github.com/BurntSushi/toml v1.3.2 // indirect + github.com/DataDog/zstd v1.4.5 // indirect + github.com/Microsoft/go-winio v0.6.1 // indirect + github.com/VictoriaMetrics/fastcache v1.12.1 // indirect + github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect + github.com/beorn7/perks v1.0.1 // indirect + github.com/bits-and-blooms/bitset v1.13.0 // indirect + github.com/btcsuite/btcd/btcec/v2 v2.3.3 // indirect + github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/cockroachdb/errors v1.11.1 // indirect + github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect + github.com/cockroachdb/pebble v1.1.0 // indirect + github.com/cockroachdb/redact v1.1.5 // indirect + github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect + github.com/consensys/bavard v0.1.13 // indirect + github.com/consensys/gnark-crypto v0.12.1 // indirect + github.com/cpuguy83/go-md2man/v2 v2.0.4 // indirect + github.com/crate-crypto/go-ipa v0.0.0-20231025140028-3c0104f4b233 // indirect + github.com/crate-crypto/go-kzg-4844 v1.0.0 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/deckarep/golang-set/v2 v2.6.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/ethereum/c-kzg-4844 v1.0.2 // indirect + github.com/fjl/memsize v0.0.2 // indirect + github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff // indirect + github.com/gballet/go-verkle v0.1.1-0.20231031103413-a67434b50f46 // indirect + github.com/getsentry/sentry-go v0.18.0 // indirect + github.com/glebarez/go-sqlite v1.22.0 // indirect + github.com/go-logr/logr v1.4.1 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-ole/go-ole v1.3.0 // indirect + github.com/go-openapi/analysis v0.23.0 // indirect + github.com/go-openapi/jsonpointer v0.21.0 // indirect + github.com/go-openapi/jsonreference v0.21.0 // indirect + github.com/go-openapi/loads v0.22.0 // indirect + github.com/go-openapi/spec v0.21.0 // indirect + github.com/go-sql-driver/mysql v1.8.1 // indirect + github.com/gofrs/flock v0.8.1 // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/golang-jwt/jwt/v4 v4.5.0 // indirect + github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb // indirect + github.com/google/pprof v0.0.0-20240320155624-b11c3daa6f07 // indirect + github.com/hashicorp/go-bexpr v0.1.10 // indirect + github.com/holiman/billy v0.0.0-20240216141850-2abb0c79d3c4 // indirect + github.com/holiman/bloomfilter/v2 v2.0.3 // indirect + github.com/holiman/uint256 v1.2.4 // indirect + github.com/huin/goupnp v1.3.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect + github.com/jackc/pgx/v5 v5.4.3 // indirect + github.com/jackpal/go-nat-pmp v1.0.2 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + github.com/joho/godotenv v1.5.1 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/klauspost/compress v1.17.7 // indirect + github.com/kr/pretty v0.3.1 // indirect + github.com/kr/text v0.2.0 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-runewidth v0.0.15 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/mitchellh/pointerstructure v1.2.0 // indirect + github.com/mmcloughlin/addchain v0.4.0 // indirect + github.com/oklog/ulid v1.3.1 // indirect + github.com/olekukonko/tablewriter v0.0.5 // indirect + github.com/onsi/gomega v1.30.0 // indirect + github.com/opentracing/opentracing-go v1.2.0 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/prometheus/client_golang v1.19.0 // indirect + github.com/prometheus/client_model v0.6.0 // indirect + github.com/prometheus/common v0.51.0 // indirect + github.com/prometheus/procfs v0.13.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/rivo/uniseg v0.4.4 // indirect + github.com/rogpeppe/go-internal v1.11.0 // indirect + github.com/rs/cors v1.7.0 // indirect + github.com/russross/blackfriday/v2 v2.1.0 // indirect + github.com/shirou/gopsutil v3.21.11+incompatible // indirect + github.com/status-im/keycard-go v0.2.0 // indirect + github.com/supranational/blst v0.3.11 // indirect + github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect + github.com/tklauser/go-sysconf v0.3.13 // indirect + github.com/tklauser/numcpus v0.7.0 // indirect + github.com/tyler-smith/go-bip39 v1.1.0 // indirect + github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913 // indirect + github.com/yusufpapurcu/wmi v1.2.4 // indirect + go.mongodb.org/mongo-driver v1.14.0 // indirect + go.opentelemetry.io/otel v1.24.0 // indirect + go.opentelemetry.io/otel/metric v1.24.0 // indirect + go.opentelemetry.io/otel/trace v1.24.0 // indirect + golang.org/x/crypto v0.23.0 // indirect + golang.org/x/mod v0.17.0 // indirect + golang.org/x/net v0.24.0 // indirect + golang.org/x/sync v0.7.0 // indirect + golang.org/x/sys v0.20.0 // indirect + golang.org/x/text v0.15.0 // indirect + golang.org/x/time v0.5.0 // indirect + golang.org/x/tools v0.20.0 // indirect + google.golang.org/protobuf v1.33.0 // indirect + gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + modernc.org/libc v1.37.6 // indirect + modernc.org/mathutil v1.6.0 // indirect + modernc.org/memory v1.7.2 // indirect + modernc.org/sqlite v1.28.0 // indirect + olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3 // indirect + rsc.io/tmplfunc v0.0.3 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..4a26c77 --- /dev/null +++ b/go.sum @@ -0,0 +1,443 @@ +filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= +filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= +github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= +github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8= +github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= +github.com/DataDog/zstd v1.4.5 h1:EndNeuB0l9syBZhut0wns3gV1hL8zX8LIu6ZiVHWLIQ= +github.com/DataDog/zstd v1.4.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= +github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= +github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= +github.com/VictoriaMetrics/fastcache v1.12.1 h1:i0mICQuojGDL3KblA7wUNlY5lOK6a4bwt3uRKnkZU40= +github.com/VictoriaMetrics/fastcache v1.12.1/go.mod h1:tX04vaqcNoQeGLD+ra5pU5sWkuxnzWhEzLwhP9w653o= +github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= +github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= +github.com/antihax/optional v1.0.0 h1:xK2lYat7ZLaVVcIuj82J8kIro4V6kDe0AUDFboUCwcg= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= +github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= +github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bits-and-blooms/bitset v1.13.0 h1:bAQ9OPNFYbGHV6Nez0tmNI0RiEu7/hxlYJRUA0wFAVE= +github.com/bits-and-blooms/bitset v1.13.0/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8= +github.com/btcsuite/btcd/btcec/v2 v2.3.3 h1:6+iXlDKE8RMtKsvK0gshlXIuPbyWM/h84Ensb7o3sC0= +github.com/btcsuite/btcd/btcec/v2 v2.3.3/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04= +github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 h1:q0rUy8C/TYNBQS1+CGKw68tLOFYSNEs0TFnxxnS9+4U= +github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc= +github.com/cespare/cp v0.1.0 h1:SE+dxFebS7Iik5LK0tsi1k9ZCxEaFX4AjQmoyA+1dJk= +github.com/cespare/cp v0.1.0/go.mod h1:SOGHArjBr4JWaSDEVpWpo/hNg6RoKrls6Oh40hiwW+s= +github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= +github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/cockroachdb/datadriven v1.0.3-0.20230413201302-be42291fc80f h1:otljaYPt5hWxV3MUfO5dFPFiOXg9CyG5/kCfayTqsJ4= +github.com/cockroachdb/datadriven v1.0.3-0.20230413201302-be42291fc80f/go.mod h1:a9RdTaap04u637JoCzcUoIcDmvwSUtcUFtT/C3kJlTU= +github.com/cockroachdb/errors v1.11.1 h1:xSEW75zKaKCWzR3OfxXUxgrk/NtT4G1MiOv5lWZazG8= +github.com/cockroachdb/errors v1.11.1/go.mod h1:8MUxA3Gi6b25tYlFEBGLf+D8aISL+M4MIpiWMSNRfxw= +github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= +github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= +github.com/cockroachdb/pebble v1.1.0 h1:pcFh8CdCIt2kmEpK0OIatq67Ln9uGDYY3d5XnE0LJG4= +github.com/cockroachdb/pebble v1.1.0/go.mod h1:sEHm5NOXxyiAoKWhoFxT8xMgd/f3RA6qUqQ1BXKrh2E= +github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwPJ30= +github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= +github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= +github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ= +github.com/consensys/bavard v0.1.13 h1:oLhMLOFGTLdlda/kma4VOJazblc7IM5y5QPd2A/YjhQ= +github.com/consensys/bavard v0.1.13/go.mod h1:9ItSMtA/dXMAiL7BG6bqW2m3NdSEObYWoH223nGHukI= +github.com/consensys/gnark-crypto v0.12.1 h1:lHH39WuuFgVHONRl3J0LRBtuYdQTumFSDtJF7HpyG8M= +github.com/consensys/gnark-crypto v0.12.1/go.mod h1:v2Gy7L/4ZRosZ7Ivs+9SfUDr0f5UlG+EM5t7MPHiLuY= +github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4= +github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/crate-crypto/go-ipa v0.0.0-20231025140028-3c0104f4b233 h1:d28BXYi+wUpz1KBmiF9bWrjEMacUEREV6MBi2ODnrfQ= +github.com/crate-crypto/go-ipa v0.0.0-20231025140028-3c0104f4b233/go.mod h1:geZJZH3SzKCqnz5VT0q/DyIG/tvu/dZk+VIfXicupJs= +github.com/crate-crypto/go-kzg-4844 v1.0.0 h1:TsSgHwrkTKecKJ4kadtHi4b3xHW5dCFUDFnUp1TsawI= +github.com/crate-crypto/go-kzg-4844 v1.0.0/go.mod h1:1kMhvPgI0Ky3yIa+9lFySEBUBXkYxeOi8ZF1sYioxhc= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/deckarep/golang-set/v2 v2.6.0 h1:XfcQbWM1LlMB8BsJ8N9vW5ehnnPVIw0je80NsVHagjM= +github.com/deckarep/golang-set/v2 v2.6.0/go.mod h1:VAky9rY/yGXJOLEDv3OMci+7wtDpOF4IN+y82NBOac4= +github.com/decred/dcrd/crypto/blake256 v1.0.1 h1:7PltbUIQB7u/FfZ39+DGa/ShuMyJ5ilcvdfma9wOH6Y= +github.com/decred/dcrd/crypto/blake256 v1.0.1/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPcCXqlm2ArzUIkw9czNJo= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0 h1:rpfIENRNNilwHwZeG5+P150SMrnNEcHYvcCuK6dPZSg= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/ethereum/c-kzg-4844 v1.0.2 h1:8tV84BCEiPeOkiVgW9mpYBeBUir2bkCNVqxPwwVeO+s= +github.com/ethereum/c-kzg-4844 v1.0.2/go.mod h1:VewdlzQmpT5QSrVhbBuGoCdFJkpaJlO1aQputP83wc0= +github.com/ethereum/go-ethereum v1.14.3 h1:5zvnAqLtnCZrU9uod1JCvHWJbPMURzYFHfc2eHz4PHA= +github.com/ethereum/go-ethereum v1.14.3/go.mod h1:1STrq471D0BQbCX9He0hUj4bHxX2k6mt5nOQJhDNOJ8= +github.com/fjl/memsize v0.0.2 h1:27txuSD9or+NZlnOWdKUxeBzTAUkWCVh+4Gf2dWFOzA= +github.com/fjl/memsize v0.0.2/go.mod h1:VvhXpOYNQvB+uIk2RvXzuaQtkQJzzIx6lSBe1xv7hi0= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= +github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= +github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/gateio/gateapi-go/v6 v6.67.0 h1:BxN4TkaWFo4D2Lg+gcCEm57GdeyGfIlKzIJi26rhCbs= +github.com/gateio/gateapi-go/v6 v6.67.0/go.mod h1:racCcjrdyOUbRDO5eCUGUiyDPrF/ZmwBj/bupPZTVLY= +github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff h1:tY80oXqGNY4FhTFhk+o9oFHGINQ/+vhlm8HFzi6znCI= +github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= +github.com/gballet/go-verkle v0.1.1-0.20231031103413-a67434b50f46 h1:BAIP2GihuqhwdILrV+7GJel5lyPV3u1+PgzrWLc0TkE= +github.com/gballet/go-verkle v0.1.1-0.20231031103413-a67434b50f46/go.mod h1:QNpY22eby74jVhqH4WhDLDwxc/vqsern6pW+u2kbkpc= +github.com/getsentry/sentry-go v0.18.0 h1:MtBW5H9QgdcJabtZcuJG80BMOwaBpkRDZkxRkNC1sN0= +github.com/getsentry/sentry-go v0.18.0/go.mod h1:Kgon4Mby+FJ7ZWHFUAZgVaIa8sxHtnRJRLTXZr51aKQ= +github.com/glebarez/go-sqlite v1.22.0 h1:uAcMJhaA6r3LHMTFgP0SifzgXg46yJkgxqyuyec+ruQ= +github.com/glebarez/go-sqlite v1.22.0/go.mod h1:PlBIdHe0+aUEFn+r2/uthrWq4FxbzugL0L8Li6yQJbc= +github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw= +github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ= +github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= +github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ= +github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= +github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= +github.com/go-openapi/analysis v0.23.0 h1:aGday7OWupfMs+LbmLZG4k0MYXIANxcuBTYUC03zFCU= +github.com/go-openapi/analysis v0.23.0/go.mod h1:9mz9ZWaSlV8TvjQHLl2mUW2PbZtemkE8yA5v22ohupo= +github.com/go-openapi/errors v0.22.0 h1:c4xY/OLxUBSTiepAg3j/MHuAv5mJhnf53LLMWFB+u/w= +github.com/go-openapi/errors v0.22.0/go.mod h1:J3DmZScxCDufmIMsdOuDHxJbdOGC0xtUynjIx092vXE= +github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ= +github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY= +github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ= +github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4= +github.com/go-openapi/loads v0.22.0 h1:ECPGd4jX1U6NApCGG1We+uEozOAvXvJSF4nnwHZ8Aco= +github.com/go-openapi/loads v0.22.0/go.mod h1:yLsaTCS92mnSAZX5WWoxszLj0u+Ojl+Zs5Stn1oF+rs= +github.com/go-openapi/runtime v0.28.0 h1:gpPPmWSNGo214l6n8hzdXYhPuJcGtziTOgUpvsFWGIQ= +github.com/go-openapi/runtime v0.28.0/go.mod h1:QN7OzcS+XuYmkQLw05akXk0jRH/eZ3kb18+1KwW9gyc= +github.com/go-openapi/spec v0.21.0 h1:LTVzPc3p/RzRnkQqLRndbAzjY0d0BCL72A6j3CdL9ZY= +github.com/go-openapi/spec v0.21.0/go.mod h1:78u6VdPw81XU44qEWGhtr982gJ5BWg2c0I5XwVMotYk= +github.com/go-openapi/strfmt v0.23.0 h1:nlUS6BCqcnAk0pyhi9Y+kdDVZdZMHfEKQiS4HaMgO/c= +github.com/go-openapi/strfmt v0.23.0/go.mod h1:NrtIpfKtWIygRkKVsxh7XQMDQW5HKQl6S5ik2elW+K4= +github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE= +github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= +github.com/go-openapi/validate v0.24.0 h1:LdfDKwNbpB6Vn40xhTdNZAnfLECL81w+VX3BumrGD58= +github.com/go-openapi/validate v0.24.0/go.mod h1:iyeX1sEufmv3nPbBdX3ieNviWnOZaJ1+zquzJEf2BAQ= +github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= +github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= +github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= +github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= +github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw= +github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= +github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb h1:PBC98N2aIaM3XXiurYmW7fx4GZkL8feAMVq7nEjURHk= +github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20240320155624-b11c3daa6f07 h1:57oOH2Mu5Nw16KnZAVLdlUjmPH/TSYCKTJgG0OVfX0Y= +github.com/google/pprof v0.0.0-20240320155624-b11c3daa6f07/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= +github.com/google/subcommands v1.2.0/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY= +github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY= +github.com/hashicorp/go-bexpr v0.1.10 h1:9kuI5PFotCboP3dkDYFr/wi0gg0QVbSNz5oFRpxn4uE= +github.com/hashicorp/go-bexpr v0.1.10/go.mod h1:oxlubA2vC/gFVfX1A6JGp7ls7uCDlfJn732ehYYg+g0= +github.com/holiman/billy v0.0.0-20240216141850-2abb0c79d3c4 h1:X4egAf/gcS1zATw6wn4Ej8vjuVGxeHdan+bRb2ebyv4= +github.com/holiman/billy v0.0.0-20240216141850-2abb0c79d3c4/go.mod h1:5GuXa7vkL8u9FkFuWdVvfR5ix8hRB7DbOAaYULamFpc= +github.com/holiman/bloomfilter/v2 v2.0.3 h1:73e0e/V0tCydx14a0SCYS/EWCxgwLZ18CZcZKVu0fao= +github.com/holiman/bloomfilter/v2 v2.0.3/go.mod h1:zpoh+gs7qcpqrHr3dB55AMiJwo0iURXE7ZOP9L9hSkA= +github.com/holiman/uint256 v1.2.4 h1:jUc4Nk8fm9jZabQuqr2JzednajVmBpC+oiTiXZJEApU= +github.com/holiman/uint256 v1.2.4/go.mod h1:EOMSn4q6Nyt9P6efbI3bueV4e1b3dGlUCXeiRV4ng7E= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/huin/goupnp v1.3.0 h1:UvLUlWDNpoUdYzb2TCn+MuTWtcjXKSza2n6CBdQ0xXc= +github.com/huin/goupnp v1.3.0/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8= +github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/ilyakaznacheev/cleanenv v1.5.0 h1:0VNZXggJE2OYdXE87bfSSwGxeiGt9moSR2lOrsHHvr4= +github.com/ilyakaznacheev/cleanenv v1.5.0/go.mod h1:a5aDzaJrLCQZsazHol1w8InnDcOX0OColm64SlIi6gk= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk= +github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.4.3 h1:cxFyXhxlvAifxnkKKdlxv8XqUf59tDlYjnV5YYfsJJY= +github.com/jackc/pgx/v5 v5.4.3/go.mod h1:Ig06C2Vu0t5qXC60W8sqIthScaEnFvojjj9dSljmHRA= +github.com/jackpal/go-nat-pmp v1.0.2 h1:KzKSgb7qkJvOUTqYl9/Hg/me3pWgBmERKrTGD7BdWus= +github.com/jackpal/go-nat-pmp v1.0.2/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc= +github.com/jinzhu/copier v0.4.0 h1:w3ciUoD19shMCRargcpm0cm91ytaBhDvuRpz1ODO/U8= +github.com/jinzhu/copier v0.4.0/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/compress v1.17.7 h1:ehO88t2UGzQK66LMdE8tibEd1ErmzZjNEqWkjLAKQQg= +github.com/klauspost/compress v1.17.7/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/leanovate/gopter v0.2.9 h1:fQjYxZaynp97ozCzfOyOuAGOU4aU/z37zf/tOujFk7c= +github.com/leanovate/gopter v0.2.9/go.mod h1:U2L/78B+KVFIx2VmW6onHJQzXtFb+p5y3y2Sh+Jxxv8= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= +github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/mitchellh/pointerstructure v1.2.0 h1:O+i9nHnXS3l/9Wu7r4NrEdwA2VFTicjUEN1uBnDo34A= +github.com/mitchellh/pointerstructure v1.2.0/go.mod h1:BRAsLI5zgXmw97Lf6s25bs8ohIXc3tViBH44KcwB2g4= +github.com/mmcloughlin/addchain v0.4.0 h1:SobOdjm2xLj1KkXN5/n0xTIWyZA2+s99UCY1iPfkHRY= +github.com/mmcloughlin/addchain v0.4.0/go.mod h1:A86O+tHqZLMNO4w6ZZ4FlVQEadcoqkyU72HC5wJ4RlU= +github.com/mmcloughlin/profile v0.1.1/go.mod h1:IhHD7q1ooxgwTgjxQYkACGA77oFTDdFVejUS1/tS/qU= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= +github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= +github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= +github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= +github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= +github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= +github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= +github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= +github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= +github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro= +github.com/onsi/gomega v1.30.0 h1:hvMK7xYz4D3HapigLTeGdId/NcfQx1VHMJc60ew99+8= +github.com/onsi/gomega v1.30.0/go.mod h1:9sxs+SwGrKI0+PWe4Fxa9tFQQBG5xSsSbMXOI8PPpoQ= +github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= +github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= +github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= +github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v1.19.0 h1:ygXvpU1AoN1MhdzckN+PyD9QJOSD4x7kmXYlnfbA6JU= +github.com/prometheus/client_golang v1.19.0/go.mod h1:ZRM9uEAypZakd+q/x7+gmsvXdURP+DABIEIjnmDdp+k= +github.com/prometheus/client_model v0.6.0 h1:k1v3CzpSRUTrKMppY35TLwPvxHqBu0bYgxZzqGIgaos= +github.com/prometheus/client_model v0.6.0/go.mod h1:NTQHnmxFpouOD0DpvP4XujX3CdOAGQPoaGhyTchlyt8= +github.com/prometheus/common v0.51.0 h1:vT5R9NAlW4V6k8Wruk7ikrHaHRsrPbduM/cKTOdQM/k= +github.com/prometheus/common v0.51.0/go.mod h1:wHFBCEVWVmHMUpg7pYcOm2QUR/ocQdYSJVQJKnHc3xQ= +github.com/prometheus/procfs v0.13.0 h1:GqzLlQyfsPbaEHaQkO7tbDlriv/4o5Hudv6OXHGKX7o= +github.com/prometheus/procfs v0.13.0/go.mod h1:cd4PFCR54QLnGKPaKGA6l+cfuNXtht43ZKY6tow0Y1g= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis= +github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= +github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/rs/cors v1.7.0 h1:+88SsELBHx5r+hZ8TCkggzSstaWNbDvThkVK8H6f9ik= +github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= +github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= +github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= +github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k= +github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= +github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= +github.com/status-im/keycard-go v0.2.0 h1:QDLFswOQu1r5jsycloeQh3bVU8n/NatHHaZobtDnDzA= +github.com/status-im/keycard-go v0.2.0/go.mod h1:wlp8ZLbsmrF6g6WjugPAx+IzoLrkdf9+mHxBEeo3Hbg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/supranational/blst v0.3.11 h1:LyU6FolezeWAhvQk0k6O/d49jqgO52MSDDfYgbeoEm4= +github.com/supranational/blst v0.3.11/go.mod h1:jZJtfjgudtNl4en1tzwPIV3KjUnQUvG3/j+w+fVonLw= +github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d h1:vfofYNRScrDdvS342BElfbETmL1Aiz3i2t0zfRj16Hs= +github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d/go.mod h1:RRCYJbIwD5jmqPI9XoAFR0OcDxqUctll6zUj/+B4S48= +github.com/tklauser/go-sysconf v0.3.13 h1:GBUpcahXSpR2xN01jhkNAbTLRk2Yzgggk8IM08lq3r4= +github.com/tklauser/go-sysconf v0.3.13/go.mod h1:zwleP4Q4OehZHGn4CYZDipCgg9usW5IJePewFCGVEa0= +github.com/tklauser/numcpus v0.7.0 h1:yjuerZP127QG9m5Zh/mSO4wqurYil27tHrqwRoRjpr4= +github.com/tklauser/numcpus v0.7.0/go.mod h1:bb6dMVcj8A42tSE7i32fsIUCbQNllK5iDguyOZRUzAY= +github.com/tyler-smith/go-bip39 v1.1.0 h1:5eUemwrMargf3BSLRRCalXT93Ns6pQJIjYQN2nyfOP8= +github.com/tyler-smith/go-bip39 v1.1.0/go.mod h1:gUYDtqQw1JS3ZJ8UWVcGTGqqr6YIN3CWg+kkNaLt55U= +github.com/uniswapv3-go/uniswapv3-universal-router-decoder-go v0.3.0 h1:6cA2BelNLjDtneKxwOhq4Tn7PgCYIC8f6V7Omvm4Zyo= +github.com/uniswapv3-go/uniswapv3-universal-router-decoder-go v0.3.0/go.mod h1:gIRL4wwG3WyKQbcp3v44N9INbNulPZFq1fGpbLOc4v4= +github.com/urfave/cli/v2 v2.27.2 h1:6e0H+AkS+zDckwPCUrZkKX38mRaau4nL2uipkJpbkcI= +github.com/urfave/cli/v2 v2.27.2/go.mod h1:g0+79LmHHATl7DAcHO99smiR/T7uGLw84w8Y42x+4eM= +github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913 h1:+qGGcbkzsfDQNPPe9UDgpxAWQrhbbBXOYJFQDq/dtJw= +github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913/go.mod h1:4aEEwZQutDLsQv2Deui4iYQ6DWTxR14g6m8Wv88+Xqk= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= +github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= +github.com/zwgblue/yaml-encoder v0.0.0-20221226083717-a0bdbda0d998 h1:nfgqxY/ewt2bYcoPiND18j/uKPn4cbiQa9WyD+HIPKM= +github.com/zwgblue/yaml-encoder v0.0.0-20221226083717-a0bdbda0d998/go.mod h1:gDS9Ro20YdMC2SY41VMVcy6PqyVCseFPIX1+symaFww= +go.mongodb.org/mongo-driver v1.14.0 h1:P98w8egYRjYe3XDjxhYJagTokP/H6HzlsnojRgZRd80= +go.mongodb.org/mongo-driver v1.14.0/go.mod h1:Vzb0Mk/pa7e6cWw85R4F/endUC3u0U9jGcNU603k65c= +go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo= +go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo= +go.opentelemetry.io/otel/metric v1.24.0 h1:6EhoGWWK28x1fbpA4tYTOWBkPefTDQnb8WSGXlc88kI= +go.opentelemetry.io/otel/metric v1.24.0/go.mod h1:VYhLe1rFfxuTXLgj4CBiyz+9WYBA8pNGJgDcSFRKBco= +go.opentelemetry.io/otel/sdk v1.24.0 h1:YMPPDNymmQN3ZgczicBY3B6sf9n62Dlj9pWD3ucgoDw= +go.opentelemetry.io/otel/sdk v1.24.0/go.mod h1:KVrIYw6tEubO9E96HQpcmpTKDVn9gdv35HoYiQWGDFg= +go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI= +go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= +golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= +golang.org/x/exp v0.0.0-20240318143956-a85f2c67cd81 h1:6R2FC06FonbXQ8pK11/PDFY6N6LWlf9KlzibaCapmqc= +golang.org/x/exp v0.0.0-20240318143956-a85f2c67cd81/go.mod h1:CQ1k9gNrJ50XIzaKCRR2hssIjF07kZFEiieALBM/ARQ= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= +golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= +golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= +golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= +golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.20.0 h1:hz/CVckiOxybQvFw6h7b/q80NTr9IUQb4s1IIzW7KNY= +golang.org/x/tools v0.20.0/go.mod h1:WvitBU7JJf6A4jOdg4S1tviW9bhUxkgeCui/0JHctQg= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= +google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8= +gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/driver/mysql v1.5.6 h1:Ld4mkIickM+EliaQZQx3uOJDJHtrd70MxAUqWqlx3Y8= +gorm.io/driver/mysql v1.5.6/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM= +gorm.io/driver/postgres v1.5.7 h1:8ptbNJTDbEmhdr62uReG5BGkdQyeasu/FZHxI0IMGnM= +gorm.io/driver/postgres v1.5.7/go.mod h1:3e019WlBaYI5o5LIdNV+LyxCMNtLOQETBXL2h4chKpA= +gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= +gorm.io/gorm v1.25.10 h1:dQpO+33KalOA+aFYGlK+EfxcI5MbO7EP2yYygwh9h+s= +gorm.io/gorm v1.25.10/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= +modernc.org/libc v1.37.6 h1:orZH3c5wmhIQFTXF+Nt+eeauyd+ZIt2BX6ARe+kD+aw= +modernc.org/libc v1.37.6/go.mod h1:YAXkAZ8ktnkCKaN9sw/UDeUVkGYJ/YquGO4FTi5nmHE= +modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= +modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo= +modernc.org/memory v1.7.2 h1:Klh90S215mmH8c9gO98QxQFsY+W451E8AnzjoE2ee1E= +modernc.org/memory v1.7.2/go.mod h1:NO4NVCQy0N7ln+T9ngWqOQfi7ley4vpwvARR+Hjw95E= +modernc.org/sqlite v1.28.0 h1:Zx+LyDDmXczNnEQdvPuEfcFVA2ZPyaD7UCZDjef3BHQ= +modernc.org/sqlite v1.28.0/go.mod h1:Qxpazz0zH8Z1xCFyi5GSL3FzbtZ3fvbjmywNogldEW0= +olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3 h1:slmdOY3vp8a7KQbHkL+FLbvbkgMqmXojpFUO/jENuqQ= +olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3/go.mod h1:oVgVk4OWVDi43qWBEyGhXgYxt7+ED4iYNpTngSLX2Iw= +rsc.io/tmplfunc v0.0.3 h1:53XFQh69AfOa8Tw0Jm7t+GV7KZhOi6jzsCzTtKbMvzU= +rsc.io/tmplfunc v0.0.3/go.mod h1:AG3sTPzElb1Io3Yg4voV9AGZJuleGAwaVRxL9M49PhA= diff --git a/internal/daemons/cross_chain/cross_chain.go b/internal/daemons/cross_chain/cross_chain.go new file mode 100644 index 0000000..8d4db3c --- /dev/null +++ b/internal/daemons/cross_chain/cross_chain.go @@ -0,0 +1,139 @@ +package cross_chain + +import ( + "context" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + "omni-balance/internal/daemons" + "omni-balance/internal/db" + "omni-balance/internal/models" + "omni-balance/utils/configs" + "omni-balance/utils/provider" + "sync" + "time" +) + +func init() { + daemons.RegisterIntervalTask(daemons.Task{ + Name: "cross_chain", + TaskFunc: Run, + DefaultInterval: time.Second * 3, + Description: "Responsible for cross-chaining unfinished tokens from the Rebalance task to the target chain.", + }) +} + +func Run(ctx context.Context, conf configs.Config) error { + orders, err := retrieveOrders() + if err != nil { + return err + } + if len(orders) == 0 { + return nil + } + return processOrders(ctx, conf, orders) +} + +func retrieveOrders() ([]*models.Order, error) { + var orders []*models.Order + return orders, db.DB().Where("status = ? AND current_chain_name != target_chain_name", + models.OrderStatusWaitCrossChain).Find(&orders).Error +} + +func processOrders(ctx context.Context, conf configs.Config, orders []*models.Order) error { + var w sync.WaitGroup + for _, order := range orders { + w.Add(1) + go func(order *models.Order) { + defer w.Done() + log := order.GetLogs() + if err := start(ctx, order, conf, log.WithField("order_id", order.ID)); err != nil { + log.Errorf("start cross chain error: %s", err) + } + }(order) + } + w.Wait() + return nil +} + +func start(ctx context.Context, order *models.Order, conf configs.Config, log *logrus.Entry) error { + if order.Lock(db.DB()) { + log.Infof("order #%d locked, unlock time is %s", order.ID, time.Unix(order.LockTime+60*60*1, 0)) + return nil + } + defer order.UnLock(db.DB()) + if order == nil { + return errors.New("order is nil") + } + wallet := conf.GetWallet(order.Wallet) + bridge, err := getBridge(ctx, order, conf) + if err != nil { + return errors.Wrap(err, "get bridge error") + } + orderProcess := models.GetLastOrderProcess(ctx, db.DB(), order.ID) + swapParams := daemons.CreateSwapParams(*order, orderProcess, log, wallet) + result, err := bridge.Swap(ctx, swapParams) + if err != nil { + return errors.Wrap(err, "swap error") + } + update := createUpdateLog(order, result, log) + return db.DB().Model(&models.Order{}).Where("id = ?", order.ID).Updates(update).Error +} + +func createUpdateLog(order *models.Order, result provider.SwapResult, log *logrus.Entry) map[string]interface{} { + update := map[string]interface{}{ + "error": result.Error, + "current_chain_name": result.CurrentChain, + } + switch result.Status { + case provider.TxStatusSuccess: + log.Infof("order #%d token %s cross from %s to %s success", order.ID, order.TokenOutName, + order.CurrentChainName, order.TargetChainName) + update["status"] = models.OrderStatusSuccess + default: + update["status"] = evaluateStatus(result) + log.Infof("order #%d token %s cross from %s to %s status is %s", order.ID, order.TokenOutName, + order.CurrentChainName, order.TargetChainName, result.Status) + } + return update +} + +func evaluateStatus(result provider.SwapResult) models.OrderStatus { + if result.Status == "" { + return models.OrderStatusUnknown + } + return models.OrderStatus(result.Status) +} + +func getBridge(ctx context.Context, order *models.Order, conf configs.Config) (provider.Provider, error) { + var ( + bridges []provider.Provider + log = order.GetLogs() + ) + for _, providerInitFunc := range provider.LiquidityProviderTypeAndConf(configs.Bridge, conf) { + bridge, err := provider.InitializeBridge(providerInitFunc, conf) + if err != nil { + return nil, errors.Wrap(err, "init bridge error") + } + tokenInCosts, err := bridge.GetCost(context.Background(), provider.SwapParams{ + SourceToken: order.TokenInName, + Sender: conf.GetWallet(order.Wallet), + TargetToken: order.TokenOutName, + Receiver: order.Wallet, + TargetChain: order.TargetChainName, + Amount: order.Amount, + }) + if err != nil { + log.Warnf("check bridge error: %v, not use %s bridge", err, bridge.Name()) + continue + } + if len(tokenInCosts) == 0 { + continue + } + log.Debugf("check bridge %s success", bridge.Name()) + bridges = append(bridges, bridge) + } + if len(bridges) == 0 { + return nil, errors.New("no bridge found") + } + return bridges[0], nil +} diff --git a/internal/daemons/init.go b/internal/daemons/init.go new file mode 100644 index 0000000..607ca9c --- /dev/null +++ b/internal/daemons/init.go @@ -0,0 +1,120 @@ +package daemons + +import ( + "context" + "github.com/sirupsen/logrus" + "omni-balance/utils" + "omni-balance/utils/configs" + "strings" + "sync" + "time" +) + +type TaskFunc func(ctx context.Context, conf configs.Config) error + +var ( + tasks = make(map[string]Task) + m sync.Mutex +) + +type Task struct { + Name string + Description string + TaskFunc TaskFunc + DefaultInterval time.Duration + RunOnStart bool +} + +func Help() string { + var result = strings.Builder{} + + result.WriteString("Available tasks:\n") + var names []string + for index := range tasks { + result.WriteString(" Name: ") + result.WriteString(tasks[index].Name) + result.WriteString("\n") + result.WriteString(" Description: ") + result.WriteString(tasks[index].Description) + result.WriteString("\n") + result.WriteString(" Default Run Interval: ") + result.WriteString(tasks[index].DefaultInterval.String()) + names = append(names, tasks[index].Name) + result.WriteString("\n\n") + } + result.WriteString("\n\nYou can override the Run Interval time for these tasks in your configuration. For example:\n") + result.WriteString("task_interval:\n") + times := time.Second * 10 + for _, v := range names { + result.WriteString(" ") + result.WriteString(v) + result.WriteString(": ") + result.WriteString(times.String()) + result.WriteString("\n") + times = times * 55 + } + return result.String() +} + +func GetTaskConfig() []Task { + var result = make([]Task, 0) + for _, v := range tasks { + result = append(result, v) + } + return result +} + +func RegisterIntervalTask(task Task) { + m.Lock() + defer m.Unlock() + tasks[task.Name] = task +} + +func runForever(ctx context.Context, conf configs.Config, task Task) { + defer func() { + if err := recover(); err != nil { + logrus.Errorf("task %s failed, err: %v, will retry after 2s", task.Name, err) + time.Sleep(time.Second * 2) + go runForever(ctx, conf, task) + } + }() + + interval := conf.GetTaskInterval(task.Name, task.DefaultInterval) + var t = time.NewTicker(interval) + defer t.Stop() + for { + select { + case <-ctx.Done(): + logrus.Infof("task %s stopped", task.Name) + return + case <-t.C: + if !utils.IsFinishedInit() { + logrus.Infof("task %s waiting for init finished", task.Name) + continue + } + if err := task.TaskFunc(ctx, conf); err != nil { + logrus.Errorf("task %s failed, err: %v", task.Name, err) + } + t.Reset(interval) + } + } +} + +func Run(ctx context.Context, conf configs.Config) error { + for index := range tasks { + if tasks[index].RunOnStart { + logrus.Infof("task %s run on start, wait for the task finished", tasks[index].Name) + if err := tasks[index].TaskFunc(ctx, conf); err != nil { + logrus.Errorf("task %s failed, err: %v", tasks[index].Name, err) + continue + } + logrus.Infof("task %s run on start finished", tasks[index].Name) + continue + } + } + for index := range tasks { + logrus.Infof("task %s run in background", tasks[index].Name) + go runForever(ctx, conf, tasks[index]) + } + return nil +} diff --git a/internal/daemons/monitor/monitor.go b/internal/daemons/monitor/monitor.go new file mode 100644 index 0000000..ba3767a --- /dev/null +++ b/internal/daemons/monitor/monitor.go @@ -0,0 +1,99 @@ +package monitor + +import ( + "context" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + "omni-balance/internal/daemons" + "omni-balance/internal/db" + "omni-balance/internal/models" + "omni-balance/utils/configs" + "omni-balance/utils/wallet_monitor" + "time" +) + +func init() { + daemons.RegisterIntervalTask(daemons.Task{ + Name: "monitor_wallet_balance", + Description: "Responsible for monitoring the balance of specified tokens in the wallet.", + TaskFunc: Run, + DefaultInterval: time.Minute * 3, + }) +} + +func Run(ctx context.Context, conf configs.Config) error { + existBuyTokens, err := getExistingBuyTokens() + if err != nil { + return errors.Wrap(err, "find buy tokens error") + } + + ignoreTokens := createIgnoreTokens(existBuyTokens) + result, err := wallet_monitor.NewMonitor(conf).Check(ctx, ignoreTokens...) + if err != nil { + return errors.Wrap(err, "check wallet error") + } + + if err := createOrder(result, conf); err != nil { + return errors.Wrap(err, "create buy tokens error") + } + return nil +} + +func getExistingBuyTokens() ([]*models.Order, error) { + var existBuyTokens []*models.Order + err := db.DB().Where("status != ? ", models.OrderStatusSuccess).Find(&existBuyTokens).Error + if err != nil { + return nil, err + } + return existBuyTokens, nil +} + +func createIgnoreTokens(existBuyTokens []*models.Order) []wallet_monitor.IgnoreToken { + var ignoreTokens []wallet_monitor.IgnoreToken + for _, v := range existBuyTokens { + ignoreTokens = append(ignoreTokens, wallet_monitor.IgnoreToken{ + Name: v.TokenOutName, + Chain: v.TargetChainName, + Address: v.Wallet, + }) + } + return ignoreTokens +} + +func createOrder(result []wallet_monitor.Result, conf configs.Config) error { + if len(result) == 0 { + return nil + } + var orders []*models.Order + for _, r := range result { + for _, token := range r.Tokens { + for _, v := range token.Chains { + threshold := conf.GetTokenThreshold(r.Wallet, token.Name, v.ChainName) + if v.TokenBalance.Add(v.Amount).LessThanOrEqual(threshold) { + v.Amount = threshold.Add(v.Amount).Sub(v.TokenBalance) + logrus.WithFields(logrus.Fields{ + "wallet": r.Wallet, + "token": token.Name, + "chain": v.ChainName, + "threshold": threshold, + "token_balance": v.TokenBalance, + }).Infof("The amount was set too small, "+ + "and another rebalance would still be required after this one. "+ + "Therefore, the amount for this rebalance is set to %s.", v.Amount) + } + orders = append(orders, &models.Order{ + Wallet: r.Wallet, + TokenOutName: token.Name, + TargetChainName: v.ChainName, + CurrentBalance: v.TokenBalance, + Amount: v.Amount, + Status: models.OrderStatusWait, + }) + } + } + } + if err := db.DB().CreateInBatches(orders, 100).Error; err != nil { + return err + } + return nil +} diff --git a/internal/daemons/rebalance/rebalance.go b/internal/daemons/rebalance/rebalance.go new file mode 100644 index 0000000..253db59 --- /dev/null +++ b/internal/daemons/rebalance/rebalance.go @@ -0,0 +1,336 @@ +package rebalance + +import ( + "context" + "fmt" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethclient/simulated" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "omni-balance/internal/daemons" + "omni-balance/internal/db" + "omni-balance/internal/models" + "omni-balance/utils" + "omni-balance/utils/chains" + "omni-balance/utils/configs" + "omni-balance/utils/constant" + "omni-balance/utils/error_types" + "omni-balance/utils/notice" + "omni-balance/utils/provider" + "omni-balance/utils/wallets" + "sync" + "time" +) + +func init() { + daemons.RegisterIntervalTask(daemons.Task{ + Name: "rebalance", + Description: "Responsible for injecting specified assets into monitored wallets in the most efficient way when the balance of specified tokens is insufficient.", + TaskFunc: Run, + DefaultInterval: time.Minute * 10, + }) +} + +func Run(ctx context.Context, conf configs.Config) error { + orders, err := listOrders(ctx) + if err != nil { + return errors.Wrap(err, "find orders error") + } + if len(orders) == 0 { + return nil + } + var w sync.WaitGroup + for index := range orders { + w.Add(1) + go func(order *models.Order) { + defer w.Done() + log := order.GetLogs() + utils.SetLogToCtx(ctx, log) + if err := reBalance(ctx, order, conf); err != nil { + log.Errorf("reBalance order #%d error: %s", order.ID, err) + return + } + err = notice.Send(ctx, + fmt.Sprintf("rebalance order #%d success", order.ID), + fmt.Sprintf("rebalance %s %s from %s to %s use %s %s success", + order.TokenInName, order.Amount, order.SourceChainName, order.TargetChainName, + order.ProviderName, order.ProviderType), + logrus.InfoLevel, + ) + if err != nil { + log.Debugf("notice error: %s", err) + } + log.Debugf("reBalance order #%d success", order.ID) + }(orders[index]) + } + w.Wait() + return nil +} + +func transfer(ctx context.Context, order *models.Order, args provider.SwapParams, + conf configs.Config, setWaitTransfer bool, client simulated.Client) (bool, error) { + ctx = context.WithValue(ctx, constant.ChainNameKeyInCtx, order.TargetChainName) + + result, err := provider.Transfer(ctx, conf, args, client) + if errors.Is(err, error_types.ErrNativeTokenInsufficient) || + errors.Is(err, error_types.ErrWalletLocked) || + errors.Is(err, context.Canceled) { + return true, errors.Wrap(err, "transfer error") + } + if err == nil { + return true, createUpdateLog(ctx, order, result, conf, setWaitTransfer, client) + } + if !errors.Is(errors.Unwrap(err), error_types.ErrInsufficientBalance) && + !errors.Is(errors.Unwrap(err), error_types.ErrInsufficientLiquidity) && err != nil { + return true, errors.Wrap(err, "transfer not is insufficient balance") + } + return false, nil +} + +func reBalance(ctx context.Context, order *models.Order, conf configs.Config) error { + log := utils.GetLogFromCtx(ctx) + if order.Lock(db.DB()) { + log.Infof("order #%d locked, unlock time is %s", order.ID, time.Unix(order.LockTime+60*60*1, 0)) + return nil + } + defer order.UnLock(db.DB()) + var ( + orderProcess = models.GetLastOrderProcess(ctx, db.DB(), order.ID) + args = daemons.CreateSwapParams(*order, orderProcess, log, conf.GetWallet(order.Wallet)) + wallet = conf.GetWallet(order.Wallet) + token = conf.GetTokenInfoOnChain(order.TokenOutName, order.TargetChainName) + chain = conf.GetChainConfig(order.TargetChainName) + client, err = chains.NewTryClient(ctx, chain.RpcEndpoints) + ) + + if err != nil { + return errors.Wrap(err, "new evm client error") + } + defer client.Close() + if wallet.IsDifferentAddress() { + ok, err := transfer(ctx, order, args, conf, false, client) + if err != nil && ok { + return errors.Wrap(err, "transfer error") + } + if ok { + return nil + } + log.Debugf("cannot use transfer, try other providers.") + } + + balance, err := wallet.GetExternalBalance(ctx, common.HexToAddress(token.ContractAddress), token.Decimals, client) + if err != nil { + return errors.Wrap(err, "check balance error") + } + + for _, v := range conf.GetWalletConfig(order.Wallet).Tokens { + if !utils.InArray(order.TargetChainName, v.Chains) { + continue + } + if order.TokenOutName != v.Name { + continue + } + if !balance.GreaterThan(balance) { + break + } + log.Infof("%s balance on %s is enough, skip", v.Name, order.TargetChainName) + if err := order.Success(db.DB(), "", nil, balance); err != nil { + return errors.Wrap(err, "update order success error") + } + return nil + } + + providerObj, err := getReBalanceProvider(ctx, *order, conf) + if err != nil { + return errors.Wrap(err, "get reBalance provider error") + } + + if err := order.SaveProvider(db.DB(), providerObj.Type(), providerObj.Name()); err != nil { + return errors.Wrap(err, "save provider error") + } + + log.Infof("start reBalance %s on %s use %s provider", order.TokenOutName, order.TargetChainName, providerObj.Name()) + result, err := providerObj.Swap(ctx, args) + if err != nil { + log.Warnf("reBalance %s on %s error: %s", order.TokenOutName, providerObj.Name(), err.Error()) + } + if err := createUpdateLog(ctx, order, result, conf, true, client); err != nil { + return errors.Wrap(err, "create update log error") + } + + _, err = transfer(ctx, order, args, conf, false, client) + if err != nil { + return errors.Wrap(err, "transfer error") + } + return nil +} + +func listOrders(ctx context.Context) ([]*models.Order, error) { + var orders []*models.Order + err := db.DB().Where("status != ?", models.OrderStatusSuccess).Find(&orders).Error + if err != nil { + return nil, errors.Wrap(err, "find buy tokens error") + } + return orders, nil +} + +func createUpdateLog(ctx context.Context, order *models.Order, result provider.SwapResult, conf configs.Config, + setWaitTransfer bool, client simulated.Client) error { + + wallet := conf.GetWallet(order.Wallet) + walletBalance := getWalletTokenBalance(ctx, wallet, order.TokenOutName, order.TargetChainName, conf, client) + update := result.Marshal() + updateOrder := &models.Order{ + TokenInName: result.TokenInName, + SourceChainName: result.TokenInChainName, + CurrentChainName: result.CurrentChain, + CurrentBalance: walletBalance, + ProviderOrderId: result.OrderId, + Tx: result.Tx, + Order: result.MarshalOrder(), + Error: result.Error, + } + log := utils.GetLogFromCtx(ctx).WithFields(logrus.Fields{ + "order_id": order.ID, + "status": result.Status, + }) + switch result.Status { + case provider.TxStatusSuccess: + updateOrder.Status = models.OrderStatusSuccess + if setWaitTransfer && wallet.IsDifferentAddress() { + updateOrder.Status = models.OrderStatusWaitTransferFromOperator + } + default: + updateOrder.Status = models.OrderStatus(result.Status) + if result.Status == "" { + updateOrder.Status = models.OrderStatusUnknown + } + + } + log.Debugf("order status is %s", update["status"]) + return db.DB().Model(&models.Order{}).Where("id = ?", order.ID).Limit(1).Updates(updateOrder).Error +} + +func getWalletTokenBalance(ctx context.Context, wallet wallets.Wallets, tokenName, chainName string, + conf configs.Config, client simulated.Client) decimal.Decimal { + + chainConfig := conf.GetChainConfig(chainName) + if len(chainConfig.RpcEndpoints) == 0 { + return decimal.Zero + } + token := conf.GetTokenInfoOnChain(tokenName, chainName) + + balance, err := wallet.GetExternalBalance(ctx, common.HexToAddress(token.ContractAddress), token.Decimals, client) + if err != nil { + return decimal.Zero + } + return balance +} + +func getReBalanceProvider(ctx context.Context, order models.Order, conf configs.Config) (provider.Provider, error) { + log := order.GetLogs() + if order.ProviderType != "" && order.ProviderName != "" { + fn, err := provider.GetProvider(order.ProviderType, order.ProviderName) + if err != nil { + return nil, errors.Wrap(err, "get provider error") + } + return fn(conf) + } + type canUseProvider struct { + provider provider.Provider + tokenInCosts provider.TokenInCosts + } + var canUseProviders []canUseProvider + providers := provider.ListProvidersByConfig(conf) + for _, providerFns := range providers { + for _, providerFn := range providerFns { + p, err := provider.InitializeBridge(providerFn, conf) + if err != nil { + log.Debugf("init provider error: %s", err.Error()) + continue + } + log = log.WithFields(logrus.Fields{ + "provider_type": p.Type(), + "provider_name": p.Name(), + }) + tokenInCosts, ok := providerSupportsOrder(ctx, p, order, conf, log) + if !ok || len(tokenInCosts) == 0 { + continue + } + log.Debugf("provider %s can use %s on %s. The tokenInCosts is %+v", + p.Name(), order.TokenOutName, order.TargetChainName, tokenInCosts) + canUseProviders = append(canUseProviders, canUseProvider{ + provider: p, + tokenInCosts: tokenInCosts, + }) + } + } + + if len(canUseProviders) <= 0 { + return nil, errors.New("no provider can use") + } + if len(canUseProviders) == 1 { + log.Debugf("can use %s provider, the tokenIn is %+v", canUseProviders[0].provider.Name(), canUseProviders[0].tokenInCosts) + return canUseProviders[0].provider, nil + } + var ( + minPrice decimal.Decimal + providerObj provider.Provider + ) + for _, canUseProvider := range canUseProviders { + var ( + tokenNames []string + tokenInCostsMap = make(map[string]decimal.Decimal) + ) + for _, tokenIn := range canUseProvider.tokenInCosts { + if tokenIn.TokenName == order.TokenInName { + return canUseProvider.provider, nil + } + tokenInCostsMap[tokenIn.TokenName] = tokenIn.CostAmount + tokenNames = append(tokenNames, tokenIn.TokenName) + + } + tokenName2Price, err := models.FindTokenPrice(db.DB(), tokenNames) + if err != nil { + log.Warnf("find token price error: %s", err.Error()) + continue + } + + for name, v := range tokenName2Price { + log.Debugf("token %s price %s on %s", name, v.String(), canUseProvider.provider.Name()) + price := v.Mul(tokenInCostsMap[name]) + if price.LessThan(minPrice) { + minPrice = price + providerObj = canUseProvider.provider + continue + } + if minPrice.IsZero() { + minPrice = price + providerObj = canUseProvider.provider + } + } + } + if providerObj == nil { + return nil, errors.New("no provider can use") + } + log.Debugf("min price %s, provider %s", minPrice, providerObj.Name()) + return providerObj, nil +} + +func providerSupportsOrder(ctx context.Context, p provider.Provider, order models.Order, conf configs.Config, log *logrus.Entry) (provider.TokenInCosts, bool) { + wallet := conf.GetWallet(order.Wallet) + tokenInCosts, err := p.GetCost(ctx, provider.SwapParams{ + SourceToken: order.TokenInName, + Sender: conf.GetWallet(order.Wallet), + TargetToken: order.TokenOutName, + Receiver: wallet.GetAddress().Hex(), + TargetChain: order.TargetChainName, + Amount: order.Amount, + }) + if err != nil { + log.Debugf("check token %s on %s use %s error: %s", order.TokenOutName, order.TargetChainName, p.Name(), err.Error()) + return nil, false + } + return tokenInCosts, true +} diff --git a/internal/daemons/token_price/token_price.go b/internal/daemons/token_price/token_price.go new file mode 100644 index 0000000..44ee1fa --- /dev/null +++ b/internal/daemons/token_price/token_price.go @@ -0,0 +1,60 @@ +package token_price + +import ( + "context" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "omni-balance/internal/daemons" + "omni-balance/internal/db" + "omni-balance/internal/models" + "omni-balance/utils/configs" + "omni-balance/utils/token_price" + "sync" + "time" +) + +func init() { + daemons.RegisterIntervalTask(daemons.Task{ + Name: "get_token_price_in_usdt", + Description: "Responsible for obtaining the token price, denominated in USDT.", + TaskFunc: Run, + DefaultInterval: time.Minute * 3, + RunOnStart: true, + }) +} + +func Run(ctx context.Context, conf configs.Config) error { + var ( + w sync.WaitGroup + m sync.Mutex + tokenPrice []models.TokenPrice + ) + providers := token_price.ListTokenPriceProviders() + for _, provider := range providers { + w.Add(1) + go func(provider token_price.TokenPrice) { + defer w.Done() + result, err := provider.GetTokenPriceInUSDT(ctx, conf.SourceToken...) + if err != nil { + logrus.Warnf("%s get token price error: %s", provider.Name(), err) + return + } + m.Lock() + defer m.Unlock() + for _, r := range result { + if r.Price.LessThan(decimal.Zero) { + logrus.Warnf("%s get %s token price is less than 0", provider.Name(), r.TokeName) + continue + } + tokenPrice = append(tokenPrice, models.TokenPrice{ + TokenName: r.TokeName, + Price: r.Price, + Source: provider.Name(), + }) + } + + }(provider) + } + w.Wait() + return models.SaveTokenPrice(ctx, db.DB().Begin(), tokenPrice) +} diff --git a/internal/daemons/utils.go b/internal/daemons/utils.go new file mode 100644 index 0000000..94c66d2 --- /dev/null +++ b/internal/daemons/utils.go @@ -0,0 +1,72 @@ +package daemons + +import ( + "github.com/sirupsen/logrus" + "omni-balance/internal/db" + "omni-balance/internal/models" + "omni-balance/utils/configs" + "omni-balance/utils/provider" + "omni-balance/utils/wallets" +) + +func CreateSwapParams(order models.Order, orderProcess models.OrderProcess, log *logrus.Entry, wallet wallets.Wallets) provider.SwapParams { + return provider.SwapParams{ + SourceChain: order.CurrentChainName, + Sender: wallet, + Receiver: wallet.GetAddress().Hex(), + TargetChain: order.TargetChainName, + SourceToken: order.TokenOutName, + TargetToken: order.TokenOutName, + Amount: order.Amount, + LastHistory: createLastHistory(orderProcess), + RecordFn: createRecordFunction(order, log), + } +} + +func createLastHistory(orderProcess models.OrderProcess) provider.SwapHistory { + return provider.SwapHistory{ + Actions: orderProcess.Action, + Status: orderProcess.Status, + CurrentChain: orderProcess.CurrentChainName, + Amount: orderProcess.Amount, + Tx: orderProcess.Tx, + } +} + +func createRecordFunction(order models.Order, log *logrus.Entry) func(s provider.SwapHistory, errs ...error) { + return func(s provider.SwapHistory, errs ...error) { + op := createOrderProcess(order, s) + if len(errs) != 0 && errs[0] != nil { + op.Error = errs[0].Error() + } + if err := db.DB().Create(op).Error; err != nil { + log.Errorf("save %s bridge provider error: %s", order.TokenOutName, err.Error()) + return + } + log.Infof("order #%d token %s cross from %s to %s action %s status is %s", + order.ID, order.TokenOutName, order.CurrentChainName, order.TargetChainName, s.Actions, s.Status) + } +} + +func createOrderProcess(order models.Order, s provider.SwapHistory) *models.OrderProcess { + var ( + providerType = order.ProviderType + providerName = order.ProviderName + ) + if s.ProviderType != "" { + providerType = configs.LiquidityProviderType(s.ProviderType) + } + if s.ProviderName != "" { + providerName = s.ProviderName + } + return &models.OrderProcess{ + OrderId: order.ID, + ProviderType: providerType, + ProviderName: providerName, + Status: s.Status, + Action: s.Actions, + Amount: s.Amount, + CurrentChainName: s.CurrentChain, + Tx: s.Tx, + } +} diff --git a/internal/db/db.go b/internal/db/db.go new file mode 100644 index 0000000..77b0639 --- /dev/null +++ b/internal/db/db.go @@ -0,0 +1,53 @@ +package db + +import ( + "fmt" + "github.com/glebarez/sqlite" + "github.com/pkg/errors" + "gorm.io/driver/mysql" + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" + "omni-balance/utils/configs" +) + +var ( + globalDb *gorm.DB +) + +func InitDb(conf configs.Config) (err error) { + var ( + dialector gorm.Dialector + ) + switch conf.Db.Type { + case configs.MySQL: + // do something + c := conf.Db.MySQL + dialector = mysql.Open(fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", c.User, c.Password, c.Host, c.Port, c.Database)) + case configs.PostgreSQL: + c := conf.Db.PostgreSQL + dialector = postgres.Open(fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s", c.Host, c.User, c.Password, c.Database, c.Port)) + case configs.SQLite: + dialector = sqlite.Open(conf.Db.SQLite.Path) + default: + return errors.New("unsupported db type") + } + db, err := gorm.Open(dialector, &gorm.Config{}) + if err != nil { + return err + } + db.Logger = db.Logger.LogMode(logger.Silent) + sqlDb, err := db.DB() + if err != nil { + return err + } + globalDb = db + return sqlDb.Ping() +} + +func DB() *gorm.DB { + if globalDb == nil { + panic("db is nil") + } + return globalDb +} diff --git a/internal/models/order.go b/internal/models/order.go new file mode 100644 index 0000000..de38dd9 --- /dev/null +++ b/internal/models/order.go @@ -0,0 +1,102 @@ +package models + +import ( + "context" + "encoding/json" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "gorm.io/gorm" + "omni-balance/utils/configs" + "time" +) + +type OrderStatus string + +const ( + OrderStatusWait OrderStatus = "wait" + OrderStatusProcessing OrderStatus = "processing" + OrderStatusSuccess OrderStatus = "success" + OrderStatusFail OrderStatus = "fail" + OrderStatusWaitTransferFromOperator OrderStatus = "wait_transfer_from_operator" + OrderStatusWaitCrossChain OrderStatus = "wait_cross_chain" + OrderStatusUnknown OrderStatus = "unknown" +) + +type Order struct { + gorm.Model + // 唯一索引 + Wallet string `json:"wallet" gorm:"type:varchar(64)"` + TokenInName string `json:"token_in_name"` + TokenOutName string `json:"token_out_name" gorm:"type:varchar(64)"` + SourceChainName string `json:"source_chain_name"` + TargetChainName string `json:"target_chain_name"` + CurrentChainName string `json:"current_chain_name" gorm:"type:varchar(64)"` + CurrentBalance decimal.Decimal `json:"current_balance" gorm:"type:decimal(32,16); default:0"` + Amount decimal.Decimal `json:"amount" gorm:"type:decimal(32,16); default:0"` + IsLock bool `json:"is_lock" gore:"type:boolean; default:false"` + LockTime int64 `json:"lock_time" gorm:"default:0"` + Status OrderStatus `json:"status" gorm:"type:int; default:0;index"` + ProviderType configs.LiquidityProviderType `json:"provider_type" gorm:"type:varchar(64)"` + ProviderName string `json:"provider_name" gorm:"type:varchar(64)"` + ProviderOrderId string `json:"order_id" gorm:"type:varchar(64)"` + Tx string `json:"tx" gorm:"type:varchar(64)"` + Order *json.RawMessage `json:"order" gorm:"type:json;default:null"` + Error string `json:"error" gorm:"type:varchar(255)"` +} + +type OrderProcess struct { + gorm.Model + // Order.ID 一对多关联 + OrderId uint `json:"order_id" gorm:"type:int;index"` + Error string `json:"error"` + ProviderType configs.LiquidityProviderType `json:"type"` + ProviderName string `json:"provider_name"` + CurrentChainName string `json:"current_chain_name"` + Status string `json:"status"` + Action string `json:"action"` + Amount decimal.Decimal `json:"amount"` + // Tx is the transaction hash + Tx string `json:"tx"` +} + +func (o *Order) UnLock(db *gorm.DB) { + db.Model(&Order{}).Where("id = ?", o.ID).Updates(map[string]interface{}{"is_lock": false, "lock_time": 0}) +} + +func (o *Order) Lock(db *gorm.DB) bool { + var order Order + db.Where("id = ?", o.ID).First(&order) + if order.IsLock && time.Unix(order.LockTime, 0).Add(time.Hour).Unix() < time.Now().Unix() { + return true + } + db.Model(&Order{}).Where("id = ?", o.ID).Updates(map[string]interface{}{"is_lock": 1, "lock_time": time.Now().Unix()}) + return false +} + +func (o *Order) SaveProvider(db *gorm.DB, provider configs.LiquidityProviderType, providerName string) error { + return db.Model(&Order{}).Where("id = ?", o.ID).Updates(map[string]interface{}{"provider_type": provider, "provider_name": providerName}).Error +} + +func (o *Order) Success(db *gorm.DB, tx string, order interface{}, balance decimal.Decimal) error { + data, _ := json.Marshal(order) + return db.Model(&Order{}).Where("id = ?", o.ID).Updates(map[string]interface{}{ + "status": OrderStatusSuccess, + "tx": tx, + "current_chain_name": o.TargetChainName, + "order": json.RawMessage(data), + "current_balance": balance, + }).Error +} + +func GetLastOrderProcess(ctx context.Context, db *gorm.DB, orderId uint) OrderProcess { + var result OrderProcess + _ = db.WithContext(ctx).Where("order_id = ?", orderId).Order("id desc").First(&result) + return result +} + +func (o *Order) GetLogs() *logrus.Entry { + data, _ := json.Marshal(o) + var fields logrus.Fields + _ = json.Unmarshal(data, &fields) + return logrus.WithFields(fields) +} diff --git a/internal/models/token_price.go b/internal/models/token_price.go new file mode 100644 index 0000000..bf68b2e --- /dev/null +++ b/internal/models/token_price.go @@ -0,0 +1,84 @@ +package models + +import ( + "context" + "github.com/shopspring/decimal" + "gorm.io/gorm" +) + +type TokenPrices []TokenPrice + +type TokenPrice struct { + gorm.Model + TokenName string `json:"token_name" gorm:"type:varchar(64);uniqueIndex:TokenName_Source_Chain"` + Price decimal.Decimal `json:"price" gorm:"type:decimal(32,16); default:0"` + Source string `json:"source" gorm:"type:varchar(64);uniqueIndex:TokenName_Source_Chain"` + Chain string `json:"chain" gorm:"type:varchar(64);uniqueIndex:TokenName_Source_Chain"` +} + +func (t *TokenPrice) Save(db *gorm.DB) error { + queryDb := db.Model(&TokenPrices{}) + var tp TokenPrice + queryDb = queryDb.Where("token_name = ? and source = ? and chain = ?", t.TokenName, t.Source, t.Chain) + queryDb.First(&tp) + if tp.ID == 0 { + return db.Create(&t).Error + } + return db.Model(&TokenPrices{}).Where("id = ?", tp.ID).Updates(t).Error +} + +func (tokenPrices TokenPrices) AveragePrice() decimal.Decimal { + if len(tokenPrices) == 0 { + return decimal.Zero + } + var total decimal.Decimal + for _, v := range tokenPrices { + total = total.Add(v.Price) + } + return total.Div(decimal.NewFromInt(int64(len(tokenPrices)))) +} + +func (tokenPrices TokenPrices) AveragePriceOnChain(chain string) decimal.Decimal { + if len(tokenPrices) == 0 || chain == "" { + return decimal.Zero + } + var total decimal.Decimal + for _, v := range tokenPrices { + if v.Chain == chain { + total = total.Add(v.Price) + } + } + return total.Div(decimal.NewFromInt(int64(len(tokenPrices)))) +} + +func FindTokenPrice(db *gorm.DB, tokenName []string) (result map[string]decimal.Decimal, err error) { + var ( + tokenPrices []TokenPrice + tokenName2Price = make(map[string]TokenPrices) + ) + err = db.Where("token_name in (?)", tokenName).First(&tokenPrices).Error + if err != nil { + return + } + for index, v := range tokenPrices { + tokenName2Price[v.TokenName] = append(tokenName2Price[v.TokenName], tokenPrices[index]) + } + result = make(map[string]decimal.Decimal) + for _, v := range tokenName { + if len(tokenName2Price[v]) == 0 { + continue + } + result[v] = tokenName2Price[v].AveragePrice() + } + return result, nil +} + +func SaveTokenPrice(_ context.Context, txDb *gorm.DB, price []TokenPrice) error { + for _, v := range price { + if err := v.Save(txDb); err != nil { + txDb.Rollback() + return err + } + } + return txDb.Commit().Error +} diff --git a/utils/chains/client.go b/utils/chains/client.go new file mode 100644 index 0000000..1c115dd --- /dev/null +++ b/utils/chains/client.go @@ -0,0 +1,165 @@ +package chains + +import ( + "context" + "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient" + "github.com/ethereum/go-ethereum/ethclient/simulated" + "math/big" + "sync/atomic" +) + +type Client struct { + index atomic.Int64 + clients []*ethclient.Client + chainId *big.Int +} + +func NewTryClient(ctx context.Context, endpoints []string) (*Client, error) { + t := &Client{} + + for _, v := range endpoints { + client, err := ethclient.DialContext(ctx, v) + if err != nil { + return nil, err + } + t.clients = append(t.clients, client) + } + return t, nil +} + +func (t *Client) Close() { + for _, v := range t.clients { + v.Close() + } +} + +func (t *Client) Clients() simulated.Client { + return t.clients[t.index.Load()%int64(len(t.clients))] +} + +func (t *Client) BlockNumber(ctx context.Context) (uint64, error) { + return t.Clients().BlockNumber(ctx) +} + +func (t *Client) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { + return t.Clients().BlockByHash(ctx, hash) +} + +func (t *Client) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) { + return t.Clients().BlockByNumber(ctx, number) +} + +func (t *Client) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) { + return t.Clients().HeaderByHash(ctx, hash) +} + +func (t *Client) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) { + return t.Clients().HeaderByNumber(ctx, number) +} + +func (t *Client) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) { + return t.Clients().TransactionCount(ctx, blockHash) +} + +func (t *Client) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error) { + return t.Clients().TransactionInBlock(ctx, blockHash, index) +} + +func (t *Client) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) { + return t.Clients().SubscribeNewHead(ctx, ch) +} + +func (t *Client) BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error) { + return t.Clients().BalanceAt(ctx, account, blockNumber) +} + +func (t *Client) StorageAt(ctx context.Context, account common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) { + return t.Clients().StorageAt(ctx, account, key, blockNumber) +} + +func (t *Client) CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error) { + return t.Clients().CodeAt(ctx, account, blockNumber) +} + +func (t *Client) NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (uint64, error) { + return t.Clients().NonceAt(ctx, account, blockNumber) +} + +func (t *Client) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) { + return t.Clients().CallContract(ctx, call, blockNumber) +} + +func (t *Client) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) { + return t.Clients().EstimateGas(ctx, call) +} + +func (t *Client) SuggestGasPrice(ctx context.Context) (*big.Int, error) { + return t.Clients().SuggestGasPrice(ctx) +} + +func (t *Client) SuggestGasTipCap(ctx context.Context) (*big.Int, error) { + return t.Clients().SuggestGasTipCap(ctx) +} + +func (t *Client) FeeHistory(ctx context.Context, blockCount uint64, lastBlock *big.Int, rewardPercentiles []float64) (*ethereum.FeeHistory, error) { + return t.Clients().FeeHistory(ctx, blockCount, lastBlock, rewardPercentiles) +} + +func (t *Client) FilterLogs(ctx context.Context, q ethereum.FilterQuery) ([]types.Log, error) { + return t.Clients().FilterLogs(ctx, q) +} + +func (t *Client) SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) { + return t.Clients().SubscribeFilterLogs(ctx, q, ch) +} + +func (t *Client) PendingBalanceAt(ctx context.Context, account common.Address) (*big.Int, error) { + return t.Clients().PendingBalanceAt(ctx, account) +} + +func (t *Client) PendingStorageAt(ctx context.Context, account common.Address, key common.Hash) ([]byte, error) { + return t.Clients().PendingStorageAt(ctx, account, key) +} + +func (t *Client) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) { + return t.Clients().PendingCodeAt(ctx, account) +} + +func (t *Client) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) { + return t.Clients().PendingNonceAt(ctx, account) +} + +func (t *Client) PendingTransactionCount(ctx context.Context) (uint, error) { + return t.Clients().PendingTransactionCount(ctx) +} + +func (t *Client) PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) { + return t.Clients().PendingCallContract(ctx, call) +} + +func (t *Client) TransactionByHash(ctx context.Context, txHash common.Hash) (tx *types.Transaction, isPending bool, err error) { + return t.Clients().TransactionByHash(ctx, txHash) +} + +func (t *Client) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) { + return t.Clients().TransactionReceipt(ctx, txHash) +} + +func (t *Client) SendTransaction(ctx context.Context, tx *types.Transaction) error { + return t.Clients().SendTransaction(ctx, tx) +} + +func (t *Client) ChainID(ctx context.Context) (*big.Int, error) { + if t.chainId != nil { + return t.chainId, nil + } + chainId, err := t.Clients().ChainID(ctx) + if err != nil { + return nil, err + } + t.chainId = chainId + return chainId, nil +} diff --git a/utils/chains/eip712.go b/utils/chains/eip712.go new file mode 100644 index 0000000..21d3231 --- /dev/null +++ b/utils/chains/eip712.go @@ -0,0 +1,39 @@ +package chains + +import ( + "fmt" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/signer/core/apitypes" + "github.com/pkg/errors" +) + +// SignTypedData - Sign typed data +func SignTypedData(typedData apitypes.TypedData, signFn func(msg []byte) (sig []byte, err error)) (sig []byte, err error) { + hash, err := EncodeForSigning(typedData) + if err != nil { + return nil, errors.Wrap(err, "failed to encode typed data") + } + sig, err = signFn(hash.Bytes()) + if err != nil { + return nil, errors.Wrap(err, "failed to sign typed data") + } + sig[64] += 27 + return +} + +// EncodeForSigning - Encoding the typed data +func EncodeForSigning(typedData apitypes.TypedData) (hash common.Hash, err error) { + domainSeparator, err := typedData.HashStruct("EIP712Domain", typedData.Domain.Map()) + if err != nil { + return hash, errors.Wrap(err, "failed to hash domain") + } + + typedDataHash, err := typedData.HashStruct(typedData.PrimaryType, typedData.Message) + if err != nil { + return hash, errors.Wrap(err, "failed to hash typed data") + } + rawData := []byte(fmt.Sprintf("\x19\x01%s%s", string(domainSeparator), string(typedDataHash))) + hash = common.BytesToHash(crypto.Keccak256(rawData)) + return +} diff --git a/utils/chains/util.go b/utils/chains/util.go new file mode 100644 index 0000000..5eddcd0 --- /dev/null +++ b/utils/chains/util.go @@ -0,0 +1,325 @@ +package chains + +import ( + "context" + "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethclient/simulated" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "github.com/spf13/cast" + "math/big" + "omni-balance/utils" + "omni-balance/utils/constant" + "omni-balance/utils/erc20" + "omni-balance/utils/error_types" + "strings" + "time" +) + +func getDecimals(decimals ...int32) int32 { + var currentDecimals int32 = 18 + if len(decimals) != 0 && decimals[0] != 0 { + currentDecimals = decimals[0] + } + return currentDecimals +} + +func EthToWei(v decimal.Decimal, decimals ...int32) *big.Int { + decimalStr := v.Mul(decimal.New(1, getDecimals(decimals...))).String() + wei, _ := new(big.Int).SetString(decimalStr, 10) + return wei +} + +func WeiToEth(v *big.Int, decimals ...int32) decimal.Decimal { + return decimal.NewFromBigInt(v, 0).Div(decimal.New(1, getDecimals(decimals...))) +} + +// GetTokenBalance retrieves the token balance of a specified wallet address. +// ctx: Context to control the function's execution, including cancellation and timeouts. +// tokenAddress: Contract address of the token; if "0x0000000000000000000000000000000000000000", it indicates querying the native token (e.g., ETH) balance. +// walletAddress: Address of the wallet whose token balance is being queried. +// tokenDecimal: Optional argument specifying the number of decimal places for the token. Required and must not be zero when querying the native token balance. +// Returns the token balance in its smallest unit and an error if any occurs. +func GetTokenBalance(ctx context.Context, client simulated.Client, tokenAddress, walletAddress string, + tokenDecimal ...interface{}) (decimal.Decimal, error) { + + var ( + balance *big.Int + err error + ) + if strings.EqualFold(tokenAddress, constant.ZeroAddress.Hex()) { + if len(tokenDecimal) == 0 && tokenDecimal[0] != 0 { + return decimal.Zero, errors.Errorf("token decimal is required") + } + tokenDecimals := cast.ToInt32(tokenDecimal[0]) + balance, err = client.BalanceAt(ctx, common.HexToAddress(walletAddress), nil) + if err != nil { + return decimal.Zero, errors.Wrap(err, "get balance error") + } + return WeiToEth(balance, tokenDecimals), nil + } + erc20Abi, err := erc20.TokenMetaData.GetAbi() + if err != nil { + return decimal.Zero, errors.Wrap(err, "get erc20 abi error") + } + input, err := erc20Abi.Pack("balanceOf", common.HexToAddress(walletAddress)) + if err != nil { + return decimal.Zero, errors.Wrap(err, "pack erc20 balanceOf error") + } + to := common.HexToAddress(tokenAddress) + result, err := client.CallContract(ctx, ethereum.CallMsg{To: &to, Data: input}, nil) + if err != nil { + return decimal.Zero, errors.Wrap(err, "call erc20 balanceOf error") + } + + balance = new(big.Int).SetBytes(result) + if len(tokenDecimal) == 0 { + input, err := erc20Abi.Pack("decimals") + if err != nil { + return decimal.Zero, errors.Wrap(err, "pack erc20 decimals error") + } + tokenDecimals, err := client.CallContract(ctx, ethereum.CallMsg{To: &to, Data: input}, nil) + if err != nil { + return decimal.Zero, errors.Wrap(err, "call erc20 decimals error") + } + tokenDecimal = append(tokenDecimal, new(big.Int).SetBytes(tokenDecimals).Int64()) + } + return WeiToEth(balance, cast.ToInt32(tokenDecimal[0])), nil +} + +func SignTx(tx *types.Transaction, privateKey string, chainId int64) (*types.Transaction, error) { + key, err := crypto.HexToECDSA(privateKey) + if err != nil { + return nil, errors.Wrap(err, "privateKey") + } + return types.SignTx(tx, types.NewEIP155Signer(big.NewInt(chainId)), key) +} + +func SignMsg(msg []byte, privateKey string) (sig []byte, err error) { + key, err := crypto.HexToECDSA(privateKey) + if err != nil { + return nil, errors.WithStack(err) + } + return crypto.Sign(msg, key) +} + +func WaitForTx(ctx context.Context, client simulated.Client, txHash common.Hash) error { + log := utils.GetLogFromCtx(ctx) + t := time.NewTicker(time.Second) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return errors.New("context cancelled") + case <-t.C: + tx, err := client.TransactionReceipt(ctx, txHash) + if errors.Is(err, context.Canceled) || + errors.Is(err, context.DeadlineExceeded) { + return err + } + if errors.Is(err, ethereum.NotFound) { + log.Debugf("tx not found, txHash: %s, try again later", txHash.Hex()) + continue + } + if err != nil { + log.Debugf("get tx receipt error: %s, try again later", err) + continue + } + if tx.Status == 0 { + return errors.New("tx failed") + } + log.Debugf("tx success, txHash: %s", txHash.Hex()) + return nil + } + } +} + +type TokenApproveParams struct { + ChainId int64 + TokenAddress common.Address + Owner common.Address + SendTransaction func(ctx context.Context, tx *types.LegacyTx, client simulated.Client) (common.Hash, error) + WaitTransaction func(ctx context.Context, txHash common.Hash, client simulated.Client) error + Spender common.Address + AmountWei decimal.Decimal + Client simulated.Client +} + +func TokenApprove(ctx context.Context, args TokenApproveParams) error { + log := utils.GetLogFromCtx(ctx).WithFields(logrus.Fields{ + "job": "approve", + "tokenAddress": args.TokenAddress.Hex(), + "owner": args.Owner.Hex(), + "spender": args.Spender.Hex(), + "amountWei": args.AmountWei.String(), + }) + contract, err := erc20.NewTokenCaller(args.TokenAddress, args.Client) + if err != nil { + return errors.Wrap(err, "erc20 caller") + } + allowanceWei, err := contract.Allowance(nil, args.Owner, args.Spender) + if err != nil { + return errors.Wrap(err, "erc20 allowance") + } + log.Debugf("erc20 allowance: %s", allowanceWei) + if decimal.NewFromBigInt(allowanceWei, 0).GreaterThanOrEqual(args.AmountWei) { + log.Debugf("erc20 allowance is enough, skip approve") + return nil + } + erc20Abi, err := erc20.TokenMetaData.GetAbi() + if err != nil { + return errors.Wrap(err, "get abi") + } + input, err := erc20Abi.Pack("approve", args.Spender, args.AmountWei.BigInt()) + if err != nil { + return errors.Wrap(err, "abi pack") + } + + txHash, err := args.SendTransaction(ctx, &types.LegacyTx{ + To: &args.TokenAddress, + Data: input, + }, args.Client) + if err != nil { + return errors.Wrap(err, "erc20 approve") + } + log.Debugf("erc20 approve txHash: %s", txHash.Hex()) + if args.WaitTransaction != nil { + return args.WaitTransaction(ctx, txHash, args.Client) + } + return WaitForTx(ctx, args.Client, txHash) +} + +func MostNewAbiType(t string, internalType string, components []abi.ArgumentMarshaling) abi.Type { + newType, err := abi.NewType(t, internalType, components) + if err != nil { + panic(err) + } + return newType +} + +type SendTokenParams struct { + Client simulated.Client + Sender common.Address + TokenAddress common.Address + GetBalance func(ctx context.Context, tokenAddress common.Address, decimals int32, client simulated.Client) (decimal.Decimal, error) + TokenDecimals int32 + ToAddress common.Address + AmountWei decimal.Decimal +} + +func BuildSendToken(ctx context.Context, args SendTokenParams) (*types.LegacyTx, error) { + var ( + isNativeToken = strings.EqualFold(args.TokenAddress.Hex(), constant.ZeroAddress.Hex()) + ) + balance, err := args.GetBalance(ctx, args.TokenAddress, args.TokenDecimals, args.Client) + if err != nil { + return nil, errors.Wrap(err, "get balance") + } + balanceWei := decimal.NewFromBigInt(EthToWei(balance, args.TokenDecimals), 0) + if balanceWei.IsZero() || balanceWei.IsNegative() || balanceWei.LessThan(args.AmountWei) { + return nil, error_types.ErrInsufficientBalance + } + + if !isNativeToken { + nativeTokenBalanceWei, err := args.Client.BalanceAt(ctx, args.Sender, nil) + if err != nil { + return nil, error_types.ErrNativeTokenInsufficient + } + if nativeTokenBalanceWei.Cmp(big.NewInt(0)) < 0 { + return nil, error_types.ErrNativeTokenInsufficient + } + } + + var tx *types.LegacyTx + if isNativeToken { + tx = &types.LegacyTx{ + To: &args.ToAddress, + Value: args.AmountWei.BigInt(), + } + } + + if !isNativeToken { + erc20Abi, err := erc20.TokenMetaData.GetAbi() + if err != nil { + return nil, errors.Wrap(err, "get abi") + } + input, err := erc20Abi.Pack("transfer", args.ToAddress, args.AmountWei.BigInt()) + if err != nil { + return nil, errors.Wrap(err, "abi pack") + } + tx = &types.LegacyTx{ + To: &args.TokenAddress, + Data: input, + } + } + return tx, nil +} + +func SendTransaction(ctx context.Context, client simulated.Client, tx *types.LegacyTx, + sender common.Address, privateKey string) (common.Hash, error) { + if tx.Nonce == 0 { + nonce, err := client.NonceAt(ctx, sender, nil) + if err != nil { + return common.Hash{}, errors.Wrap(err, "get nonce") + } + tx.Nonce = nonce + } + if tx.GasPrice == nil { + gasPrice, err := client.SuggestGasPrice(ctx) + if err != nil { + return common.Hash{}, errors.Wrap(err, "suggest gas price") + } + tx.GasPrice = gasPrice + } + + if tx.Gas == 0 { + gas, err := client.EstimateGas(ctx, ethereum.CallMsg{ + From: sender, + To: tx.To, + Value: tx.Value, + Data: tx.Data, + }) + if err != nil { + return common.Hash{}, errors.Wrap(err, "estimate gas") + } + tx.Gas = gas + } + chainId, err := client.ChainID(ctx) + if err != nil { + return common.Hash{}, errors.Wrap(err, "get chain id") + } + transaction, err := SignTx(types.NewTx(tx), privateKey, chainId.Int64()) + if err != nil { + return common.Hash{}, errors.Wrap(err, "sign tx") + } + return transaction.Hash(), client.SendTransaction(ctx, transaction) +} + +func IsTransferInput(input []byte) bool { + if len(input) == 0 { + return false + } + _, _, err := GetTransferInfo(input) + return err == nil +} + +// GetTransferInfo input ex: a9059cbb0000000000000000000000000350101f2cb6aa65caab7954246a56f906a3f57d0000000000000000000000000000000000000000033b2e3c9fd0803ce8000000 +func GetTransferInfo(input []byte) (to common.Address, amount *big.Int, err error) { + erc20Abi, err := erc20.TokenMetaData.GetAbi() + if err != nil { + return common.Address{}, nil, errors.Wrap(err, "get abi") + } + args, err := erc20Abi.Methods["transfer"].Inputs.Unpack(input[4:]) + if err != nil { + return common.Address{}, nil, errors.Wrap(err, "unpack") + } + if len(args) != 2 { + return common.Address{}, nil, errors.New("invalid args") + } + return args[0].(common.Address), args[1].(*big.Int), nil +} diff --git a/utils/configs/config.go b/utils/configs/config.go new file mode 100644 index 0000000..b532df4 --- /dev/null +++ b/utils/configs/config.go @@ -0,0 +1,468 @@ +package configs + +import ( + "encoding/json" + "fmt" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "omni-balance/utils" + "omni-balance/utils/constant" + "omni-balance/utils/wallets" + "strings" + "time" +) + +// LiquidityProviderType liquidity provider type +type LiquidityProviderType string +type DbType string + +const ( + // CEX centralized exchange + CEX LiquidityProviderType = "CEX" + // DEX decentralized exchange + DEX LiquidityProviderType = "DEX" + // Bridge cross-chain bridge + Bridge LiquidityProviderType = "Bridge" +) + +const ( + // MySQL mysql + MySQL DbType = "MySQL" + // PostgreSQL postgresql + PostgreSQL DbType = "PostgreSQL" + // SQLite sqlite + SQLite DbType = "SQLite" +) + +type Config struct { + Debug bool `json:"debug" yaml:"debug" comment:"Debug mode"` + + // Chains need to be monitored + Chains []Chain `json:"chains" yaml:"chains" comment:"Chains"` + chains map[string]Chain + + // SourceToken used to buy other tokens + SourceToken []SourceToken `json:"source_token" yaml:"source_token" comment:"Source token used to buy other tokens"` + sourceToken map[string]SourceToken + + LiquidityProviders []LiquidityProvider `json:"liquidity_providers" yaml:"liquidity_providers" comment:"Liquidity providers"` + liquidityProvider map[LiquidityProviderType][]LiquidityProvider + + Wallets []Wallet `json:"wallets" yaml:"wallets" comment:"Wallets need to rebalance"` + wallets map[string]Wallet + + Db DbConfig `json:"db" yaml:"db" comment:"Database config"` + + TaskInterval map[string]time.Duration `json:"task_interval" yaml:"task_interval"` + + // 通知渠道, 当成功rebalance时, 发送通知 + Notice struct { + Type string `json:"type" yaml:"type" comment:"Notice type, support: slack"` + Config map[string]interface{} `json:"config" yaml:"config" comment:"It depends on the notification type, slack needs ['webhook','channel']"` + } `json:"notice" yaml:"notice" comment:"Notice config. When rebalance success, send notice"` +} + +type Chain struct { + Id int `json:"id" yaml:"id" comment:"Chain id"` + Name string `json:"name" yaml:"name" comment:"Chain name"` + NativeToken string `json:"native_token" comment:"Native token name, if not set, use the 0x0000000000000000000000000000000000000000"` + RpcEndpoints []string `json:"rpc_endpoints" yaml:"rpc_endpoints" comment:"RPC endpoints"` + Tokens []Token `json:"tokens" yaml:"tokens" comment:"Tokens"` +} + +type Wallet struct { + Address string `json:"address" yaml:"address" comment:"Monitoring address"` + Operator Operator `json:"operator" yaml:"operator" comment:"Used to isolate the monitoring address and the operation address, preventing the leakage of the monitoring address private key. If Operator is empty, it is not enabled. If 'multi_sign_type' is not empty, 'address' is multi sign address, 'operator' is multi sign operator address"` + MultiSignType string `json:"multi_sign_type" yaml:"multi_sign_type" comment:"multi sign address type, support: safe. If not empty, 'address' is multi sign address, 'operator' is multi sign operator address"` + Tokens []WalletToken `json:"tokens" yaml:"tokens" comment:"Tokens to be monitored"` + PrivateKey string `json:"private_key" yaml:"private_key" comment:"'address' private key. If 'operator' is not empty, private_key is the operator's private key"` +} + +type Operator struct { + // Address Operator address + Address common.Address `json:"address" yaml:"address" comment:"Operator address"` + Operator common.Address `json:"operator" yaml:"operator" comment:"Used to isolate the monitoring address and the operation address, preventing the leakage of the monitoring address private key. If Operator is empty, it is not enabled. If 'multi_sign_type' is not empty, 'address' is multi sign address, 'operator' is multi sign operator address"` + PrivateKey string `json:"private_key" yaml:"private_key" comment:"'address' private key. If 'operator' is not empty, private_key is the operator's private key"` + MultiSignType string `json:"multi_sign_type" yaml:"multi_sign_type" comment:"MultiSign type, ex: safe"` +} + +type WalletToken struct { + Name string `json:"name" yaml:"name" comment:"Token name"` + Amount decimal.Decimal `json:"amount" yaml:"amount" comment:"The number of each rebalance"` + Threshold decimal.Decimal `json:"threshold" yaml:"threshold" comment:"Threshold when the token balance is less than the threshold, the rebalance will be triggered"` + Chains []string `json:"chains" yaml:"chains" comment:"The chains need to be monitored"` +} + +type CrossChain struct { + Providers []string `json:"providers" yaml:"providers" comment:"use providers to cross chain"` + TargetChain string `json:"target_chain" yaml:"target_chain" comment:"target chain name"` +} + +type Token struct { + Name string `json:"name" yaml:"name" comment:"Token name"` + ContractAddress string `json:"contract_address" yaml:"contract_address" comment:"Token contract address"` + // decimals token decimals + Decimals int32 `json:"decimals" yaml:"decimals" comment:"Token decimals"` +} + +// SourceToken used to buy other tokens +type SourceToken struct { + Name string `json:"name" yaml:"name" comment:"Token name"` + Chains []string `json:"chains" yaml:"chains" comment:"Chain name"` +} + +// TargetToken use SourceToken to buy TargetToken +type TargetToken struct { + Name string `json:"name" yaml:"name" comment:"Token name"` + Amount decimal.Decimal `json:"amount" yaml:"amount" comment:"The number of each rebalance"` + Threshold decimal.Decimal `json:"threshold" yaml:"threshold" help:"Threshold when the token balance is less than the threshold, the rebalance will be triggered"` +} + +// LiquidityProvider liquidity provider +type LiquidityProvider struct { + // Type liquidity provider type + Type LiquidityProviderType `json:"type" yaml:"type" comment:"Type liquidity provider type"` + // LiquidityName liquidity provider name + LiquidityName string `json:"liquidity_name" yaml:"liquidity_name" comment:"LiquidityName liquidity provider name"` + // Config liquidity provider config, depend on the type + Config map[string]interface{} `json:"config" yaml:"config" comment:"Config liquidity provider config, depend on the type"` +} + +type DbConfig struct { + // Type db type + Type DbType `json:"type"` + // MySQL mysql config + MySQL *MysqlConfig `json:"mysql,omitempty" yaml:"MYSQL" comment:"MYSQL config"` + // PostgreSQL postgresql config + PostgreSQL *MysqlConfig `json:"postgresql,omitempty" yaml:"POSTGRESQL" comment:"POSTGRESQL config"` + // SQLite sqlite config + SQLite *Sqlite `json:"sqlite,omitempty" yaml:"SQLITE" comment:"SQLITE config"` +} + +type MysqlConfig struct { + // Host mysql host + Host string `json:"host" yaml:"host"` + // Port mysql port + Port string `json:"port" yaml:"port"` + // User mysql user + User string `json:"user" yaml:"user"` + // Password mysql password + Password string `json:"password" yaml:"password"` + // Database mysql database + Database string `json:"database" yaml:"database"` +} + +type Sqlite struct { + // Path sqlite path + Path string `json:"path"` +} + +func (c Chain) GetToken(tokenName string) Token { + for _, v := range c.Tokens { + if !strings.EqualFold(v.Name, tokenName) { + continue + } + return v + } + return Token{} +} + +func (c *Config) Init() *Config { + c.chains = make(map[string]Chain) + oldName2NewName := make(map[string]string) + + for index, v := range c.Chains { + newName := constant.GetChainName(v.Id) + if newName == "" { + panic(fmt.Sprintf("chain id %d not found", v.Id)) + } + // 规范所有链的名字 + oldName2NewName[v.Name] = newName + c.Chains[index].Name = newName + c.chains[newName] = c.Chains[index] + } + + c.sourceToken = make(map[string]SourceToken) + for index, v := range c.SourceToken { + var chains []string + for _, v := range v.Chains { + if newName, ok := oldName2NewName[v]; ok { + chains = append(chains, newName) + continue + } + panic(fmt.Sprintf("chain %s not found", v)) + } + c.SourceToken[index].Chains = chains + c.sourceToken[v.Name] = c.SourceToken[index] + } + + c.liquidityProvider = make(map[LiquidityProviderType][]LiquidityProvider) + for _, v := range c.LiquidityProviders { + c.liquidityProvider[v.Type] = append(c.liquidityProvider[v.Type], v) + } + + c.wallets = make(map[string]Wallet) + for walletIndex, v := range c.Wallets { + for index, t := range v.Tokens { + var chains []string + for _, v := range t.Chains { + if newName, ok := oldName2NewName[v]; ok { + chains = append(chains, newName) + continue + } + panic(fmt.Sprintf("chain %s not found", v)) + } + c.Wallets[walletIndex].Tokens[index].Chains = chains + } + c.wallets[v.Address] = c.Wallets[walletIndex] + } + return c +} + +func (c *Config) Check() error { + if len(c.Chains) == 0 { + return errors.New("chains must be set") + } + for chainIndex, v := range c.Chains { + if len(v.RpcEndpoints) == 0 { + return errors.New("rpc_endpoints must be set") + } + if len(v.Tokens) == 0 { + return errors.New("tokens must be set") + } + for index, v := range v.Tokens { + if v.ContractAddress == "" { + return errors.Errorf("chains[%d]tokens[%d]contract_address must be set", chainIndex, index) + } + if v.Name == "" { + return errors.Errorf("chains[%d]tokens[%d]name must be set", chainIndex, index) + } + if v.Decimals == 0 { + return errors.Errorf("chains[%d]tokens[%d]decimals must be set", chainIndex, index) + } + } + } + + if len(c.SourceToken) == 0 { + return errors.New("source_token must be set") + } + for index, v := range c.SourceToken { + for chainIndex, chain := range v.Chains { + if _, ok := c.chains[chain]; !ok { + return errors.Errorf("source_token[%d]chains[%d] not in chains", index, chainIndex) + } + var ok bool + for _, token := range c.chains[chain].Tokens { + if strings.EqualFold(token.Name, v.Name) { + ok = true + } + } + if !ok { + return errors.Errorf("source_token[%d] token name not in chains", index) + } + } + } + + if len(c.LiquidityProviders) == 0 { + return errors.New("liquidity_providers must be set") + } + for index, v := range c.LiquidityProviders { + if v.Type == "" { + return errors.Errorf("liquidity_providers[%d]type must be set", index) + } + + if v.LiquidityName == "" { + return errors.Errorf("liquidity_providers[%d]liquidity_name must be set", index) + } + } + + if len(c.Wallets) == 0 { + return errors.New("wallets must be set") + } + for index, v := range c.Wallets { + if v.Address == "" { + return errors.Errorf("wallets[%d]address must be set", index) + } + if len(v.Tokens) == 0 { + return errors.Errorf("wallets[%d]tokens must be set", index) + } + for tokenIndex, token := range v.Tokens { + if token.Name == "" { + return errors.Errorf("wallets[%d]tokens[%d]name must be set", index, tokenIndex) + } + if token.Amount.IsZero() { + return errors.Errorf("wallets[%d]tokens[%d]amount must be set", index, tokenIndex) + } + if token.Threshold.IsZero() { + return errors.Errorf("wallets[%d]tokens[%d]threshold must be set", index, tokenIndex) + } + + if len(token.Chains) == 0 { + return errors.Errorf("wallets[%d]tokens[%d]chains must be set", index, tokenIndex) + } + for chainIndex, chain := range token.Chains { + if _, ok := c.chains[chain]; !ok { + return errors.Errorf("wallets[%d]tokens[%d]chains[%d] not in chains", index, tokenIndex, chainIndex) + } + var ok bool + for _, chainToken := range c.chains[chain].Tokens { + if strings.EqualFold(chainToken.Name, chainToken.Name) { + ok = true + } + } + if !ok { + return errors.Errorf("wallets[%d]tokens[%d] token name not in chains", index, tokenIndex) + } + } + } + } + + if c.Db.Type == "" { + return errors.New("db type must be set") + } + if c.Db.Type == MySQL && c.Db.MySQL == nil { + return errors.New("mysql config must be set") + } + if c.Db.Type == PostgreSQL && c.Db.PostgreSQL == nil { + return errors.New("postgresql config must be set") + } + if c.Db.Type == SQLite && c.Db.SQLite == nil { + return errors.New("sqlite config must be set") + } + return nil +} + +func (c *Config) GetProvidersConfig(name string, providerType LiquidityProviderType, dest interface{}) error { + for _, provider := range c.liquidityProvider[providerType] { + if !strings.EqualFold(provider.LiquidityName, name) { + continue + } + + conf, err := json.Marshal(provider.Config) + if err != nil { + return err + } + return json.Unmarshal(conf, dest) + } + return errors.Errorf("provider %s not found", name) +} + +func (c *Config) GetChainConfig(chainName string) Chain { + return c.chains[chainName] +} + +func (c *Config) GetTokenThreshold(wallet, tokenName, chain string) decimal.Decimal { + for _, token := range c.wallets[wallet].Tokens { + if !strings.EqualFold(token.Name, tokenName) { + continue + } + if utils.InArray(chain, token.Chains) { + return token.Threshold + } + } + logrus.Fatalf("token %s not found on chain %s", tokenName, chain) + return decimal.Zero +} + +func (c *Config) GetWallet(wallet string) wallets.Wallets { + return wallets.NewWallets(wallets.WalletConfig{ + PrivateKey: c.wallets[wallet].PrivateKey, + Address: common.HexToAddress(c.wallets[wallet].Address), + Operator: wallets.Operator{ + Address: c.wallets[wallet].Operator.Address, + Operator: c.wallets[wallet].Operator.Operator, + PrivateKey: c.wallets[wallet].Operator.PrivateKey, + MultiSignType: c.wallets[wallet].Operator.MultiSignType, + }, + MultiSignType: c.wallets[wallet].MultiSignType, + }) +} + +func (c *Config) GetWalletConfig(wallet string) Wallet { + return c.wallets[wallet] +} + +func (c *Config) GetTokenInfoOnChain(tokenName, chainName string) Token { + for _, token := range c.chains[chainName].Tokens { + if !strings.EqualFold(token.Name, tokenName) { + continue + } + return token + } + logrus.Fatalf("token %s not found on chain %s", tokenName, chainName) + return Token{} +} + +func (c *Config) GetTokenPurchaseAmount(wallet, tokenName, chain string) decimal.Decimal { + for _, token := range c.wallets[wallet].Tokens { + if !strings.EqualFold(token.Name, tokenName) { + continue + } + if utils.InArray(chain, token.Chains) { + return token.Amount + } + } + logrus.Fatalf("token %s not found on chain %s", tokenName, chain) + return decimal.Zero +} + +func (c *Config) GetTokenAddress(tokenName, chainName string) string { + address := c.GetTokenInfoOnChain(tokenName, chainName).ContractAddress + if address == "" { + logrus.Fatalf("token %s not found on chain %s", tokenName, chainName) + } + return address +} + +func (c *Config) GetSourceTokenNamesByChain(chainName string) []string { + var result []string + for _, v := range c.SourceToken { + if !utils.InArray(chainName, v.Chains) { + continue + } + result = append(result, v.Name) + } + if len(result) == 0 { + logrus.Fatalf("source token not found on chain %s", chainName) + } + return result +} + +func (w Wallet) CheckPrivateKey() error { + if w.PrivateKey == "" { + return errors.New("private key must be set") + } + key, err := crypto.HexToECDSA(w.PrivateKey) + if err != nil { + return errors.Wrap(err, "privateKey") + } + if !strings.EqualFold(w.Address, crypto.PubkeyToAddress(key.PublicKey).Hex()) { + return errors.New("private key and address not match") + } + return nil +} + +func (c *Config) GetTaskInterval(name string, defaultInterval time.Duration) time.Duration { + if len(c.TaskInterval) == 0 { + return defaultInterval + } + if _, ok := c.TaskInterval[name]; !ok { + return defaultInterval + } + return c.TaskInterval[name] +} + +func (c *Config) IsNativeToken(chainName, tokenName string) bool { + if strings.EqualFold(c.chains[chainName].NativeToken, tokenName) { + return true + } + for _, token := range c.chains[chainName].Tokens { + if strings.EqualFold(token.Name, tokenName) { + return strings.EqualFold(token.ContractAddress, constant.ZeroAddress.Hex()) + } + } + return false +} diff --git a/utils/constant/chain.go b/utils/constant/chain.go new file mode 100644 index 0000000..002cf0c --- /dev/null +++ b/utils/constant/chain.go @@ -0,0 +1,110 @@ +package constant + +import "golang.org/x/exp/constraints" + +const ( + Zksync = "zksync" + Sepolia = "sepolia" + Polygon = "polygon" + PolygonZkEvm = "polygon-zkEvm" + Bsc = "bsc" + Blast = "blast" + DarwiniaDvm = "darwinia-dvm" + Base = "base" + Arbitrum = "arbitrum" + Gnosis = "gnosis" + Scroll = "scroll" + Optimism = "op" + AstarZkevm = "astar-zkevm" + Mantle = "mantle" + Linea = "linea" + CrabDvm = "crab-dvm" + Ethereum = "ethereum" + Merlin = "merlin" + Avalanche = "avalanche" + Mode = "mode" + Cronos = "cronos" + PulseChain = "pulseChain" + Kava = "kava" + ZkLinkNova = "zkLink-nova" + Rootstock = "rootstock" + ZkSync = "zkSync" + Astar = "astar" + OpBNB = "opBNB" + Bnb = "bnb" + Celo = "celo" +) + +const ( + ChainNameKeyInCtx ContextKey = "chain_name" + LogKeyInCtx ContextKey = "log" +) + +var ( + chainName2Id = map[string]int{ + Sepolia: 11155111, + Zksync: 324, + Polygon: 137, + PolygonZkEvm: 1101, + Bsc: 56, + Blast: 81457, + DarwiniaDvm: 46, + Base: 8453, + Arbitrum: 42161, + Gnosis: 100, + Scroll: 534352, + Optimism: 10, + AstarZkevm: 3776, + Mantle: 5000, + Linea: 59144, + CrabDvm: 44, + Ethereum: 1, + Merlin: 4200, + Avalanche: 43114, + Mode: 34443, + Cronos: 25, + PulseChain: 369, + Kava: 2222, + ZkLinkNova: 810180, + Rootstock: 30, + ZkSync: 324, + Astar: 592, + OpBNB: 204, + Bnb: 56, + Celo: 42220, + } + chainId2Name = make(map[int]string) +) + +func init() { + if len(chainId2Name) != 0 { + return + } + for k, v := range chainName2Id { + chainId2Name[v] = k + } +} + +func GetChainName[t constraints.Integer](chainId t) string { + return chainId2Name[int(chainId)] +} + +func GetChainId(chainName string) int { + return chainName2Id[chainName] +} + +func ListChainId() []int { + var chainIds []int + for _, v := range chainName2Id { + chainIds = append(chainIds, v) + } + return chainIds +} + +func ListChainName() []string { + var chainNames []string + for k := range chainName2Id { + chainNames = append(chainNames, k) + } + return chainNames +} diff --git a/utils/constant/tests_data.go b/utils/constant/tests_data.go new file mode 100644 index 0000000..f162641 --- /dev/null +++ b/utils/constant/tests_data.go @@ -0,0 +1,20 @@ +package constant + +import "context" + +type ContextKey string + +const ( + // TestPrivateKey and TestWalletAddress is for testnet, nothing to do with mainnet + TestPrivateKey = "2f8f3049314beb2adffeac27ce9ea799b254cc5035673c861b1c0a09539b3de3" // gitleaks:allow + TestWalletAddress = "0x43Ef13E84D9992d1461a1f90CAc4653658CEA4FD" // gitleaks:allow + testKey ContextKey = "is_test" +) + +func WithTestCtx(ctx context.Context) context.Context { + return context.WithValue(ctx, testKey, true) +} + +func IsTestCtx(ctx context.Context) bool { + return ctx.Value(testKey) == true +} diff --git a/utils/constant/token.go b/utils/constant/token.go new file mode 100644 index 0000000..8db4710 --- /dev/null +++ b/utils/constant/token.go @@ -0,0 +1,50 @@ +package constant + +import "github.com/ethereum/go-ethereum/common" + +var ( + ZeroAddress = common.HexToAddress("0x0000000000000000000000000000000000000000") + //stableTokens = map[string]StableToken{ + // Ethereum: { + // USDT: common.HexToAddress("0xdAC17F958D2ee523a2206206994597C13D831ec7"), + // USDC: common.HexToAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"), + // }, + // Polygon: { + // USDT: common.HexToAddress("0xc2132D05D31c914a87C6611C10748AEb04B58e8F"), + // USDC: common.HexToAddress("0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"), + // }, + // Bnb: { + // USDT: common.HexToAddress("0x55d398326f99059fF775485246999027B3197955"), + // USDC: common.HexToAddress("0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"), + // }, + // Avalanche: { + // USDT: common.HexToAddress("0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7"), + // USDC: common.HexToAddress("0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"), + // }, + // Arbitrum: { + // USDT: common.HexToAddress("0xFd086bC7CD5C481DCC9C85ebE478A1C0Ps0000"), + // USDC: common.HexToAddress("0xaf88d065e77c8cC2239327C5EDb3A432268e5831"), + // }, + // Optimism: { + // USDT: common.HexToAddress("0x94b008aA00579c1307B06f3CD2E8CEa38539Ef48"), + // USDC: common.HexToAddress("0x7F5c764cBc14f9669B88837ca1490cCa17c31607"), + // }, + // Base: { + // USDT: common.HexToAddress("0xFd086bC7CD5C481DCC9C85ebE478A1C0Ps0000"), + // USDC: common.HexToAddress("0xaf88d065e77c8cC2239327C5EDb3A432268e5831"), + // }, + // Celo: { + // USDT: common.HexToAddress("0x765DE816845861e75A25D541C82aB31593bB6eD8"), + // USDC: common.HexToAddress("0xF194afDf50B03e69Bd7D057c1Aa9e10c9954E4C9"), + // }, + // Blast: { + // USDT: common.HexToAddress("0xFd086bC7CD5C481DCC9C85ebE478A1C0Ps0000"), + // USDC: common.HexToAddress("0xaf88d065e77c8cC2239327C5EDb3A432268e5831"), + // }, + //} +) + +type StableToken struct { + USDT common.Address + USDC common.Address +} diff --git a/utils/consts.go b/utils/consts.go new file mode 100644 index 0000000..0f07a9d --- /dev/null +++ b/utils/consts.go @@ -0,0 +1,16 @@ +package utils + +import "sync/atomic" + +var ( + // 是否初始化完成 + isInit atomic.Bool +) + +func IsFinishedInit() bool { + return isInit.Load() +} + +func FinishInit() { + isInit.Store(true) +} diff --git a/utils/erc20/erc20.go b/utils/erc20/erc20.go new file mode 100644 index 0000000..cb67c42 --- /dev/null +++ b/utils/erc20/erc20.go @@ -0,0 +1,759 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package erc20 + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription + _ = abi.ConvertType +) + +// TokenMetaData contains all meta data concerning the Token contract. +var TokenMetaData = &bind.MetaData{ + ABI: "[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"TotalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"balance\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"}]", +} + +// TokenABI is the input ABI used to generate the binding from. +// Deprecated: Use TokenMetaData.ABI instead. +var TokenABI = TokenMetaData.ABI + +// Token is an auto generated Go binding around an Ethereum contract. +type Token struct { + TokenCaller // Read-only binding to the contract + TokenTransactor // Write-only binding to the contract + TokenFilterer // Log filterer for contract events +} + +// TokenCaller is an auto generated read-only Go binding around an Ethereum contract. +type TokenCaller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// TokenTransactor is an auto generated write-only Go binding around an Ethereum contract. +type TokenTransactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// TokenFilterer is an auto generated log filtering Go binding around an Ethereum contract events. +type TokenFilterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// TokenSession is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type TokenSession struct { + Contract *Token // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// TokenCallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type TokenCallerSession struct { + Contract *TokenCaller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// TokenTransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type TokenTransactorSession struct { + Contract *TokenTransactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// TokenRaw is an auto generated low-level Go binding around an Ethereum contract. +type TokenRaw struct { + Contract *Token // Generic contract binding to access the raw methods on +} + +// TokenCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type TokenCallerRaw struct { + Contract *TokenCaller // Generic read-only contract binding to access the raw methods on +} + +// TokenTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type TokenTransactorRaw struct { + Contract *TokenTransactor // Generic write-only contract binding to access the raw methods on +} + +// NewToken creates a new instance of Token, bound to a specific deployed contract. +func NewToken(address common.Address, backend bind.ContractBackend) (*Token, error) { + contract, err := bindToken(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &Token{TokenCaller: TokenCaller{contract: contract}, TokenTransactor: TokenTransactor{contract: contract}, TokenFilterer: TokenFilterer{contract: contract}}, nil +} + +// NewTokenCaller creates a new read-only instance of Token, bound to a specific deployed contract. +func NewTokenCaller(address common.Address, caller bind.ContractCaller) (*TokenCaller, error) { + contract, err := bindToken(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &TokenCaller{contract: contract}, nil +} + +// NewTokenTransactor creates a new write-only instance of Token, bound to a specific deployed contract. +func NewTokenTransactor(address common.Address, transactor bind.ContractTransactor) (*TokenTransactor, error) { + contract, err := bindToken(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &TokenTransactor{contract: contract}, nil +} + +// NewTokenFilterer creates a new log filterer instance of Token, bound to a specific deployed contract. +func NewTokenFilterer(address common.Address, filterer bind.ContractFilterer) (*TokenFilterer, error) { + contract, err := bindToken(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &TokenFilterer{contract: contract}, nil +} + +// bindToken binds a generic wrapper to an already deployed contract. +func bindToken(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := TokenMetaData.GetAbi() + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Token *TokenRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Token.Contract.TokenCaller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Token *TokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Token.Contract.TokenTransactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Token *TokenRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Token.Contract.TokenTransactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Token *TokenCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Token.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Token *TokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Token.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Token *TokenTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Token.Contract.contract.Transact(opts, method, params...) +} + +// TotalSupply is a free data retrieval call binding the contract method 0xa44b47f7. +// +// Solidity: function TotalSupply() view returns(uint256) +func (_Token *TokenCaller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "TotalSupply") + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// TotalSupply is a free data retrieval call binding the contract method 0xa44b47f7. +// +// Solidity: function TotalSupply() view returns(uint256) +func (_Token *TokenSession) TotalSupply() (*big.Int, error) { + return _Token.Contract.TotalSupply(&_Token.CallOpts) +} + +// TotalSupply is a free data retrieval call binding the contract method 0xa44b47f7. +// +// Solidity: function TotalSupply() view returns(uint256) +func (_Token *TokenCallerSession) TotalSupply() (*big.Int, error) { + return _Token.Contract.TotalSupply(&_Token.CallOpts) +} + +// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. +// +// Solidity: function allowance(address _owner, address _spender) view returns(uint256) +func (_Token *TokenCaller) Allowance(opts *bind.CallOpts, _owner common.Address, _spender common.Address) (*big.Int, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "allowance", _owner, _spender) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. +// +// Solidity: function allowance(address _owner, address _spender) view returns(uint256) +func (_Token *TokenSession) Allowance(_owner common.Address, _spender common.Address) (*big.Int, error) { + return _Token.Contract.Allowance(&_Token.CallOpts, _owner, _spender) +} + +// Allowance is a free data retrieval call binding the contract method 0xdd62ed3e. +// +// Solidity: function allowance(address _owner, address _spender) view returns(uint256) +func (_Token *TokenCallerSession) Allowance(_owner common.Address, _spender common.Address) (*big.Int, error) { + return _Token.Contract.Allowance(&_Token.CallOpts, _owner, _spender) +} + +// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. +// +// Solidity: function balanceOf(address _owner) view returns(uint256 balance) +func (_Token *TokenCaller) BalanceOf(opts *bind.CallOpts, _owner common.Address) (*big.Int, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "balanceOf", _owner) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. +// +// Solidity: function balanceOf(address _owner) view returns(uint256 balance) +func (_Token *TokenSession) BalanceOf(_owner common.Address) (*big.Int, error) { + return _Token.Contract.BalanceOf(&_Token.CallOpts, _owner) +} + +// BalanceOf is a free data retrieval call binding the contract method 0x70a08231. +// +// Solidity: function balanceOf(address _owner) view returns(uint256 balance) +func (_Token *TokenCallerSession) BalanceOf(_owner common.Address) (*big.Int, error) { + return _Token.Contract.BalanceOf(&_Token.CallOpts, _owner) +} + +// Decimals is a free data retrieval call binding the contract method 0x313ce567. +// +// Solidity: function decimals() view returns(uint8) +func (_Token *TokenCaller) Decimals(opts *bind.CallOpts) (uint8, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "decimals") + + if err != nil { + return *new(uint8), err + } + + out0 := *abi.ConvertType(out[0], new(uint8)).(*uint8) + + return out0, err + +} + +// Decimals is a free data retrieval call binding the contract method 0x313ce567. +// +// Solidity: function decimals() view returns(uint8) +func (_Token *TokenSession) Decimals() (uint8, error) { + return _Token.Contract.Decimals(&_Token.CallOpts) +} + +// Decimals is a free data retrieval call binding the contract method 0x313ce567. +// +// Solidity: function decimals() view returns(uint8) +func (_Token *TokenCallerSession) Decimals() (uint8, error) { + return _Token.Contract.Decimals(&_Token.CallOpts) +} + +// Name is a free data retrieval call binding the contract method 0x06fdde03. +// +// Solidity: function name() view returns(string) +func (_Token *TokenCaller) Name(opts *bind.CallOpts) (string, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "name") + + if err != nil { + return *new(string), err + } + + out0 := *abi.ConvertType(out[0], new(string)).(*string) + + return out0, err + +} + +// Name is a free data retrieval call binding the contract method 0x06fdde03. +// +// Solidity: function name() view returns(string) +func (_Token *TokenSession) Name() (string, error) { + return _Token.Contract.Name(&_Token.CallOpts) +} + +// Name is a free data retrieval call binding the contract method 0x06fdde03. +// +// Solidity: function name() view returns(string) +func (_Token *TokenCallerSession) Name() (string, error) { + return _Token.Contract.Name(&_Token.CallOpts) +} + +// Symbol is a free data retrieval call binding the contract method 0x95d89b41. +// +// Solidity: function symbol() view returns(string) +func (_Token *TokenCaller) Symbol(opts *bind.CallOpts) (string, error) { + var out []interface{} + err := _Token.contract.Call(opts, &out, "symbol") + + if err != nil { + return *new(string), err + } + + out0 := *abi.ConvertType(out[0], new(string)).(*string) + + return out0, err + +} + +// Symbol is a free data retrieval call binding the contract method 0x95d89b41. +// +// Solidity: function symbol() view returns(string) +func (_Token *TokenSession) Symbol() (string, error) { + return _Token.Contract.Symbol(&_Token.CallOpts) +} + +// Symbol is a free data retrieval call binding the contract method 0x95d89b41. +// +// Solidity: function symbol() view returns(string) +func (_Token *TokenCallerSession) Symbol() (string, error) { + return _Token.Contract.Symbol(&_Token.CallOpts) +} + +// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. +// +// Solidity: function approve(address _spender, uint256 _value) returns(bool) +func (_Token *TokenTransactor) Approve(opts *bind.TransactOpts, _spender common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "approve", _spender, _value) +} + +// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. +// +// Solidity: function approve(address _spender, uint256 _value) returns(bool) +func (_Token *TokenSession) Approve(_spender common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.Contract.Approve(&_Token.TransactOpts, _spender, _value) +} + +// Approve is a paid mutator transaction binding the contract method 0x095ea7b3. +// +// Solidity: function approve(address _spender, uint256 _value) returns(bool) +func (_Token *TokenTransactorSession) Approve(_spender common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.Contract.Approve(&_Token.TransactOpts, _spender, _value) +} + +// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. +// +// Solidity: function transfer(address _to, uint256 _value) returns(bool) +func (_Token *TokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "transfer", _to, _value) +} + +// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. +// +// Solidity: function transfer(address _to, uint256 _value) returns(bool) +func (_Token *TokenSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.Contract.Transfer(&_Token.TransactOpts, _to, _value) +} + +// Transfer is a paid mutator transaction binding the contract method 0xa9059cbb. +// +// Solidity: function transfer(address _to, uint256 _value) returns(bool) +func (_Token *TokenTransactorSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.Contract.Transfer(&_Token.TransactOpts, _to, _value) +} + +// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. +// +// Solidity: function transferFrom(address _from, address _to, uint256 _value) returns(bool) +func (_Token *TokenTransactor) TransferFrom(opts *bind.TransactOpts, _from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.contract.Transact(opts, "transferFrom", _from, _to, _value) +} + +// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. +// +// Solidity: function transferFrom(address _from, address _to, uint256 _value) returns(bool) +func (_Token *TokenSession) TransferFrom(_from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.Contract.TransferFrom(&_Token.TransactOpts, _from, _to, _value) +} + +// TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. +// +// Solidity: function transferFrom(address _from, address _to, uint256 _value) returns(bool) +func (_Token *TokenTransactorSession) TransferFrom(_from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) { + return _Token.Contract.TransferFrom(&_Token.TransactOpts, _from, _to, _value) +} + +// Fallback is a paid mutator transaction binding the contract fallback function. +// +// Solidity: fallback() payable returns() +func (_Token *TokenTransactor) Fallback(opts *bind.TransactOpts, calldata []byte) (*types.Transaction, error) { + return _Token.contract.RawTransact(opts, calldata) +} + +// Fallback is a paid mutator transaction binding the contract fallback function. +// +// Solidity: fallback() payable returns() +func (_Token *TokenSession) Fallback(calldata []byte) (*types.Transaction, error) { + return _Token.Contract.Fallback(&_Token.TransactOpts, calldata) +} + +// Fallback is a paid mutator transaction binding the contract fallback function. +// +// Solidity: fallback() payable returns() +func (_Token *TokenTransactorSession) Fallback(calldata []byte) (*types.Transaction, error) { + return _Token.Contract.Fallback(&_Token.TransactOpts, calldata) +} + +// TokenApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the Token contract. +type TokenApprovalIterator struct { + Event *TokenApproval // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *TokenApprovalIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(TokenApproval) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(TokenApproval) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *TokenApprovalIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *TokenApprovalIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// TokenApproval represents a Approval event raised by the Token contract. +type TokenApproval struct { + Owner common.Address + Spender common.Address + Value *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterApproval is a free log retrieval operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. +// +// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) +func (_Token *TokenFilterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, spender []common.Address) (*TokenApprovalIterator, error) { + + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + var spenderRule []interface{} + for _, spenderItem := range spender { + spenderRule = append(spenderRule, spenderItem) + } + + logs, sub, err := _Token.contract.FilterLogs(opts, "Approval", ownerRule, spenderRule) + if err != nil { + return nil, err + } + return &TokenApprovalIterator{contract: _Token.contract, event: "Approval", logs: logs, sub: sub}, nil +} + +// WatchApproval is a free log subscription operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. +// +// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) +func (_Token *TokenFilterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *TokenApproval, owner []common.Address, spender []common.Address) (event.Subscription, error) { + + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + var spenderRule []interface{} + for _, spenderItem := range spender { + spenderRule = append(spenderRule, spenderItem) + } + + logs, sub, err := _Token.contract.WatchLogs(opts, "Approval", ownerRule, spenderRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(TokenApproval) + if err := _Token.contract.UnpackLog(event, "Approval", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseApproval is a log parse operation binding the contract event 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925. +// +// Solidity: event Approval(address indexed owner, address indexed spender, uint256 value) +func (_Token *TokenFilterer) ParseApproval(log types.Log) (*TokenApproval, error) { + event := new(TokenApproval) + if err := _Token.contract.UnpackLog(event, "Approval", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// TokenTransferIterator is returned from FilterTransfer and is used to iterate over the raw logs and unpacked data for Transfer events raised by the Token contract. +type TokenTransferIterator struct { + Event *TokenTransfer // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *TokenTransferIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(TokenTransfer) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(TokenTransfer) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *TokenTransferIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *TokenTransferIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// TokenTransfer represents a Transfer event raised by the Token contract. +type TokenTransfer struct { + From common.Address + To common.Address + Value *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterTransfer is a free log retrieval operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. +// +// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) +func (_Token *TokenFilterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*TokenTransferIterator, error) { + + var fromRule []interface{} + for _, fromItem := range from { + fromRule = append(fromRule, fromItem) + } + var toRule []interface{} + for _, toItem := range to { + toRule = append(toRule, toItem) + } + + logs, sub, err := _Token.contract.FilterLogs(opts, "Transfer", fromRule, toRule) + if err != nil { + return nil, err + } + return &TokenTransferIterator{contract: _Token.contract, event: "Transfer", logs: logs, sub: sub}, nil +} + +// WatchTransfer is a free log subscription operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. +// +// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) +func (_Token *TokenFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *TokenTransfer, from []common.Address, to []common.Address) (event.Subscription, error) { + + var fromRule []interface{} + for _, fromItem := range from { + fromRule = append(fromRule, fromItem) + } + var toRule []interface{} + for _, toItem := range to { + toRule = append(toRule, toItem) + } + + logs, sub, err := _Token.contract.WatchLogs(opts, "Transfer", fromRule, toRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(TokenTransfer) + if err := _Token.contract.UnpackLog(event, "Transfer", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseTransfer is a log parse operation binding the contract event 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef. +// +// Solidity: event Transfer(address indexed from, address indexed to, uint256 value) +func (_Token *TokenFilterer) ParseTransfer(log types.Log) (*TokenTransfer, error) { + event := new(TokenTransfer) + if err := _Token.contract.UnpackLog(event, "Transfer", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} diff --git a/utils/error_types/errors.go b/utils/error_types/errors.go new file mode 100644 index 0000000..b04c6c9 --- /dev/null +++ b/utils/error_types/errors.go @@ -0,0 +1,17 @@ +package error_types + +import "errors" + +var ( + ErrNotFound = errors.New("not found") + ErrInsufficientLiquidity = errors.New("insufficient liquidity") + ErrNativeTokenInsufficient = errors.New("native token insufficient") + ErrPrivateKeyEmpty = errors.New("private key empty") + ErrPrivateKeyNotMatch = errors.New("private key not match") + ErrUnsupportedMultiSign = errors.New("unsupported multi sign") + ErrInsufficientBalance = errors.New("insufficient balance") + ErrUnsupportedTokenAndChain = errors.New("unsupported token and chain") + ErrUnsupportedWalletType = errors.New("unsupported wallet type") + ErrUnsupportedActions = errors.New("unsupported actions") + ErrWalletLocked = errors.New("wallet locked") +) diff --git a/utils/locks/lock.go b/utils/locks/lock.go new file mode 100644 index 0000000..57ee9f1 --- /dev/null +++ b/utils/locks/lock.go @@ -0,0 +1,75 @@ +package locks + +import ( + "context" + "fmt" + "github.com/google/uuid" + "omni-balance/utils" + "strings" + "sync" + "time" +) + +var ( + nameMutexMap = make(map[string]*sync.Mutex) + mutex sync.Mutex +) + +// LockKey generate lock key, if values is empty, generate a random string +func LockKey(values ...any) string { + if len(values) == 0 { + values = append(values, uuid.New().String()) + } + var format []string + for range values { + format = append(format, "%s") + } + return strings.ToLower(fmt.Sprintf(strings.Join(format, "_"), values...)) +} + +func LockWithKey(ctx context.Context, key string, noWait ...bool) bool { + log := utils.GetLogFromCtx(ctx) + tryLock := func() bool { + mutex.Lock() + defer mutex.Unlock() + locker, ok := nameMutexMap[key] + if !ok { + nameMutexMap[key] = &sync.Mutex{} + nameMutexMap[key].Lock() + return true + } + return locker.TryLock() + } + ok := tryLock() + if len(noWait) != 0 && noWait[0] && !ok { + return false + } + if ok { + return true + } + var t = time.NewTicker(time.Second) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return false + case <-t.C: + if tryLock() { + return true + } + if log != nil { + log.Debugf("%s is locked, waiting...", key) + } + } + } +} + +func UnlockWithKey(_ context.Context, key string) { + mutex.Lock() + defer mutex.Unlock() + if _, ok := nameMutexMap[key]; !ok { + nameMutexMap[key] = &sync.Mutex{} + return + } + nameMutexMap[key].Unlock() +} diff --git a/utils/locks/lock_test.go b/utils/locks/lock_test.go new file mode 100644 index 0000000..e3425e8 --- /dev/null +++ b/utils/locks/lock_test.go @@ -0,0 +1,86 @@ +package locks + +import ( + "context" + "testing" +) + +func TestLockKey(t *testing.T) { + type args struct { + values []any + } + tests := []struct { + name string + args args + want string + }{ + { + name: "test1", + args: args{ + values: []any{"test1", "test2"}, + }, + want: "test1_test2", + }, + { + name: "test2", + args: args{ + values: []any{"test1", "test2", "test3"}, + }, + want: "test1_test2_test3", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := LockKey(tt.args.values...); got != tt.want { + t.Errorf("LockKey() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestLockWithKey(t *testing.T) { + type args struct { + ctx context.Context + key string + noWait bool + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "test1", + args: args{ + ctx: context.Background(), + key: "test1", + }, + want: true, + }, + { + name: "noWaitLock", + args: args{ + ctx: context.Background(), + key: "test1", + noWait: true, + }, + want: false, + }, + { + name: "noWaitLock", + args: args{ + ctx: context.Background(), + key: "test1", + noWait: true, + }, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := LockWithKey(tt.args.ctx, tt.args.key, tt.args.noWait); got != tt.want { + t.Errorf("LockWithKey() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/utils/notice/notice.go b/utils/notice/notice.go new file mode 100644 index 0000000..7506ce6 --- /dev/null +++ b/utils/notice/notice.go @@ -0,0 +1,67 @@ +package notice + +import ( + "context" + "encoding/json" + "fmt" + "github.com/patrickmn/go-cache" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + "omni-balance/utils" + "time" +) + +var ( + msg = cache.New(time.Hour, time.Minute) +) + +type Type string + +const ( + SlackNotice Type = "slack" +) + +var ( + notice Notice +) + +type Notice interface { + Send(ctx context.Context, title string, content string, levels ...logrus.Level) error +} + +func Init(noticeType Type, conf map[string]interface{}) error { + if notice != nil { + return nil + } + confData, _ := json.Marshal(conf) + switch noticeType { + case SlackNotice: + s := &Slack{} + if err := json.Unmarshal(confData, s); err != nil { + return errors.Wrap(err, "unmarshal slack config") + } + notice = s + default: + if noticeType != "" { + return errors.Errorf("notice type %s not support", noticeType) + } + } + return nil +} + +func Send(ctx context.Context, title string, content string, levels ...logrus.Level) error { + if notice == nil { + return nil + } + + key := utils.Md5(fmt.Sprintf("%s:%s", title, content)) + if _, ok := msg.Get(key); ok { + logrus.Debugf("notice %s:%s already send, 1 hour later will send again", title, content) + return nil + } + if err := notice.Send(ctx, title, content, levels...); err != nil { + return err + } + msg.SetDefault(key, struct{}{}) + return nil +} diff --git a/utils/notice/slack.go b/utils/notice/slack.go new file mode 100644 index 0000000..f8caf6e --- /dev/null +++ b/utils/notice/slack.go @@ -0,0 +1,82 @@ +package notice + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "github.com/sirupsen/logrus" + "net/http" + "omni-balance/utils" +) + +type Slack struct { + Webhook string `json:"webhook"` + Channel string `json:"channel"` +} + +type body struct { + Channel string `json:"channel"` + Username string `json:"username"` + UnfurlLinks bool `json:"unfurl_links"` + Attachments []Attachment `json:"attachments"` +} + +type Attachment struct { + Fallback string `json:"fallback"` + Color string `json:"color"` + AuthorName string `json:"author_name"` + Fields []Field `json:"fields"` +} +type Field struct { + Title string `json:"title"` + Value string `json:"value"` + Short bool `json:"short"` +} + +func Level2SlackColor(level logrus.Level) string { + switch level { + case logrus.ErrorLevel: + return "danger" + case logrus.WarnLevel: + return "warning" + default: + return "good" + } +} + +func (s *Slack) Send(ctx context.Context, title string, content string, levels ...logrus.Level) error { + var level = logrus.DebugLevel + if len(levels) > 0 { + level = levels[0] + } + b := &body{ + Channel: s.Channel, + Username: "omni-balance", + UnfurlLinks: false, + Attachments: []Attachment{ + { + Fallback: fmt.Sprintf("%s\n%s", title, content), + Color: Level2SlackColor(level), + Fields: []Field{ + { + Title: "title", + Value: title, + Short: true, + }, + { + Title: "message", + Value: content, + Short: true, + }, + }, + }, + }, + } + var bodyBuf = bytes.NewBuffer(nil) + if err := json.NewEncoder(bodyBuf).Encode(b); err != nil { + return err + } + _ = utils.Request(ctx, http.MethodPost, s.Webhook, bodyBuf, nil, "Content-Type", "application/json") + return nil +} diff --git a/utils/provider/bridge/darwinia/abi.go b/utils/provider/bridge/darwinia/abi.go new file mode 100644 index 0000000..e7452a6 --- /dev/null +++ b/utils/provider/bridge/darwinia/abi.go @@ -0,0 +1,376 @@ +package darwinia + +const MSGLINE_MESSAGER = `[ + { + "name": "receiveMessage", + "outputs": [], + "type": "function", + "stateMutability": "nonpayable", + "inputs": [ + { + "internalType": "uint256", + "name": "_srcAppChainId", + "type": "uint256" + }, + { + "internalType": "address", + "name": "_remoteAppAddress", + "type": "address" + }, + { + "internalType": "address", + "name": "_localAppAddress", + "type": "address" + }, + { + "internalType": "bytes", + "name": "_message", + "type": "bytes" + } + ] + } +]` + +const XTOKEN_ISSUING_NEXT = `[ + { + "inputs": [ + { + "internalType": "uint256", + "name": "_remoteChainId", + "type": "uint256" + }, + { + "internalType": "address", + "name": "_originalToken", + "type": "address" + }, + { + "internalType": "address", + "name": "_originalSender", + "type": "address" + }, + { + "internalType": "address", + "name": "_recipient", + "type": "address" + }, + { + "internalType": "address", + "name": "_rollbackAccount", + "type": "address" + }, + { + "internalType": "uint256", + "name": "_amount", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "_nonce", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "_extData", + "type": "bytes" + } + ], + "name": "issue", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_xToken", + "type": "address" + }, + { + "internalType": "address", + "name": "_recipient", + "type": "address" + }, + { + "internalType": "address", + "name": "_rollbackAccount", + "type": "address" + }, + { + "internalType": "uint256", + "name": "_amount", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "_nonce", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "_extData", + "type": "bytes" + }, + { + "internalType": "bytes", + "name": "_extParams", + "type": "bytes" + } + ], + "name": "burnAndXUnlock", + "outputs": [ + { + "internalType": "bytes32", + "name": "transferId", + "type": "bytes32" + } + ], + "stateMutability": "payable", + "type": "function" + } +]` + +const XTOKEN_BACKING_NEXT = `[ + { + "inputs": [ + { + "internalType": "uint256", + "name": "_remoteChainId", + "type": "uint256" + }, + { + "internalType": "address", + "name": "_originalToken", + "type": "address" + }, + { + "internalType": "address", + "name": "_recipient", + "type": "address" + }, + { + "internalType": "address", + "name": "_rollbackAccount", + "type": "address" + }, + { + "internalType": "uint256", + "name": "_amount", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "_nonce", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "_extData", + "type": "bytes" + }, + { + "internalType": "bytes", + "name": "_extParams", + "type": "bytes" + } + ], + "name": "lockAndXIssue", + "outputs": [ + { + "internalType": "bytes32", + "name": "transferId", + "type": "bytes32" + } + ], + "stateMutability": "payable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "_remoteChainId", + "type": "uint256" + }, + { + "internalType": "address", + "name": "_originalToken", + "type": "address" + }, + { + "internalType": "address", + "name": "_originSender", + "type": "address" + }, + { + "internalType": "address", + "name": "_recipient", + "type": "address" + }, + { + "internalType": "address", + "name": "_rollbackAccount", + "type": "address" + }, + { + "internalType": "uint256", + "name": "_amount", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "_nonce", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "_extData", + "type": "bytes" + } + ], + "name": "unlock", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } +]` + +const WTOKEN_CONVERTOR = `[ + { + "inputs": [ + { + "internalType": "uint256", + "name": "_remoteChainId", + "type": "uint256" + }, + { + "internalType": "address", + "name": "_recipient", + "type": "address" + }, + { + "internalType": "address", + "name": "_rollbackAccount", + "type": "address" + }, + { + "internalType": "uint256", + "name": "_amount", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "_nonce", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "_extData", + "type": "bytes" + }, + { + "internalType": "bytes", + "name": "_extParams", + "type": "bytes" + } + ], + "name": "lockAndXIssue", + "outputs": [], + "stateMutability": "payable", + "type": "function" + } +]` + +const XTOKEN_CONVERTOR = `[{ + "inputs": [ + { + "internalType": "address", + "name": "_recipient", + "type": "address" + }, + { + "internalType": "address", + "name": "_rollbackAccount", + "type": "address" + }, + { + "internalType": "uint256", + "name": "_amount", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "_nonce", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "_extData", + "type": "bytes" + }, + { + "internalType": "bytes", + "name": "_extParams", + "type": "bytes" + } + ], + "name": "burnAndXUnlock", + "outputs": [], + "stateMutability": "payable", + "type": "function" +}]` + +const ERC20_ABI = `[ + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "_spender", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "value", + "type": "uint256" + } + ], + "outputs": [ + { + "internalType": "bool", + "name": "success", + "type": "bool" + } + ], + "name": "approve", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "internalType": "address", + "name": "spender", + "type": "address" + } + ], + "name": "allowance", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + } + +]` diff --git a/utils/provider/bridge/darwinia/consts.go b/utils/provider/bridge/darwinia/consts.go new file mode 100644 index 0000000..691bdff --- /dev/null +++ b/utils/provider/bridge/darwinia/consts.go @@ -0,0 +1,77 @@ +package darwinia + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "strings" +) + +type SwapFunc func(ctx context.Context, args SwapParams) (tx *types.LegacyTx, err error) + +var ( + SUPPORT_TOKENS = []supportToken{ + {Config: crab2darwinia, Fn: Crab2Darwinia}, + {Config: darwinia2Crab, Fn: Darwinia2Crab}, + {Config: darwinia2ethereum, Fn: Darwinia2ethereum}, + {Config: ethereum2darwinia, Fn: Ethereum2darwinia}, + } + SUPPORTS = make(map[int64]map[int64]map[string]struct{}) + BRIDGE_DIRECTION = make(map[int64]map[int64]SwapFunc) +) + +type supportToken struct { + Config map[string]Params + Fn func(ctx context.Context, args SwapParams) (tx *types.LegacyTx, err error) +} + +type Params struct { + TokenAddress common.Address + contractAddress common.Address + remoteAppAddress common.Address + localAppAddress common.Address + xTokenAddress common.Address + recipient common.Address + sourceMessager common.Address + targetMessager common.Address + originalToken common.Address + sourceChainId int64 + targetChainId int64 + extData string +} + +func init() { + for _, supportTokens := range SUPPORT_TOKENS { + for tokenName, params := range supportTokens.Config { + if _, ok := BRIDGE_DIRECTION[params.sourceChainId]; !ok { + BRIDGE_DIRECTION[params.sourceChainId] = make(map[int64]SwapFunc) + } + if _, ok := BRIDGE_DIRECTION[params.sourceChainId][params.targetChainId]; !ok { + BRIDGE_DIRECTION[params.sourceChainId][params.targetChainId] = supportTokens.Fn + } + if _, ok := SUPPORTS[params.sourceChainId]; !ok { + SUPPORTS[params.sourceChainId] = make(map[int64]map[string]struct{}) + } + + if _, ok := SUPPORTS[params.sourceChainId][params.targetChainId]; !ok { + SUPPORTS[params.sourceChainId][params.targetChainId] = make(map[string]struct{}, 0) + } + + SUPPORTS[params.sourceChainId][params.targetChainId][tokenName] = struct{}{} + } + } +} + +func GetSourceChains(targetChainId int64, TokenName string) (sourceChainIds []int64) { + TokenName = strings.ToUpper(TokenName) + for sourceChainId := range SUPPORTS { + if _, ok := SUPPORTS[sourceChainId][targetChainId]; !ok { + continue + } + if _, ok := SUPPORTS[sourceChainId][targetChainId][TokenName]; !ok { + continue + } + sourceChainIds = append(sourceChainIds, sourceChainId) + } + return sourceChainIds +} diff --git a/utils/provider/bridge/darwinia/crab2darwinia.go b/utils/provider/bridge/darwinia/crab2darwinia.go new file mode 100644 index 0000000..b5bb0de --- /dev/null +++ b/utils/provider/bridge/darwinia/crab2darwinia.go @@ -0,0 +1,122 @@ +package darwinia + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "omni-balance/utils/constant" + "strings" +) + +var ( + crab2darwinia = map[string]Params{ + "RING": Params{ + contractAddress: common.HexToAddress("0xf6372ab2d35B32156A19F2d2F23FA6dDeFBE58bd"), + originalToken: common.HexToAddress("0xE7578598Aac020abFB918f33A20faD5B71d670b4"), + remoteAppAddress: common.HexToAddress("0xf6372ab2d35B32156A19F2d2F23FA6dDeFBE58bd"), + localAppAddress: common.HexToAddress("0xa64D1c284280b22f921E7B2A55040C7bbfD4d9d0"), + sourceMessager: common.HexToAddress("0x65Be094765731F394bc6d9DF53bDF3376F1Fc8B0"), + targetMessager: common.HexToAddress("0x65Be094765731F394bc6d9DF53bDF3376F1Fc8B0"), + xTokenAddress: common.HexToAddress("0x273131F7CB50ac002BDd08cA721988731F7e1092"), + recipient: common.HexToAddress("0xA8d0E9a45249Ec839C397fa0F371f5F64eCAB7F7"), + sourceChainId: 44, + targetChainId: 46, + }, + "CRAB": Params{ + contractAddress: common.HexToAddress("0x004D0dE211BC148c3Ce696C51Cbc85BD421727E9"), + originalToken: common.HexToAddress("0x2D2b97EA380b0185e9fDF8271d1AFB5d2Bf18329"), + remoteAppAddress: common.HexToAddress("0xa64D1c284280b22f921E7B2A55040C7bbfD4d9d0"), + localAppAddress: common.HexToAddress("0xf6372ab2d35B32156A19F2d2F23FA6dDeFBE58bd"), + sourceMessager: common.HexToAddress("0x65Be094765731F394bc6d9DF53bDF3376F1Fc8B0"), + targetMessager: common.HexToAddress("0x65Be094765731F394bc6d9DF53bDF3376F1Fc8B0"), + sourceChainId: 44, + targetChainId: 46, + }, + } +) + +func Crab2Darwinia(ctx context.Context, args SwapParams) (tx *types.LegacyTx, err error) { + conf := crab2darwinia[strings.ToUpper(args.TokenName)] + if conf.sourceChainId == 0 { + return nil, errors.Errorf("not support token %s", args.TokenName) + } + var ( + data []byte + isNativeToken = strings.EqualFold(args.TokenName, "CRAB") + wallet = args.Sender + realWallet = wallet.GetAddress(true) + ) + if !isNativeToken { + if !constant.IsTestCtx(ctx) { + + if err := approve(ctx, conf.sourceChainId, conf.TokenAddress, conf.localAppAddress, wallet, + args.Amount.Mul(decimal.NewFromInt(2)), args.Client); err != nil { + + return nil, errors.Wrap(err, "approve") + } + } + + data, err = Unlock( + conf.sourceChainId, + conf.originalToken, + realWallet, + conf.recipient, + realWallet, + args.Amount, + args.Nonce, + realWallet.Bytes(), + ) + if err != nil { + return nil, errors.Wrap(err, "unlock") + } + } + if isNativeToken { + data, err = Issue( + conf.sourceChainId, + conf.originalToken, + conf.contractAddress, + realWallet, + realWallet, + args.Amount, + args.Nonce, + []byte("")) + if err != nil { + return nil, errors.Wrap(err, "issue") + } + } + data, err = ReceiveMessage(conf.sourceChainId, conf.remoteAppAddress, conf.localAppAddress, common.Bytes2Hex(data)) + if err != nil { + return nil, errors.Wrap(err, "receiveMessage") + } + fee, param, gas, err := FetchMsglineFeeAndParams(ctx, conf.sourceChainId, conf.targetChainId, conf.sourceMessager, + conf.targetMessager, wallet.GetAddress(true), common.Bytes2Hex(data)) + if err != nil { + return nil, errors.Wrap(err, "fetchMsglineFeeAndParams") + } + if isNativeToken { + data, err = WTokenLockAndXIssue(conf.targetChainId, + wallet.GetAddress(true), wallet.GetAddress(true), args.Amount, args.Nonce, "", common.Bytes2Hex(param)) + if err != nil { + return nil, errors.Wrap(err, "wTokenLockAndXIssue") + } + } + if !isNativeToken { + data, err = BurnAndXUnlock(conf.xTokenAddress, conf.recipient, realWallet, args.Amount, args.Nonce, realWallet.Bytes(), param) + if err != nil { + return nil, errors.Wrap(err, "burnAndXUnlock") + } + } + + a := &types.LegacyTx{ + To: &conf.contractAddress, + Value: args.Amount.Add(fee).BigInt(), + Data: data, + Gas: uint64(gas.IntPart()), + } + if !isNativeToken { + a.Value = fee.BigInt() + } + return a, nil +} diff --git a/utils/provider/bridge/darwinia/crab2darwinia_test.go b/utils/provider/bridge/darwinia/crab2darwinia_test.go new file mode 100644 index 0000000..be522d6 --- /dev/null +++ b/utils/provider/bridge/darwinia/crab2darwinia_test.go @@ -0,0 +1,38 @@ +package darwinia + +import ( + "github.com/ethereum/go-ethereum/common" + "github.com/shopspring/decimal" + "github.com/stretchr/testify/assert" + "omni-balance/utils" + "omni-balance/utils/chains" + "testing" +) + +func TestCrab2Darwinia(t *testing.T) { + var ( + args = InitVar(t) + amount = decimal.NewFromBigInt(chains.EthToWei(decimal.RequireFromString("0")), 0) + ) + tx, err := Crab2Darwinia(args.ctx, SwapParams{ + Sender: args.sender, + TokenName: "CRAB", + Amount: amount, + Nonce: 1716966768607, + Client: args.client, + }) + assert.NoError(t, err) + utils.AssertEqualFold(t, common.Bytes2Hex(tx.Data), "7104aad5000000000000000000000000000000000000000000000000000000000000002e00000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018fc331bfdf00000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000005463200000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000000") + assert.Equal(t, tx.To.Hex(), "0x004D0dE211BC148c3Ce696C51Cbc85BD421727E9") + + tx, err = Crab2Darwinia(args.ctx, SwapParams{ + Sender: args.sender, + TokenName: "RING", + Amount: amount, + Nonce: 1716966714726, + Client: args.client, + }) + assert.NoError(t, err) + utils.AssertEqualFold(t, common.Bytes2Hex(tx.Data), "57bf0985000000000000000000000000273131f7cb50ac002bdd08ca721988731f7e1092000000000000000000000000a8d0e9a45249ec839c397fa0f371f5f64ecab7f700000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018fc330ed6600000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000001443ef13e84d9992d1461a1f90cac4653658cea4fd000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000552da00000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000000") + assert.Equal(t, tx.To.Hex(), "0xf6372ab2d35B32156A19F2d2F23FA6dDeFBE58bd") +} diff --git a/utils/provider/bridge/darwinia/darwinia.go b/utils/provider/bridge/darwinia/darwinia.go new file mode 100644 index 0000000..8a51242 --- /dev/null +++ b/utils/provider/bridge/darwinia/darwinia.go @@ -0,0 +1,310 @@ +package darwinia + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethclient/simulated" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "omni-balance/utils" + "omni-balance/utils/chains" + "omni-balance/utils/configs" + "omni-balance/utils/constant" + "omni-balance/utils/error_types" + "omni-balance/utils/provider" + "omni-balance/utils/wallets" + "strings" + "time" +) + +var ( + // action + sourceChainSendingAction = "sourceChainSending" + sourceChainWaitAction = "sourceChainWait" + targetChainSendingAction = "targetChainSending" + targetChainReceivedAction = "targetChainReceived" +) + +func Action2Int(action string) int { + switch action { + case sourceChainSendingAction: + return 1 + case sourceChainWaitAction: + return 2 + case targetChainSendingAction: + return 3 + case targetChainReceivedAction: + return 4 + default: + return 0 + } +} + +type Bridge struct { + config configs.Config +} + +var graphOlQuery = "query GetHistory($sender: String, $page: Int, $row: Int) {\n historyRecords(sender: $sender, page: $page, row: $row) {\n total\n records {\n requestTxHash\n responseTxHash\n fromChain\n toChain\n startTime\n sendToken\n sendAmount\n result\n id\n __typename\n }\n __typename\n }\n}" + +type SwapParams struct { + Sender wallets.Wallets + TokenName string + Amount decimal.Decimal + Nonce int64 + Client simulated.Client +} + +type GraphQLRequest struct { + OperationName string `json:"operationName"` + Variables map[string]interface{} `json:"variables"` + Query string `json:"query"` +} + +type HistoryRecordResponse struct { + Data struct { + HistoryRecords struct { + Total int `json:"total"` + Records []HistoryRecord `json:"records"` + Typename string `json:"__typename"` + } `json:"historyRecords"` + } `json:"data"` +} + +type HistoryRecord struct { + RequestTxHash string `json:"requestTxHash"` + ResponseTxHash string `json:"responseTxHash"` + FromChain string `json:"fromChain"` + ToChain string `json:"toChain"` + StartTime int `json:"startTime"` + SendToken string `json:"sendToken"` + SendAmount string `json:"sendAmount"` + Result int `json:"result"` + Id string `json:"id"` + Typename string `json:"__typename"` +} + +func New(conf configs.Config, noInit ...bool) (provider.Provider, error) { + if len(noInit) > 0 && noInit[0] { + return &Bridge{}, nil + } + d := &Bridge{ + config: conf, + } + return d, nil +} + +func (b *Bridge) CheckToken(ctx context.Context, tokenName, tokenInChainName, tokenOutChainName string, + amount decimal.Decimal) (bool, error) { + + sourceChains := GetSourceChains(int64(constant.GetChainId(tokenInChainName)), tokenName) + if len(sourceChains) == 0 { + return false, nil + } + return utils.InArray(int64(constant.GetChainId(tokenInChainName)), sourceChains), nil +} + +func (b *Bridge) GetCost(ctx context.Context, args provider.SwapParams) (provider.TokenInCosts, error) { + if args.TargetToken == "" || args.TargetChain == "" { + return nil, errors.Errorf("target token or target chain is empty") + } + if args.SourceChain == "" { + sourceChains := b.FindValidSourceChains(ctx, constant.GetChainId(args.TargetChain), args.TargetToken, + args.Sender.GetAddress(true).Hex(), args.Amount) + if len(sourceChains) == 0 { + return nil, error_types.ErrUnsupportedTokenAndChain + } + args.SourceChain = constant.GetChainName(utils.Choose(sourceChains)) + } + + if args.SourceToken == "" { + args.SourceToken = b.config.GetTokenInfoOnChain(args.TargetToken, args.SourceChain).Name + } + + return provider.TokenInCosts{ + { + TokenName: args.SourceToken, + CostAmount: args.Amount, + }, + }, nil +} + +func (b *Bridge) Swap(ctx context.Context, args provider.SwapParams) (result provider.SwapResult, err error) { + var ( + history = args.LastHistory + log = args.GetLogs("darwinia") + recordFn = func(s provider.SwapHistory, errs ...error) { + s.ProviderType = string(b.Type()) + s.ProviderName = b.Name() + s.Amount = args.Amount + if args.RecordFn == nil { + return + } + args.RecordFn(s, errs...) + } + ) + if history.Actions == targetChainReceivedAction && history.Status == string(provider.TxStatusSuccess) { + log.Debugf("target chain received, order id: %s", history.Tx) + return provider.SwapResult{ + ProviderType: b.Type(), + ProviderName: b.Name(), + OrderId: history.Tx, + Status: provider.TxStatusSuccess, + CurrentChain: args.TargetChain, + Tx: history.Tx, + }, nil + } + if args.SourceChain == args.TargetChain && history.Status == string(provider.TxStatusSuccess) { + log.Debugf("source chain %s and target chain %s is same", args.SourceChain, args.TargetChain) + return provider.SwapResult{}, errors.Errorf("source chain %s and target chain %s is same", args.SourceChain, args.TargetChain) + } + if history.CurrentChain != "" && history.CurrentChain != args.TargetChain { + args.SourceChain = history.CurrentChain + } + actionNumber := Action2Int(history.Actions) + ctx = context.WithValue(ctx, constant.ChainNameKeyInCtx, args.SourceChain) + if actionNumber == 0 && args.SourceChain == "" { + validSourceChain := b.GetValidSourceChain(ctx, constant.GetChainId(args.TargetChain), + args.TargetToken, args.Sender.GetAddress(true).Hex(), args.Amount) + if validSourceChain == 0 { + return result, errors.Errorf("can not find source chain for %s %s", args.TargetToken, args.TargetChain) + } + args.SourceChain = constant.GetChainName(validSourceChain) + } + var sourceChainConf = b.config.GetChainConfig(args.SourceChain) + if args.SourceToken == "" { + args.SourceToken = b.config.GetTokenInfoOnChain(args.TargetToken, args.SourceChain).Name + } + sourceToken := b.config.GetTokenInfoOnChain(args.SourceToken, args.SourceChain) + + targetChainConf := b.config.GetChainConfig(args.TargetChain) + + fn := BRIDGE_DIRECTION[int64(sourceChainConf.Id)][int64(targetChainConf.Id)] + if fn == nil { + return result, errors.Errorf("not support swap %s to %s", args.SourceChain, args.TargetChain) + } + wallet := args.Sender + ethClient, err := chains.NewTryClient(ctx, sourceChainConf.RpcEndpoints) + if err != nil { + return result, errors.Wrap(err, "dial rpc") + } + defer ethClient.Close() + log.Debugf("start transfer %s from %s to %s", args.SourceToken, args.SourceChain, args.TargetChain) + tx, err := fn(ctx, SwapParams{ + Sender: wallet, + TokenName: args.SourceToken, + Amount: decimal.NewFromBigInt(chains.EthToWei(args.Amount, sourceToken.Decimals), 0), + Nonce: time.Now().UnixMilli(), + Client: ethClient, + }) + if err != nil { + return result, errors.Wrap(err, "swap") + } + + if tx.Gas != 0 { + tx.Gas = tx.Gas * 2 + } + + sr := &provider.SwapResult{ + TokenInName: args.SourceToken, + ProviderType: configs.Bridge, + ProviderName: b.Name(), + Status: provider.TxStatusPending, + CurrentChain: args.SourceChain, + } + + if actionNumber <= 1 && history.Status != string(provider.TxStatusSuccess) { + recordFn(provider.SwapHistory{Actions: sourceChainSendingAction, Status: string(provider.TxStatusPending), + CurrentChain: args.SourceChain}) + txHash, err := args.Sender.SendTransaction(ctx, tx, ethClient) + if err != nil { + recordFn(provider.SwapHistory{Actions: sourceChainSendingAction, Status: string(provider.TxStatusFailed), + CurrentChain: args.SourceChain}, err) + return result, errors.Wrap(err, "send signed transaction") + } + recordFn(provider.SwapHistory{Actions: sourceChainSendingAction, Status: string(provider.TxStatusSuccess), + CurrentChain: args.SourceChain, Tx: txHash.Hex()}) + sr.Tx = txHash.Hex() + sr.OrderId = sr.Tx + } + + if actionNumber <= 2 && history.Status != string(provider.TxStatusSuccess) { + if sr.Tx == "" { + sr.Tx = history.Tx + } + recordFn(provider.SwapHistory{Actions: sourceChainWaitAction, Status: string(provider.TxStatusPending), + CurrentChain: args.SourceChain, Tx: sr.Tx}) + err = wallet.WaitTransaction(ctx, common.HexToHash(sr.Tx), ethClient) + if err != nil && strings.Contains(err.Error(), "tx failed") { + recordFn(provider.SwapHistory{Actions: sourceChainWaitAction, Status: string(provider.TxStatusFailed), + CurrentChain: args.SourceChain, Tx: sr.Tx}, err) + return result, err + } + if err != nil { + recordFn(provider.SwapHistory{Actions: sourceChainWaitAction, Status: string(provider.TxStatusPending), + CurrentChain: args.SourceChain, Amount: args.Amount, Tx: sr.Tx}, err) + return result, errors.Wrap(err, "wait for tx") + } + recordFn(provider.SwapHistory{Actions: sourceChainWaitAction, Status: string(provider.TxStatusSuccess), + CurrentChain: args.SourceChain, Tx: sr.Tx}) + } + + if actionNumber <= 4 && history.Status != string(provider.TxStatusSuccess) { + if sr.Tx == "" { + sr.Tx = history.Tx + } + recordFn(provider.SwapHistory{Actions: targetChainSendingAction, Status: string(provider.TxStatusPending), + CurrentChain: args.SourceChain, Tx: sr.Tx}) + log.Debugf("waiting for bridge success") + record, err := b.WaitForBridgeSuccess(ctx, sr.Tx, args.Sender.GetAddress(true).Hex()) + if err != nil { + recordFn(provider.SwapHistory{Actions: targetChainSendingAction, Status: string(provider.TxStatusFailed), + CurrentChain: args.SourceChain, Tx: sr.Tx}, err) + return *sr, errors.Wrap(err, "wait for bridge success") + } + sr.Order = record + + if record.Result == 3 { + recordFn(provider.SwapHistory{Actions: targetChainReceivedAction, Status: string(provider.TxStatusSuccess), + CurrentChain: args.TargetChain, Tx: sr.Tx}) + sr.Status = provider.TxStatusSuccess + sr.CurrentChain = args.TargetChain + } + if record.Result != 3 { + log.Debugf("bridge failed: %+v", record) + recordFn(provider.SwapHistory{Actions: targetChainReceivedAction, + Status: string(provider.TxStatusFailed), CurrentChain: args.SourceChain, Tx: sr.Tx}, + errors.Errorf("bridge failed: %d", record.Result)) + sr.Status = provider.TxStatusFailed + } + } + + return *sr, nil +} + +func (b *Bridge) Check(ctx context.Context, args provider.CheckParams) (bool, error) { + if args.Chain == "" { + return false, errors.Errorf("target chain is empty") + } + if err := b.config.GetWallet(args.Wallet).CheckFullAccess(ctx); err != nil { + return false, errors.Wrap(err, "check full access") + } + + targetChain := b.config.GetChainConfig(args.Chain) + sourceChains := b.FindValidSourceChains(ctx, targetChain.Id, args.Token, args.Wallet, args.Amount) + if len(sourceChains) == 0 { + return false, nil + } + return true, nil +} + +func (b *Bridge) Help() []string { + return []string{"See https://bridge.darwinia.network"} +} + +func (b *Bridge) Name() string { + return "darwinia-bridge" +} + +func (b *Bridge) Type() configs.LiquidityProviderType { + return configs.Bridge +} diff --git a/utils/provider/bridge/darwinia/darwinia2crab.go b/utils/provider/bridge/darwinia/darwinia2crab.go new file mode 100644 index 0000000..117320b --- /dev/null +++ b/utils/provider/bridge/darwinia/darwinia2crab.go @@ -0,0 +1,117 @@ +package darwinia + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "omni-balance/utils" + "omni-balance/utils/constant" + "strings" +) + +var ( + darwinia2Crab = map[string]Params{ + "RING": Params{ + contractAddress: common.HexToAddress("0xA8d0E9a45249Ec839C397fa0F371f5F64eCAB7F7"), + originalToken: common.HexToAddress("0xE7578598Aac020abFB918f33A20faD5B71d670b4"), + remoteAppAddress: common.HexToAddress("0xa64D1c284280b22f921E7B2A55040C7bbfD4d9d0"), + localAppAddress: common.HexToAddress("0xf6372ab2d35B32156A19F2d2F23FA6dDeFBE58bd"), + sourceMessager: common.HexToAddress("0x65Be094765731F394bc6d9DF53bDF3376F1Fc8B0"), + targetMessager: common.HexToAddress("0x65Be094765731F394bc6d9DF53bDF3376F1Fc8B0"), + sourceChainId: 46, + targetChainId: 44, + }, + "CRAB": Params{ + TokenAddress: common.HexToAddress("0x656567eb75b765fc320783cc6edd86bd854b2305"), + contractAddress: common.HexToAddress(""), + originalToken: common.HexToAddress("0x2D2b97EA380b0185e9fDF8271d1AFB5d2Bf18329"), + remoteAppAddress: common.HexToAddress("0xf6372ab2d35B32156A19F2d2F23FA6dDeFBE58bd"), + localAppAddress: common.HexToAddress("0xa64D1c284280b22f921E7B2A55040C7bbfD4d9d0"), + sourceMessager: common.HexToAddress("0x65Be094765731F394bc6d9DF53bDF3376F1Fc8B0"), + targetMessager: common.HexToAddress("0x65Be094765731F394bc6d9DF53bDF3376F1Fc8B0"), + xTokenAddress: common.HexToAddress("0x656567Eb75b765FC320783cc6EDd86bD854b2305"), + recipient: common.HexToAddress("0x004D0dE211BC148c3Ce696C51Cbc85BD421727E9"), + sourceChainId: 46, + targetChainId: 44, + }, + } +) + +func Darwinia2Crab(ctx context.Context, args SwapParams) (tx *types.LegacyTx, err error) { + tokenConf := darwinia2Crab[strings.ToUpper(args.TokenName)] + if tokenConf.sourceChainId == 0 { + return nil, errors.Errorf("not support token %s", args.TokenName) + } + var ( + data []byte + isNativeToken = utils.InArray(args.TokenName, []string{"RING"}) + wallet = args.Sender + realWallet = wallet.GetAddress(true) + ) + if !isNativeToken { + if !constant.IsTestCtx(ctx) { + if err := approve(ctx, tokenConf.sourceChainId, tokenConf.TokenAddress, + tokenConf.remoteAppAddress, wallet, args.Amount.Mul(decimal.NewFromInt(2)), args.Client); err != nil { + return nil, errors.Wrap(err, "approve") + } + } + data, err = Unlock( + tokenConf.sourceChainId, + tokenConf.originalToken, + realWallet, + tokenConf.recipient, + realWallet, + args.Amount, + args.Nonce, + realWallet.Bytes(), + ) + if err != nil { + return nil, errors.Wrap(err, "unlock") + } + } + if isNativeToken { + data, err = Issue( + tokenConf.sourceChainId, tokenConf.originalToken, tokenConf.contractAddress, + realWallet, realWallet, args.Amount, args.Nonce, []byte("")) + if err != nil { + return nil, errors.Wrap(err, "issue") + } + } + + data, err = ReceiveMessage(tokenConf.sourceChainId, tokenConf.remoteAppAddress, tokenConf.localAppAddress, common.Bytes2Hex(data)) + if err != nil { + return nil, errors.Wrap(err, "receiveMessage") + } + fee, param, gas, err := FetchMsglineFeeAndParams(ctx, tokenConf.sourceChainId, tokenConf.targetChainId, + tokenConf.sourceMessager, tokenConf.targetMessager, realWallet, common.Bytes2Hex(data)) + if err != nil { + return nil, errors.Wrap(err, "fetchMsglineFeeAndParams") + } + if isNativeToken { + data, err = WTokenLockAndXIssue(tokenConf.targetChainId, realWallet, realWallet, args.Amount, + args.Nonce, "", common.Bytes2Hex(param)) + if err != nil { + return nil, errors.Wrap(err, "wTokenLockAndXIssue") + } + } + if !isNativeToken { + data, err = BurnAndXUnlock(tokenConf.xTokenAddress, tokenConf.recipient, realWallet, args.Amount, + args.Nonce, realWallet.Bytes(), param) + if err != nil { + return nil, errors.Wrap(err, "burnAndXUnlock") + } + } + a := &types.LegacyTx{ + To: &tokenConf.contractAddress, + Value: args.Amount.Add(fee).BigInt(), + Data: data, + Gas: uint64(gas.IntPart()), + } + if !isNativeToken { + a.Value = fee.BigInt() + a.To = &tokenConf.remoteAppAddress + } + return a, nil +} diff --git a/utils/provider/bridge/darwinia/darwinia2crab_test.go b/utils/provider/bridge/darwinia/darwinia2crab_test.go new file mode 100644 index 0000000..685876b --- /dev/null +++ b/utils/provider/bridge/darwinia/darwinia2crab_test.go @@ -0,0 +1,38 @@ +package darwinia + +import ( + "github.com/ethereum/go-ethereum/common" + "github.com/shopspring/decimal" + "github.com/stretchr/testify/assert" + "omni-balance/utils" + "omni-balance/utils/chains" + "testing" +) + +func TestDarwinia2Crab(t *testing.T) { + var ( + args = InitVar(t) + amount = decimal.NewFromBigInt(chains.EthToWei(decimal.RequireFromString("0")), 0) + ) + tx, err := Darwinia2Crab(args.ctx, SwapParams{ + Sender: args.sender, + TokenName: "RING", + Amount: amount, + Nonce: 1716966591656, + Client: args.client, + }) + assert.NoError(t, err) + utils.AssertEqualFold(t, common.Bytes2Hex(tx.Data), "7104aad5000000000000000000000000000000000000000000000000000000000000002c00000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018fc32f0ca800000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000003f4a600000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000000") + assert.Equal(t, tx.To.Hex(), "0xA8d0E9a45249Ec839C397fa0F371f5F64eCAB7F7") + + tx, err = Darwinia2Crab(args.ctx, SwapParams{ + Sender: args.sender, + TokenName: "CRAB", + Amount: amount, + Nonce: 1716966643973, + Client: args.client, + }) + assert.NoError(t, err) + utils.AssertEqualFold(t, common.Bytes2Hex(tx.Data), "57bf0985000000000000000000000000656567eb75b765fc320783cc6edd86bd854b2305000000000000000000000000004d0de211bc148c3ce696c51cbc85bd421727e900000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018fc32fd90500000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000001443ef13e84d9992d1461a1f90cac4653658cea4fd0000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000003f80f00000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000000") + assert.Equal(t, tx.To.Hex(), "0xf6372ab2d35B32156A19F2d2F23FA6dDeFBE58bd") +} diff --git a/utils/provider/bridge/darwinia/darwinia2ethereum.go b/utils/provider/bridge/darwinia/darwinia2ethereum.go new file mode 100644 index 0000000..1e9fbf7 --- /dev/null +++ b/utils/provider/bridge/darwinia/darwinia2ethereum.go @@ -0,0 +1,112 @@ +package darwinia + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "omni-balance/utils/constant" + "strings" +) + +var ( + darwinia2ethereum = map[string]Params{ + "RING": Params{ + contractAddress: common.HexToAddress("0x092e19c46c9daab7824393f1cd9c22f5bea13560"), + originalToken: common.HexToAddress("0xE7578598Aac020abFB918f33A20faD5B71d670b4"), + recipient: common.HexToAddress("0x4CA75992d2750BEC270731A72DfDedE6b9E71cC7"), + remoteAppAddress: common.HexToAddress("0x2B496f19A420C02490dB859fefeCCD71eDc2c046"), + localAppAddress: common.HexToAddress("0xDc0C760c0fB4672D06088515F6446a71Df0c64C1"), + sourceMessager: common.HexToAddress("0x65Be094765731F394bc6d9DF53bDF3376F1Fc8B0"), + targetMessager: common.HexToAddress("0x65Be094765731F394bc6d9DF53bDF3376F1Fc8B0"), + sourceChainId: 46, + targetChainId: 1, + extData: "000000000000000000000000c29dcb1f12a1618262ef9fba673b77140adc02d600000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000014{sender}000000000000000000000000", + }, + "KTON": Params{ + TokenAddress: common.HexToAddress("0x0000000000000000000000000000000000000402"), + contractAddress: common.Address{}, // must replace to sender address + originalToken: common.HexToAddress("0x0000000000000000000000000000000000000402"), + remoteAppAddress: common.HexToAddress("0x2B496f19A420C02490dB859fefeCCD71eDc2c046"), + localAppAddress: common.HexToAddress("0xDc0C760c0fB4672D06088515F6446a71Df0c64C1"), + sourceMessager: common.HexToAddress("0x65Be094765731F394bc6d9DF53bDF3376F1Fc8B0"), + targetMessager: common.HexToAddress("0x65Be094765731F394bc6d9DF53bDF3376F1Fc8B0"), + recipient: common.HexToAddress("0x4CA75992d2750BEC270731A72DfDedE6b9E71cC7"), + sourceChainId: 46, + targetChainId: 1, + extData: "000000000000000000000000{sender}00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000", + }, + } +) + +func Darwinia2ethereum(ctx context.Context, args SwapParams) (tx *types.LegacyTx, err error) { + tokenConf := darwinia2ethereum[strings.ToUpper(args.TokenName)] + if tokenConf.sourceChainId == 0 { + return nil, errors.Errorf("not support token %s", args.TokenName) + } + var ( + data []byte + isNativeToken = strings.EqualFold(args.TokenName, "RING") + wallet = args.Sender + realWallet = wallet.GetAddress(true) + ) + if !isNativeToken && !constant.IsTestCtx(ctx) { + if err := approve(ctx, tokenConf.sourceChainId, tokenConf.TokenAddress, tokenConf.localAppAddress, + wallet, args.Amount.Mul(decimal.NewFromInt(2)), args.Client); err != nil { + return nil, errors.Wrap(err, "approve") + } + } + + contractAddress := tokenConf.contractAddress + if strings.EqualFold(contractAddress.Hex(), constant.ZeroAddress.Hex()) { + contractAddress = realWallet + } + extData := common.Hex2Bytes(ReplaceExtData(tokenConf.extData, realWallet.Hex())) + data, err = Issue( + tokenConf.sourceChainId, tokenConf.originalToken, contractAddress, tokenConf.recipient, + realWallet, args.Amount, args.Nonce, extData) + if err != nil { + return nil, errors.Wrap(err, "issue") + } + + data, err = ReceiveMessage(tokenConf.sourceChainId, tokenConf.remoteAppAddress, tokenConf.localAppAddress, + common.Bytes2Hex(data)) + if err != nil { + return nil, errors.Wrap(err, "receiveMessage") + } + + fee, param, gas, err := FetchMsglineFeeAndParams(ctx, tokenConf.sourceChainId, tokenConf.targetChainId, + tokenConf.sourceMessager, tokenConf.targetMessager, realWallet, common.Bytes2Hex(data)) + if err != nil { + return nil, errors.Wrap(err, "fetchMsglineFeeAndParams") + } + + if isNativeToken { + data, err = WTokenLockAndXIssue(tokenConf.targetChainId, tokenConf.recipient, realWallet, + args.Amount, args.Nonce, common.Bytes2Hex(extData), common.Bytes2Hex(param)) + if err != nil { + return nil, errors.Wrap(err, "wTokenLockAndXIssue") + } + } + if !isNativeToken { + data, err = XTokenLockAndXIssue(tokenConf.targetChainId, tokenConf.originalToken, tokenConf.recipient, + realWallet, args.Amount, args.Nonce, common.Bytes2Hex(extData), common.Bytes2Hex(param)) + if err != nil { + return nil, errors.Wrap(err, "xTokenLockAndXIssue") + } + } + if strings.EqualFold(contractAddress.Hex(), realWallet.Hex()) { + contractAddress = tokenConf.remoteAppAddress + } + a := &types.LegacyTx{ + To: &contractAddress, + Value: args.Amount.Add(fee).BigInt(), + Data: data, + Gas: uint64(gas.IntPart()), + } + if !isNativeToken { + a.Value = fee.BigInt() + } + return a, nil +} diff --git a/utils/provider/bridge/darwinia/darwinia2ethereum_test.go b/utils/provider/bridge/darwinia/darwinia2ethereum_test.go new file mode 100644 index 0000000..1e38a95 --- /dev/null +++ b/utils/provider/bridge/darwinia/darwinia2ethereum_test.go @@ -0,0 +1,38 @@ +package darwinia + +import ( + "github.com/ethereum/go-ethereum/common" + "github.com/shopspring/decimal" + "github.com/stretchr/testify/assert" + "omni-balance/utils" + "omni-balance/utils/chains" + "testing" +) + +func TestDarwinia2ethereum(t *testing.T) { + var ( + args = InitVar(t) + amount = decimal.NewFromBigInt(chains.EthToWei(decimal.RequireFromString("0")), 0) + ) + tx, err := Darwinia2ethereum(args.ctx, SwapParams{ + Sender: args.sender, + TokenName: "RING", + Amount: amount, + Nonce: 1716966337913, + Client: args.client, + }) + assert.NoError(t, err) + utils.AssertEqualFold(t, common.Bytes2Hex(tx.Data), "7104aad500000000000000000000000000000000000000000000000000000000000000010000000000000000000000004ca75992d2750bec270731a72dfdede6b9e71cc700000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018fc32b2d7900000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000001800000000000000000000000000000000000000000000000000000000000000080000000000000000000000000c29dcb1f12a1618262ef9fba673b77140adc02d60000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000001443ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000016fe400000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000000") + assert.Equal(t, tx.To.Hex(), "0x092e19C46C9daAb7824393f1CD9c22f5BEA13560") + + tx, err = Darwinia2ethereum(args.ctx, SwapParams{ + Sender: args.sender, + TokenName: "KTON", + Amount: amount, + Nonce: 1716966513487, + Client: args.client, + }) + assert.NoError(t, err) + utils.AssertEqualFold(t, common.Bytes2Hex(tx.Data), "ac66b6a2000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000004020000000000000000000000004ca75992d2750bec270731a72dfdede6b9e71cc700000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018fc32ddb4f00000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000180000000000000000000000000000000000000000000000000000000000000006000000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000016c0400000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000000") + assert.Equal(t, tx.To.Hex(), "0x2B496f19A420C02490dB859fefeCCD71eDc2c046") +} diff --git a/utils/provider/bridge/darwinia/ethereum2darwinia.go b/utils/provider/bridge/darwinia/ethereum2darwinia.go new file mode 100644 index 0000000..865f65b --- /dev/null +++ b/utils/provider/bridge/darwinia/ethereum2darwinia.go @@ -0,0 +1,112 @@ +package darwinia + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "omni-balance/utils/constant" + "strings" +) + +var ( + ethereum2darwinia = map[string]Params{ + "RING": Params{ + contractAddress: common.HexToAddress("0xc29dCb1F12a1618262eF9FBA673b77140adc02D6"), + TokenAddress: common.HexToAddress("0x9469d013805bffb7d3debe5e7839237e535ec483"), + originalToken: common.HexToAddress("0xE7578598Aac020abFB918f33A20faD5B71d670b4"), + remoteAppAddress: common.HexToAddress("0xDc0C760c0fB4672D06088515F6446a71Df0c64C1"), + localAppAddress: common.HexToAddress("0x2B496f19A420C02490dB859fefeCCD71eDc2c046"), + sourceMessager: common.HexToAddress("0x65Be094765731F394bc6d9DF53bDF3376F1Fc8B0"), + targetMessager: common.HexToAddress("0x65Be094765731F394bc6d9DF53bDF3376F1Fc8B0"), + recipient: common.HexToAddress("0x4CA75992d2750BEC270731A72DfDedE6b9E71cC7"), + sourceChainId: 1, + targetChainId: 46, + extData: "000000000000000000000000092e19c46c9daab7824393f1cd9c22f5bea1356000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000014{sender}000000000000000000000000", + }, + "KTON": Params{ + contractAddress: common.Address{}, // must replace to sender address + TokenAddress: common.HexToAddress("0x9469d013805bffb7d3debe5e7839237e535ec483"), + originalToken: common.HexToAddress("0x0000000000000000000000000000000000000402"), + remoteAppAddress: common.HexToAddress("0xDc0C760c0fB4672D06088515F6446a71Df0c64C1"), + localAppAddress: common.HexToAddress("0x2B496f19A420C02490dB859fefeCCD71eDc2c046"), + sourceMessager: common.HexToAddress("0x65Be094765731F394bc6d9DF53bDF3376F1Fc8B0"), + targetMessager: common.HexToAddress("0x65Be094765731F394bc6d9DF53bDF3376F1Fc8B0"), + recipient: common.HexToAddress("0x4CA75992d2750BEC270731A72DfDedE6b9E71cC7"), + xTokenAddress: common.HexToAddress("0x9f284e1337a815fe77d2ff4ae46544645b20c5ff"), + sourceChainId: 1, + targetChainId: 46, + extData: "000000000000000000000000{sender}00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000", + }, + } +) + +func Ethereum2darwinia(ctx context.Context, args SwapParams) (tx *types.LegacyTx, err error) { + + var ( + wallet = args.Sender + realWallet = wallet.GetAddress(true) + tokenConf = ethereum2darwinia[strings.ToUpper(args.TokenName)] + ) + + if tokenConf.sourceChainId == 0 { + return nil, errors.New("token not support") + } + if !constant.IsTestCtx(ctx) { + err := approve(ctx, tokenConf.sourceChainId, tokenConf.TokenAddress, tokenConf.remoteAppAddress, + wallet, args.Amount.Mul(decimal.NewFromInt(2)), args.Client) + if err != nil { + return nil, errors.Wrap(err, "approve") + } + } + extData := common.Hex2Bytes(ReplaceExtData(tokenConf.extData, realWallet.Hex())) + contractAddress := tokenConf.contractAddress + if strings.EqualFold(contractAddress.Hex(), constant.ZeroAddress.Hex()) { + contractAddress = realWallet + } + data, err := Unlock( + tokenConf.sourceChainId, + tokenConf.originalToken, + contractAddress, + tokenConf.recipient, + realWallet, + args.Amount, + args.Nonce, + extData) + if err != nil { + return nil, errors.Wrap(err, "Unlock") + } + + data, err = ReceiveMessage(tokenConf.sourceChainId, tokenConf.remoteAppAddress, tokenConf.localAppAddress, + common.Bytes2Hex(data)) + if err != nil { + return nil, errors.Wrap(err, "ReceiveMessage") + } + + fee, param, gas, err := FetchMsglineFeeAndParams(ctx, tokenConf.sourceChainId, tokenConf.targetChainId, + tokenConf.sourceMessager, tokenConf.targetMessager, realWallet, common.Bytes2Hex(data)) + if err != nil { + return nil, errors.Wrap(err, "FetchMsglineFeeAndParams") + } + + if strings.EqualFold(tokenConf.contractAddress.Hex(), constant.ZeroAddress.Hex()) { + contractAddress = tokenConf.remoteAppAddress + data, err = BurnAndXUnlock(tokenConf.xTokenAddress, tokenConf.recipient, realWallet, args.Amount, + args.Nonce, extData, param) + } else { + data, err = XTokenBurnAndXUnlock(tokenConf.recipient, realWallet, args.Amount, args.Nonce, extData, param) + + } + + if err != nil { + return nil, errors.Wrap(err, "XTokenBurnAndXUnlock") + } + // remoteAppAddress + return &types.LegacyTx{ + To: &contractAddress, + Value: fee.BigInt(), + Data: data, + Gas: uint64(gas.IntPart()), + }, nil +} diff --git a/utils/provider/bridge/darwinia/ethereum2darwinia_test.go b/utils/provider/bridge/darwinia/ethereum2darwinia_test.go new file mode 100644 index 0000000..e7747bb --- /dev/null +++ b/utils/provider/bridge/darwinia/ethereum2darwinia_test.go @@ -0,0 +1,93 @@ +package darwinia + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethclient" + "github.com/shopspring/decimal" + "github.com/stretchr/testify/assert" + "omni-balance/utils/chains" + "omni-balance/utils/constant" + "omni-balance/utils/wallets" + "strings" + "testing" +) + +type TestVar struct { + ctx context.Context + client *ethclient.Client + sender wallets.Wallets +} + +func InitVar(t *testing.T) TestVar { + client, err := ethclient.Dial("https://rpc.darwinia.network") + assert.NoError(t, err) + return TestVar{ + ctx: constant.WithTestCtx(context.Background()), + client: client, + sender: wallets.NewWallets(wallets.WalletConfig{ + PrivateKey: constant.TestPrivateKey, + Address: common.HexToAddress(constant.TestWalletAddress), + }), + } +} + +func TestEthereum2darwinia(t *testing.T) { + var ( + conf = InitVar(t) + amount = decimal.NewFromBigInt(chains.EthToWei(decimal.RequireFromString("0")), 0) + ) + + type args struct { + ctx context.Context + args SwapParams + } + tests := []struct { + name string + args args + wantData string + wantTo string + wantErr assert.ErrorAssertionFunc + }{ + { + name: "ethereum2darwiniaForRING", + args: args{ + ctx: conf.ctx, + args: SwapParams{ + Sender: conf.sender, + TokenName: "RING", + Amount: amount, + Nonce: 1716964432673, + Client: conf.client, + }, + }, + wantData: "cf5a8bd80000000000000000000000004ca75992d2750bec270731a72dfdede6b9e71cc700000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018fc30e1b2100000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000001600000000000000000000000000000000000000000000000000000000000000080000000000000000000000000092e19c46c9daab7824393f1cd9c22f5bea135600000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000001443ef13e84d9992d1461a1f90cac4653658cea4fd000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000579cc00000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000000", + wantTo: "0xc29dCb1F12a1618262eF9FBA673b77140adc02D6", + wantErr: nil, + }, + { + name: "ethereum2darwiniaForKTON", + args: args{ + ctx: conf.ctx, + args: SwapParams{ + Sender: conf.sender, + TokenName: "KTON", + Amount: amount, + Nonce: 1716965255138, + Client: conf.client, + }, + }, + wantData: "57bf09850000000000000000000000009f284e1337a815fe77d2ff4ae46544645b20c5ff0000000000000000000000004ca75992d2750bec270731a72dfdede6b9e71cc700000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018fc31aa7e200000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000160000000000000000000000000000000000000000000000000000000000000006000000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000051fcc00000000000000000000000043ef13e84d9992d1461a1f90cac4653658cea4fd00000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000000", + wantTo: "0xDc0C760c0fB4672D06088515F6446a71Df0c64C1", + wantErr: nil, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tx, err := Ethereum2darwinia(tt.args.ctx, tt.args.args) + assert.NoError(t, err) + assert.Equal(t, tt.wantTo, tx.To.Hex()) + assert.Equalf(t, strings.ToLower(tt.wantData), strings.ToLower(common.Bytes2Hex(tx.Data)), "Ethereum2darwinia(%v, %v)", tt.args.ctx, tt.args.args) + }) + } +} diff --git a/utils/provider/bridge/darwinia/init.go b/utils/provider/bridge/darwinia/init.go new file mode 100644 index 0000000..dd593c3 --- /dev/null +++ b/utils/provider/bridge/darwinia/init.go @@ -0,0 +1,10 @@ +package darwinia + +import ( + "omni-balance/utils/configs" + "omni-balance/utils/provider" +) + +func init() { + provider.Register(configs.Bridge, New) +} diff --git a/utils/provider/bridge/darwinia/utils.go b/utils/provider/bridge/darwinia/utils.go new file mode 100644 index 0000000..77b2a59 --- /dev/null +++ b/utils/provider/bridge/darwinia/utils.go @@ -0,0 +1,348 @@ +package darwinia + +import ( + "bytes" + "context" + "encoding/json" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethclient/simulated" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "io" + "math/big" + "net/http" + "net/url" + "omni-balance/utils" + "omni-balance/utils/chains" + "omni-balance/utils/constant" + "omni-balance/utils/provider" + "omni-balance/utils/wallets" + "strconv" + "strings" + "sync" + "time" +) + +// GetSourceChains returns the list of source chain IDs that support transferring the specified token to the target chain. +// It checks the SUPPORTS map to identify the supported source chains based on the target chain ID and token name. +// The source chain IDs are returned as a slice of int64. +// +// Parameters: +// - targetChainId: The ID of the target chain. +// - TokenName: The name of the token. +// - wallet: The wallet address. +// - amount: The amount of the token to be transferred. +func (b *Bridge) FindValidSourceChains(ctx context.Context, targetChainId int, TokenName, wallet string, + amount decimal.Decimal) (sourceChainIds []int64) { + + sourceChains := GetSourceChains(int64(targetChainId), TokenName) + if len(sourceChains) == 0 { + return nil + } + var ( + w sync.WaitGroup + m sync.Mutex + ) + for _, sourceChain := range sourceChains { + w.Add(1) + go b.checkAndAppendSourceChainIfBalanceSufficient(ctx, sourceChain, TokenName, wallet, amount, &sourceChainIds, &w, &m) + } + w.Wait() + return sourceChainIds +} + +func (b *Bridge) GetValidSourceChain(ctx context.Context, targetChainId int, TokenName, wallet string, + amount decimal.Decimal) (sourceChainId int64) { + + sourceChains := b.FindValidSourceChains(ctx, targetChainId, TokenName, wallet, amount) + if len(sourceChains) == 0 { + return 0 + } + return utils.Choose(sourceChains) +} + +func (b *Bridge) GetBalance(ctx context.Context, args provider.BalanceParams) (decimal.Decimal, error) { + chain := b.config.GetChainConfig(args.Chain) + token := chain.GetToken(args.Token) + if token.ContractAddress == "" { + return decimal.Zero, errors.Errorf("token %s not found on %s", args.Token, args.Chain) + } + client, err := chains.NewTryClient(ctx, chain.RpcEndpoints) + if err != nil { + return decimal.Zero, errors.Wrap(err, "dial rpc") + } + defer client.Close() + + return chains.GetTokenBalance(ctx, client, token.ContractAddress, args.Wallet, token.Decimals) +} + +func (b *Bridge) checkAndAppendSourceChainIfBalanceSufficient(ctx context.Context, sourceChain int64, + TokenName, wallet string, amount decimal.Decimal, sourceChainIds *[]int64, w *sync.WaitGroup, m *sync.Mutex) { + + defer w.Done() + balance, err := b.GetBalance(ctx, + provider.BalanceParams{Token: TokenName, Chain: constant.GetChainName(sourceChain), Wallet: wallet}) + if err != nil { + logrus.Debugf("get %s balance error: %s", constant.GetChainName(sourceChain), err) + return + } + if !balance.GreaterThanOrEqual(amount) { + return + } + logrus.Debugf("check %s balance: %s >= %s", constant.GetChainName(sourceChain), balance, amount) + m.Lock() + defer m.Unlock() + *sourceChainIds = append(*sourceChainIds, sourceChain) +} + +func (b *Bridge) WaitForBridgeSuccess(ctx context.Context, tx, sender string) (HistoryRecord, error) { + log := logrus.WithFields(logrus.Fields{ + "tx": tx, + "sender": sender, + "chain": b.Name(), + "type": b.Type(), + "message": "wait for bridge success", + }) + requestData := GraphQLRequest{ + OperationName: "GetHistory", + Variables: map[string]interface{}{ + "row": 20, + "page": 0, + "sender": sender, + }, + Query: graphOlQuery, + } + jsonBytes, err := json.Marshal(requestData) + if err != nil { + + return HistoryRecord{}, errors.Wrap(err, "marshal request error") + } + var t = time.NewTicker(time.Second) + defer t.Stop() + getRecords := func() (HistoryRecordResponse, error) { + resp, err := http.Post("https://apollo.xtoken.box/graphql", "application/json", bytes.NewBuffer(jsonBytes)) + if err != nil { + log.Warnf("get %s status error: %s", b.Name(), err) + return HistoryRecordResponse{}, nil + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + log.Warnf("get %s status error: %s", b.Name(), err) + return HistoryRecordResponse{}, nil + } + + var response HistoryRecordResponse + err = json.Unmarshal(body, &response) + if err != nil { + return HistoryRecordResponse{}, errors.Wrap(err, "unmarshal response error") + } + return response, nil + } + + for { + select { + case <-ctx.Done(): + return HistoryRecord{}, nil + case <-t.C: + result, err := getRecords() + if err != nil { + return HistoryRecord{}, errors.Wrap(err, "get records error") + } + log.Debugf("get %s records: %d", b.Name(), len(result.Data.HistoryRecords.Records)) + for _, record := range result.Data.HistoryRecords.Records { + if !strings.EqualFold(record.RequestTxHash, tx) { + continue + } + if record.Result == 0 { + log.Debugf("tx %s status: pending", tx) + continue + } + if record.Result != 3 { + return record, errors.Errorf("bridge failed: %d", record.Result) + } + return record, nil + } + } + } +} + +func approve(ctx context.Context, chainId int64, tokenAddress, spender common.Address, owner wallets.Wallets, + amount decimal.Decimal, client simulated.Client) error { + + return chains.TokenApprove(ctx, chains.TokenApproveParams{ + ChainId: chainId, + TokenAddress: tokenAddress, + Owner: owner.GetAddress(true), + SendTransaction: owner.SendTransaction, + WaitTransaction: owner.WaitTransaction, + Spender: spender, + AmountWei: amount, + Client: client, + }) +} + +func Issue(remoteChainId int64, originalToken, originalSender, recipient, rollbackAccount common.Address, + amount decimal.Decimal, nonce int64, extData []byte) ([]byte, error) { + contractAbi, err := abi.JSON(strings.NewReader(XTOKEN_ISSUING_NEXT)) + if err != nil { + return nil, err + } + return contractAbi.Pack( + "issue", + big.NewInt(remoteChainId), + originalToken, + originalSender, + recipient, + rollbackAccount, + amount.BigInt(), + big.NewInt(nonce), + extData) +} + +func ReceiveMessage(srcAppChainId int64, remoteAppAddress, localAppAddress common.Address, message string) ([]byte, error) { + contractAbi, err := abi.JSON(strings.NewReader(MSGLINE_MESSAGER)) + if err != nil { + return nil, err + } + return contractAbi.Pack("receiveMessage", big.NewInt(srcAppChainId), remoteAppAddress, localAppAddress, common.Hex2Bytes(message)) +} + +func FetchMsglineFeeAndParams(ctx context.Context, sourceChainId, targetChainId int64, sourceMessager, targetMessager, + sender common.Address, payload string) (fee decimal.Decimal, extParams []byte, gas decimal.Decimal, err error) { + u, err := url.Parse("https://api.msgport.xyz/ormp/fee") + if err != nil { + return decimal.Zero, nil, decimal.Zero, errors.Wrap(err, "url parse error") + } + query := u.Query() + query.Set("from_chain_id", strconv.Itoa(int(sourceChainId))) + query.Set("to_chain_id", strconv.Itoa(int(targetChainId))) + if !strings.HasPrefix(payload, "0x") { + payload = "0x" + payload + } + query.Set("payload", payload) + query.Set("from_address", sourceMessager.Hex()) + query.Set("to_address", targetMessager.Hex()) + query.Set("refund_address", sender.Hex()) + u.RawQuery = query.Encode() + type Fee struct { + Code int `json:"code"` + Data struct { + Fee string `json:"fee"` + Params string `json:"params"` + Gas struct { + GasForMessagingLayer decimal.Decimal `json:"gasForMessagingLayer"` + GasForMsgport decimal.Decimal `json:"gasForMsgport"` + Multiplier decimal.Decimal `json:"multiplier"` + Total decimal.Decimal `json:"total"` + } `json:"gas"` + } `json:"data"` + } + var result Fee + err = utils.Request(ctx, "GET", u.String(), nil, &result) + if err != nil { + return decimal.Zero, nil, decimal.Zero, errors.Wrap(err, "request error") + } + if result.Code != 0 { + return decimal.Zero, nil, decimal.Zero, errors.Errorf("fetch fee error: %d", result.Code) + } + return decimal.RequireFromString(result.Data.Fee), + common.Hex2Bytes(strings.TrimPrefix(result.Data.Params, "0x")), result.Data.Gas.Total, nil +} + +func WTokenLockAndXIssue(remoteChainId int64, recipient, rollbackAccount common.Address, amount decimal.Decimal, + nonce int64, extData, extParams string) ([]byte, error) { + + contractAbi, err := abi.JSON(strings.NewReader(WTOKEN_CONVERTOR)) + if err != nil { + return nil, err + } + return contractAbi.Pack("lockAndXIssue", + big.NewInt(remoteChainId), + recipient, + rollbackAccount, + amount.BigInt(), + big.NewInt(nonce), + common.Hex2Bytes(extData), + common.Hex2Bytes(extParams), + ) +} + +func XTokenLockAndXIssue(remoteChainId int64, originalToken, recipient, rollbackAccount common.Address, + amount decimal.Decimal, nonce int64, extData, extParams string) ([]byte, error) { + + contractAbi, err := abi.JSON(strings.NewReader(XTOKEN_BACKING_NEXT)) + if err != nil { + return nil, err + } + return contractAbi.Pack("lockAndXIssue", + big.NewInt(remoteChainId), + originalToken, + recipient, + rollbackAccount, + amount.BigInt(), + big.NewInt(nonce), + common.Hex2Bytes(strings.TrimPrefix(extData, "0x")), + common.Hex2Bytes(strings.TrimPrefix(extParams, "0x"))) +} + +func Unlock(remoteChainId int64, originalToken, originSender, recipient, rollbackAccount common.Address, + amount decimal.Decimal, nonce int64, extData []byte) ([]byte, error) { + + contractAbi, err := abi.JSON(strings.NewReader(XTOKEN_BACKING_NEXT)) + if err != nil { + return nil, err + } + return contractAbi.Pack("unlock", + big.NewInt(remoteChainId), + originalToken, + originSender, + recipient, + rollbackAccount, + amount.BigInt(), + big.NewInt(nonce), + extData, + ) +} + +func BurnAndXUnlock(xToken, recipient, rollbackAccount common.Address, amount decimal.Decimal, nonce int64, + extData, extParams []byte) ([]byte, error) { + + contractAbi, err := abi.JSON(strings.NewReader(XTOKEN_ISSUING_NEXT)) + if err != nil { + return nil, err + } + return contractAbi.Pack("burnAndXUnlock", + xToken, + recipient, + rollbackAccount, + amount.BigInt(), + big.NewInt(nonce), + extData, + extParams, + ) +} + +func XTokenBurnAndXUnlock(recipient, rollbackAccount common.Address, amount decimal.Decimal, nonce int64, + extData []byte, extParams []byte) ([]byte, error) { + + contractAbi, err := abi.JSON(strings.NewReader(XTOKEN_CONVERTOR)) + if err != nil { + return nil, err + } + return contractAbi.Pack("burnAndXUnlock", + recipient, + rollbackAccount, + amount.BigInt(), + big.NewInt(nonce), + extData, + extParams, + ) +} + +func ReplaceExtData(extData string, sender string) string { + return strings.ReplaceAll(extData, "{sender}", strings.TrimPrefix(sender, "0x")) +} diff --git a/utils/provider/bridge/helix/abi_v2_default/v2-default.go b/utils/provider/bridge/helix/abi_v2_default/v2-default.go new file mode 100644 index 0000000..a565e81 --- /dev/null +++ b/utils/provider/bridge/helix/abi_v2_default/v2-default.go @@ -0,0 +1,213 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package abi_v2_default + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription + _ = abi.ConvertType +) + +// LnDefaultBridgeSourceSnapshot is an auto generated low-level Go binding around an user-defined struct. +type LnDefaultBridgeSourceSnapshot struct { + RemoteChainId *big.Int + Provider common.Address + SourceToken common.Address + TargetToken common.Address + TransferId [32]byte + TotalFee *big.Int + WithdrawNonce uint64 +} + +// HelixMetaData contains all meta data concerning the Helix contract. +var HelixMetaData = &bind.MetaData{ + ABI: "[{\"inputs\":[{\"components\":[{\"internalType\":\"uint256\",\"name\":\"remoteChainId\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"provider\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"transferId\",\"type\":\"bytes32\"},{\"internalType\":\"uint112\",\"name\":\"totalFee\",\"type\":\"uint112\"},{\"internalType\":\"uint64\",\"name\":\"withdrawNonce\",\"type\":\"uint64\"}],\"internalType\":\"structLnDefaultBridgeSource.Snapshot\",\"name\":\"_snapshot\",\"type\":\"tuple\"},{\"internalType\":\"uint112\",\"name\":\"_amount\",\"type\":\"uint112\"},{\"internalType\":\"address\",\"name\":\"_receiver\",\"type\":\"address\"}],\"name\":\"transferAndLockMargin\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"}]", +} + +// HelixABI is the input ABI used to generate the binding from. +// Deprecated: Use HelixMetaData.ABI instead. +var HelixABI = HelixMetaData.ABI + +// Helix is an auto generated Go binding around an Ethereum contract. +type Helix struct { + HelixCaller // Read-only binding to the contract + HelixTransactor // Write-only binding to the contract + HelixFilterer // Log filterer for contract events +} + +// HelixCaller is an auto generated read-only Go binding around an Ethereum contract. +type HelixCaller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// HelixTransactor is an auto generated write-only Go binding around an Ethereum contract. +type HelixTransactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// HelixFilterer is an auto generated log filtering Go binding around an Ethereum contract events. +type HelixFilterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// HelixSession is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type HelixSession struct { + Contract *Helix // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// HelixCallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type HelixCallerSession struct { + Contract *HelixCaller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// HelixTransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type HelixTransactorSession struct { + Contract *HelixTransactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// HelixRaw is an auto generated low-level Go binding around an Ethereum contract. +type HelixRaw struct { + Contract *Helix // Generic contract binding to access the raw methods on +} + +// HelixCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type HelixCallerRaw struct { + Contract *HelixCaller // Generic read-only contract binding to access the raw methods on +} + +// HelixTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type HelixTransactorRaw struct { + Contract *HelixTransactor // Generic write-only contract binding to access the raw methods on +} + +// NewHelix creates a new instance of Helix, bound to a specific deployed contract. +func NewHelix(address common.Address, backend bind.ContractBackend) (*Helix, error) { + contract, err := bindHelix(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &Helix{HelixCaller: HelixCaller{contract: contract}, HelixTransactor: HelixTransactor{contract: contract}, HelixFilterer: HelixFilterer{contract: contract}}, nil +} + +// NewHelixCaller creates a new read-only instance of Helix, bound to a specific deployed contract. +func NewHelixCaller(address common.Address, caller bind.ContractCaller) (*HelixCaller, error) { + contract, err := bindHelix(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &HelixCaller{contract: contract}, nil +} + +// NewHelixTransactor creates a new write-only instance of Helix, bound to a specific deployed contract. +func NewHelixTransactor(address common.Address, transactor bind.ContractTransactor) (*HelixTransactor, error) { + contract, err := bindHelix(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &HelixTransactor{contract: contract}, nil +} + +// NewHelixFilterer creates a new log filterer instance of Helix, bound to a specific deployed contract. +func NewHelixFilterer(address common.Address, filterer bind.ContractFilterer) (*HelixFilterer, error) { + contract, err := bindHelix(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &HelixFilterer{contract: contract}, nil +} + +// bindHelix binds a generic wrapper to an already deployed contract. +func bindHelix(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := HelixMetaData.GetAbi() + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Helix *HelixRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Helix.Contract.HelixCaller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Helix *HelixRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Helix.Contract.HelixTransactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Helix *HelixRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Helix.Contract.HelixTransactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Helix *HelixCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Helix.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Helix *HelixTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Helix.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Helix *HelixTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Helix.Contract.contract.Transact(opts, method, params...) +} + +// TransferAndLockMargin is a paid mutator transaction binding the contract method 0x0be175a5. +// +// Solidity: function transferAndLockMargin((uint256,address,address,address,bytes32,uint112,uint64) _snapshot, uint112 _amount, address _receiver) payable returns() +func (_Helix *HelixTransactor) TransferAndLockMargin(opts *bind.TransactOpts, _snapshot LnDefaultBridgeSourceSnapshot, _amount *big.Int, _receiver common.Address) (*types.Transaction, error) { + return _Helix.contract.Transact(opts, "transferAndLockMargin", _snapshot, _amount, _receiver) +} + +// TransferAndLockMargin is a paid mutator transaction binding the contract method 0x0be175a5. +// +// Solidity: function transferAndLockMargin((uint256,address,address,address,bytes32,uint112,uint64) _snapshot, uint112 _amount, address _receiver) payable returns() +func (_Helix *HelixSession) TransferAndLockMargin(_snapshot LnDefaultBridgeSourceSnapshot, _amount *big.Int, _receiver common.Address) (*types.Transaction, error) { + return _Helix.Contract.TransferAndLockMargin(&_Helix.TransactOpts, _snapshot, _amount, _receiver) +} + +// TransferAndLockMargin is a paid mutator transaction binding the contract method 0x0be175a5. +// +// Solidity: function transferAndLockMargin((uint256,address,address,address,bytes32,uint112,uint64) _snapshot, uint112 _amount, address _receiver) payable returns() +func (_Helix *HelixTransactorSession) TransferAndLockMargin(_snapshot LnDefaultBridgeSourceSnapshot, _amount *big.Int, _receiver common.Address) (*types.Transaction, error) { + return _Helix.Contract.TransferAndLockMargin(&_Helix.TransactOpts, _snapshot, _amount, _receiver) +} diff --git a/utils/provider/bridge/helix/abi_v2_opposite/v2_opposite.go b/utils/provider/bridge/helix/abi_v2_opposite/v2_opposite.go new file mode 100644 index 0000000..123ccd1 --- /dev/null +++ b/utils/provider/bridge/helix/abi_v2_opposite/v2_opposite.go @@ -0,0 +1,213 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package abi_v2_opposite + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription + _ = abi.ConvertType +) + +// LnOppositeBridgeSourceSnapshot is an auto generated low-level Go binding around an user-defined struct. +type LnOppositeBridgeSourceSnapshot struct { + RemoteChainId *big.Int + Provider common.Address + SourceToken common.Address + TargetToken common.Address + TransferId [32]byte + TotalFee *big.Int + DepositedMargin *big.Int +} + +// AbiV2OppositeMetaData contains all meta data concerning the AbiV2Opposite contract. +var AbiV2OppositeMetaData = &bind.MetaData{ + ABI: "[{\"inputs\":[{\"components\":[{\"internalType\":\"uint256\",\"name\":\"remoteChainId\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"provider\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"transferId\",\"type\":\"bytes32\"},{\"internalType\":\"uint112\",\"name\":\"totalFee\",\"type\":\"uint112\"},{\"internalType\":\"uint112\",\"name\":\"depositedMargin\",\"type\":\"uint112\"}],\"internalType\":\"structLnOppositeBridgeSource.Snapshot\",\"name\":\"_snapshot\",\"type\":\"tuple\"},{\"internalType\":\"uint112\",\"name\":\"_amount\",\"type\":\"uint112\"},{\"internalType\":\"address\",\"name\":\"_receiver\",\"type\":\"address\"}],\"name\":\"transferAndLockMargin\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"}]", +} + +// AbiV2OppositeABI is the input ABI used to generate the binding from. +// Deprecated: Use AbiV2OppositeMetaData.ABI instead. +var AbiV2OppositeABI = AbiV2OppositeMetaData.ABI + +// AbiV2Opposite is an auto generated Go binding around an Ethereum contract. +type AbiV2Opposite struct { + AbiV2OppositeCaller // Read-only binding to the contract + AbiV2OppositeTransactor // Write-only binding to the contract + AbiV2OppositeFilterer // Log filterer for contract events +} + +// AbiV2OppositeCaller is an auto generated read-only Go binding around an Ethereum contract. +type AbiV2OppositeCaller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// AbiV2OppositeTransactor is an auto generated write-only Go binding around an Ethereum contract. +type AbiV2OppositeTransactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// AbiV2OppositeFilterer is an auto generated log filtering Go binding around an Ethereum contract events. +type AbiV2OppositeFilterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// AbiV2OppositeSession is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type AbiV2OppositeSession struct { + Contract *AbiV2Opposite // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// AbiV2OppositeCallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type AbiV2OppositeCallerSession struct { + Contract *AbiV2OppositeCaller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// AbiV2OppositeTransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type AbiV2OppositeTransactorSession struct { + Contract *AbiV2OppositeTransactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// AbiV2OppositeRaw is an auto generated low-level Go binding around an Ethereum contract. +type AbiV2OppositeRaw struct { + Contract *AbiV2Opposite // Generic contract binding to access the raw methods on +} + +// AbiV2OppositeCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type AbiV2OppositeCallerRaw struct { + Contract *AbiV2OppositeCaller // Generic read-only contract binding to access the raw methods on +} + +// AbiV2OppositeTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type AbiV2OppositeTransactorRaw struct { + Contract *AbiV2OppositeTransactor // Generic write-only contract binding to access the raw methods on +} + +// NewAbiV2Opposite creates a new instance of AbiV2Opposite, bound to a specific deployed contract. +func NewAbiV2Opposite(address common.Address, backend bind.ContractBackend) (*AbiV2Opposite, error) { + contract, err := bindAbiV2Opposite(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &AbiV2Opposite{AbiV2OppositeCaller: AbiV2OppositeCaller{contract: contract}, AbiV2OppositeTransactor: AbiV2OppositeTransactor{contract: contract}, AbiV2OppositeFilterer: AbiV2OppositeFilterer{contract: contract}}, nil +} + +// NewAbiV2OppositeCaller creates a new read-only instance of AbiV2Opposite, bound to a specific deployed contract. +func NewAbiV2OppositeCaller(address common.Address, caller bind.ContractCaller) (*AbiV2OppositeCaller, error) { + contract, err := bindAbiV2Opposite(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &AbiV2OppositeCaller{contract: contract}, nil +} + +// NewAbiV2OppositeTransactor creates a new write-only instance of AbiV2Opposite, bound to a specific deployed contract. +func NewAbiV2OppositeTransactor(address common.Address, transactor bind.ContractTransactor) (*AbiV2OppositeTransactor, error) { + contract, err := bindAbiV2Opposite(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &AbiV2OppositeTransactor{contract: contract}, nil +} + +// NewAbiV2OppositeFilterer creates a new log filterer instance of AbiV2Opposite, bound to a specific deployed contract. +func NewAbiV2OppositeFilterer(address common.Address, filterer bind.ContractFilterer) (*AbiV2OppositeFilterer, error) { + contract, err := bindAbiV2Opposite(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &AbiV2OppositeFilterer{contract: contract}, nil +} + +// bindAbiV2Opposite binds a generic wrapper to an already deployed contract. +func bindAbiV2Opposite(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := AbiV2OppositeMetaData.GetAbi() + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_AbiV2Opposite *AbiV2OppositeRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _AbiV2Opposite.Contract.AbiV2OppositeCaller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_AbiV2Opposite *AbiV2OppositeRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _AbiV2Opposite.Contract.AbiV2OppositeTransactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_AbiV2Opposite *AbiV2OppositeRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _AbiV2Opposite.Contract.AbiV2OppositeTransactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_AbiV2Opposite *AbiV2OppositeCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _AbiV2Opposite.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_AbiV2Opposite *AbiV2OppositeTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _AbiV2Opposite.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_AbiV2Opposite *AbiV2OppositeTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _AbiV2Opposite.Contract.contract.Transact(opts, method, params...) +} + +// TransferAndLockMargin is a paid mutator transaction binding the contract method 0x2656c147. +// +// Solidity: function transferAndLockMargin((uint256,address,address,address,bytes32,uint112,uint112) _snapshot, uint112 _amount, address _receiver) payable returns() +func (_AbiV2Opposite *AbiV2OppositeTransactor) TransferAndLockMargin(opts *bind.TransactOpts, _snapshot LnOppositeBridgeSourceSnapshot, _amount *big.Int, _receiver common.Address) (*types.Transaction, error) { + return _AbiV2Opposite.contract.Transact(opts, "transferAndLockMargin", _snapshot, _amount, _receiver) +} + +// TransferAndLockMargin is a paid mutator transaction binding the contract method 0x2656c147. +// +// Solidity: function transferAndLockMargin((uint256,address,address,address,bytes32,uint112,uint112) _snapshot, uint112 _amount, address _receiver) payable returns() +func (_AbiV2Opposite *AbiV2OppositeSession) TransferAndLockMargin(_snapshot LnOppositeBridgeSourceSnapshot, _amount *big.Int, _receiver common.Address) (*types.Transaction, error) { + return _AbiV2Opposite.Contract.TransferAndLockMargin(&_AbiV2Opposite.TransactOpts, _snapshot, _amount, _receiver) +} + +// TransferAndLockMargin is a paid mutator transaction binding the contract method 0x2656c147. +// +// Solidity: function transferAndLockMargin((uint256,address,address,address,bytes32,uint112,uint112) _snapshot, uint112 _amount, address _receiver) payable returns() +func (_AbiV2Opposite *AbiV2OppositeTransactorSession) TransferAndLockMargin(_snapshot LnOppositeBridgeSourceSnapshot, _amount *big.Int, _receiver common.Address) (*types.Transaction, error) { + return _AbiV2Opposite.Contract.TransferAndLockMargin(&_AbiV2Opposite.TransactOpts, _snapshot, _amount, _receiver) +} diff --git a/utils/provider/bridge/helix/abi_v3/v3.go b/utils/provider/bridge/helix/abi_v3/v3.go new file mode 100644 index 0000000..4d5655d --- /dev/null +++ b/utils/provider/bridge/helix/abi_v3/v3.go @@ -0,0 +1,214 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package abi_v3 + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription + _ = abi.ConvertType +) + +// LnBridgeSourceV3TransferParams is an auto generated low-level Go binding around an user-defined struct. +type LnBridgeSourceV3TransferParams struct { + RemoteChainId *big.Int + Provider common.Address + SourceToken common.Address + TargetToken common.Address + TotalFee *big.Int + Amount *big.Int + Receiver common.Address + Timestamp *big.Int +} + +// AbiV3MetaData contains all meta data concerning the AbiV3 contract. +var AbiV3MetaData = &bind.MetaData{ + ABI: "[{\"inputs\":[{\"components\":[{\"internalType\":\"uint256\",\"name\":\"remoteChainId\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"provider\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"sourceToken\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"targetToken\",\"type\":\"address\"},{\"internalType\":\"uint112\",\"name\":\"totalFee\",\"type\":\"uint112\"},{\"internalType\":\"uint112\",\"name\":\"amount\",\"type\":\"uint112\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"timestamp\",\"type\":\"uint256\"}],\"internalType\":\"structLnBridgeSourceV3.TransferParams\",\"name\":\"_params\",\"type\":\"tuple\"}],\"name\":\"lockAndRemoteRelease\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"}]", +} + +// AbiV3ABI is the input ABI used to generate the binding from. +// Deprecated: Use AbiV3MetaData.ABI instead. +var AbiV3ABI = AbiV3MetaData.ABI + +// AbiV3 is an auto generated Go binding around an Ethereum contract. +type AbiV3 struct { + AbiV3Caller // Read-only binding to the contract + AbiV3Transactor // Write-only binding to the contract + AbiV3Filterer // Log filterer for contract events +} + +// AbiV3Caller is an auto generated read-only Go binding around an Ethereum contract. +type AbiV3Caller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// AbiV3Transactor is an auto generated write-only Go binding around an Ethereum contract. +type AbiV3Transactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// AbiV3Filterer is an auto generated log filtering Go binding around an Ethereum contract events. +type AbiV3Filterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// AbiV3Session is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type AbiV3Session struct { + Contract *AbiV3 // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// AbiV3CallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type AbiV3CallerSession struct { + Contract *AbiV3Caller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// AbiV3TransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type AbiV3TransactorSession struct { + Contract *AbiV3Transactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// AbiV3Raw is an auto generated low-level Go binding around an Ethereum contract. +type AbiV3Raw struct { + Contract *AbiV3 // Generic contract binding to access the raw methods on +} + +// AbiV3CallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type AbiV3CallerRaw struct { + Contract *AbiV3Caller // Generic read-only contract binding to access the raw methods on +} + +// AbiV3TransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type AbiV3TransactorRaw struct { + Contract *AbiV3Transactor // Generic write-only contract binding to access the raw methods on +} + +// NewAbiV3 creates a new instance of AbiV3, bound to a specific deployed contract. +func NewAbiV3(address common.Address, backend bind.ContractBackend) (*AbiV3, error) { + contract, err := bindAbiV3(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &AbiV3{AbiV3Caller: AbiV3Caller{contract: contract}, AbiV3Transactor: AbiV3Transactor{contract: contract}, AbiV3Filterer: AbiV3Filterer{contract: contract}}, nil +} + +// NewAbiV3Caller creates a new read-only instance of AbiV3, bound to a specific deployed contract. +func NewAbiV3Caller(address common.Address, caller bind.ContractCaller) (*AbiV3Caller, error) { + contract, err := bindAbiV3(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &AbiV3Caller{contract: contract}, nil +} + +// NewAbiV3Transactor creates a new write-only instance of AbiV3, bound to a specific deployed contract. +func NewAbiV3Transactor(address common.Address, transactor bind.ContractTransactor) (*AbiV3Transactor, error) { + contract, err := bindAbiV3(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &AbiV3Transactor{contract: contract}, nil +} + +// NewAbiV3Filterer creates a new log filterer instance of AbiV3, bound to a specific deployed contract. +func NewAbiV3Filterer(address common.Address, filterer bind.ContractFilterer) (*AbiV3Filterer, error) { + contract, err := bindAbiV3(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &AbiV3Filterer{contract: contract}, nil +} + +// bindAbiV3 binds a generic wrapper to an already deployed contract. +func bindAbiV3(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := AbiV3MetaData.GetAbi() + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_AbiV3 *AbiV3Raw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _AbiV3.Contract.AbiV3Caller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_AbiV3 *AbiV3Raw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _AbiV3.Contract.AbiV3Transactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_AbiV3 *AbiV3Raw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _AbiV3.Contract.AbiV3Transactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_AbiV3 *AbiV3CallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _AbiV3.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_AbiV3 *AbiV3TransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _AbiV3.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_AbiV3 *AbiV3TransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _AbiV3.Contract.contract.Transact(opts, method, params...) +} + +// LockAndRemoteRelease is a paid mutator transaction binding the contract method 0x9cd13471. +// +// Solidity: function lockAndRemoteRelease((uint256,address,address,address,uint112,uint112,address,uint256) _params) payable returns() +func (_AbiV3 *AbiV3Transactor) LockAndRemoteRelease(opts *bind.TransactOpts, _params LnBridgeSourceV3TransferParams) (*types.Transaction, error) { + return _AbiV3.contract.Transact(opts, "lockAndRemoteRelease", _params) +} + +// LockAndRemoteRelease is a paid mutator transaction binding the contract method 0x9cd13471. +// +// Solidity: function lockAndRemoteRelease((uint256,address,address,address,uint112,uint112,address,uint256) _params) payable returns() +func (_AbiV3 *AbiV3Session) LockAndRemoteRelease(_params LnBridgeSourceV3TransferParams) (*types.Transaction, error) { + return _AbiV3.Contract.LockAndRemoteRelease(&_AbiV3.TransactOpts, _params) +} + +// LockAndRemoteRelease is a paid mutator transaction binding the contract method 0x9cd13471. +// +// Solidity: function lockAndRemoteRelease((uint256,address,address,address,uint112,uint112,address,uint256) _params) payable returns() +func (_AbiV3 *AbiV3TransactorSession) LockAndRemoteRelease(_params LnBridgeSourceV3TransferParams) (*types.Transaction, error) { + return _AbiV3.Contract.LockAndRemoteRelease(&_AbiV3.TransactOpts, _params) +} diff --git a/utils/provider/bridge/helix/configs.go b/utils/provider/bridge/helix/configs.go new file mode 100644 index 0000000..1e71290 --- /dev/null +++ b/utils/provider/bridge/helix/configs.go @@ -0,0 +1,108 @@ +package helix + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "omni-balance/utils/chains" + "omni-balance/utils/configs" +) + +type Transfer interface { + Do(ctx context.Context, opts TransferOptions) (tx *types.LegacyTx, err error) +} + +type Options struct { + SourceTokenName string + TargetTokenName string + SourceChain string + TargetChain string + Config configs.Config + Sender common.Address + Recipient common.Address + Amount decimal.Decimal +} + +type TransferOptions struct { + Relayer common.Address + TransferId common.Hash + TotalFee decimal.Decimal + WithdrawNonce uint64 + DepositedMargin decimal.Decimal + Client *ethclient.Client + _bridge string + _typename string + // only for v3 + timestamp int64 +} + +type WithdrawFeeArgs struct { + Amount decimal.Decimal + Sender common.Address + Relayer common.Address + TransferId common.Hash + WithdrawNonce string +} + +type GetFeeArgs struct { + BaseFee decimal.Decimal + ProtocolFee decimal.Decimal + LiquidityFeeRate decimal.Decimal + TransferAmount decimal.Decimal + Sender common.Address + Recipient common.Address + Relayer common.Address +} + +type HistoryRecordsResult struct { + Data struct { + HistoryRecords struct { + Total int `json:"total"` + Records []HistoryRecord `json:"records"` + Typename string `json:"__typename"` + } `json:"historyRecords"` + } `json:"data"` +} +type HistoryRecord struct { + RequestTxHash string `json:"requestTxHash"` + ResponseTxHash string `json:"responseTxHash"` + FromChain string `json:"fromChain"` + ToChain string `json:"toChain"` + StartTime int `json:"startTime"` + SendToken string `json:"sendToken"` + SendAmount string `json:"sendAmount"` + ConfirmedBlocks string `json:"confirmedBlocks"` + Result int `json:"result"` + Id string `json:"id"` + Typename string `json:"__typename"` +} + +func GetTransferOptions(_ context.Context, amount decimal.Decimal, decimals int32, fromChain, toChain string, + token common.Address) (TransferOptions, error) { + + result, err := GetSortedLnBridgeRelayInfos(amount, decimals, fromChain, toChain, token) + if err != nil { + return TransferOptions{}, errors.Wrap(err, "get sorted ln bridge relay infos") + } + info := result.Data.SortedLnBridgeRelayInfos + if len(info.Records) == 0 { + return TransferOptions{}, errors.Errorf("no relay info") + } + if decimal.RequireFromString(info.TransferLimit).LessThan(amount) { + return TransferOptions{}, errors.Errorf("transfer amount is too large, must less than %s", info.TransferLimit) + } + record := info.Records[0] + amount = decimal.NewFromBigInt(chains.EthToWei(amount, decimals), 0) + return TransferOptions{ + _typename: record.Typename, + _bridge: record.Bridge, + Relayer: record.Relayer, + TransferId: record.LastTransferId, + TotalFee: amount.Mul(record.LiquidityFeeRate.Div(decimal.New(100000, 0))).Add(record.ProtocolFee.Add(record.BaseFee)), + WithdrawNonce: uint64(record.WithdrawNonce.IntPart()), + DepositedMargin: record.Margin, + }, nil +} diff --git a/utils/provider/bridge/helix/helix.go b/utils/provider/bridge/helix/helix.go new file mode 100644 index 0000000..0b91c18 --- /dev/null +++ b/utils/provider/bridge/helix/helix.go @@ -0,0 +1,230 @@ +package helix + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "omni-balance/utils" + "omni-balance/utils/chains" + "omni-balance/utils/configs" + "omni-balance/utils/constant" + "omni-balance/utils/provider" +) + +type Bridge struct { + config configs.Config +} + +func New(conf configs.Config, noInit ...bool) (provider.Provider, error) { + if len(noInit) > 0 && noInit[0] { + return &Bridge{}, nil + } + return &Bridge{config: conf}, nil +} + +func (b *Bridge) Swap(ctx context.Context, args provider.SwapParams) (result provider.SwapResult, err error) { + var ( + lastHistory = args.LastHistory + actionNumber = Action2Int(lastHistory.Actions) + txHash = common.HexToHash(lastHistory.Tx) + log = args.GetLogs(b.Name()) + wallet = args.Sender + recordFn = func(s provider.SwapHistory, errs ...error) { + s.ProviderType = string(b.Type()) + s.ProviderName = b.Name() + s.Amount = args.Amount + if args.RecordFn == nil { + return + } + args.RecordFn(s, errs...) + } + ) + if lastHistory.Actions == targetChainReceivedAction && lastHistory.Status == string(provider.TxStatusSuccess) { + return provider.SwapResult{ + ProviderType: b.Type(), + ProviderName: b.Name(), + OrderId: lastHistory.Tx, + Status: provider.TxStatusSuccess, + CurrentChain: args.TargetChain, + Tx: lastHistory.Tx, + }, nil + } + args.SourceToken = args.TargetToken + + if args.SourceChain == "" { + sourceChainId, err := b.GetSourceChain(ctx, args.TargetChain, args.TargetToken, + wallet.GetAddress(true).Hex(), args.Amount) + if err != nil { + return result, errors.Wrap(err, "get source chain") + } + args.SourceChain = constant.GetChainName(sourceChainId) + } + ctx = context.WithValue(ctx, constant.ChainNameKeyInCtx, args.SourceChain) + log = args.GetLogs(b.Name()).WithFields( + logrus.Fields{ + "sourceChain": args.SourceChain, + "tokenIn": args.SourceToken, + }, + ) + chain := b.config.GetChainConfig(args.SourceChain) + ethClient, err := chains.NewTryClient(ctx, chain.RpcEndpoints) + if err != nil { + return result, errors.Wrap(err, "dial rpc") + } + defer ethClient.Close() + + var tokenInfo = b.config.GetTokenInfoOnChain(args.SourceToken, args.SourceChain) + if tokenInfo.Decimals == 0 || tokenInfo.Name == "" { + return result, errors.Errorf("token %s not supported", args.SourceToken) + } + + if actionNumber <= 1 && provider.TxStatus(lastHistory.Status).CanRetry() { + transferOptions, err := GetTransferOptions( + ctx, + args.Amount, + tokenInfo.Decimals, + args.SourceChain, + args.TargetChain, + common.HexToAddress(tokenInfo.ContractAddress), + ) + if err != nil { + return result, errors.Wrap(err, "get transfer options") + } + if _, ok := BRIDGES[BridgeType(transferOptions._bridge)]; !ok { + return result, errors.Errorf("bridge %s not supported", transferOptions._bridge) + } + log.Debugf("transfer options: %+v", transferOptions) + bridge := BRIDGES[BridgeType(transferOptions._bridge)](Options{ + SourceTokenName: args.SourceToken, + TargetTokenName: args.TargetToken, + SourceChain: args.SourceChain, + TargetChain: args.TargetChain, + Config: b.config, + Sender: wallet.GetAddress(true), + Recipient: wallet.GetAddress(true), + Amount: args.Amount, + }) + tx, err := bridge.Do(ctx, transferOptions) + if err != nil { + return result, errors.Wrap(err, "do transfer") + } + tx.Gas = 406775 + + recordFn(provider.SwapHistory{Actions: sourceChainSendingAction, Status: string(provider.TxStatusPending), + CurrentChain: args.SourceChain}) + txHash, err = wallet.SendTransaction(ctx, tx, ethClient) + if err != nil { + recordFn(provider.SwapHistory{Actions: sourceChainSendingAction, Status: string(provider.TxStatusFailed), + CurrentChain: args.SourceChain}) + return result, errors.Wrap(err, "send signed transaction") + } + recordFn(provider.SwapHistory{Actions: sourceChainSendingAction, Status: string(provider.TxStatusSuccess), + CurrentChain: args.SourceChain, Tx: txHash.Hex()}) + } + + sr := &provider.SwapResult{ + TokenInName: args.SourceToken, + ProviderType: configs.Bridge, + ProviderName: b.Name(), + Status: provider.TxStatusPending, + CurrentChain: args.SourceChain, + Tx: txHash.Hex(), + OrderId: txHash.Hex(), + } + + if actionNumber <= 2 { + recordFn(provider.SwapHistory{Actions: sourceChainSentAction, Status: string(provider.TxStatusPending), + CurrentChain: args.SourceChain, Tx: txHash.Hex()}) + log.Debugf("wait for tx %s", txHash.Hex()) + if err := wallet.WaitTransaction(ctx, txHash, ethClient); err != nil { + recordFn(provider.SwapHistory{Actions: sourceChainSentAction, Status: string(provider.TxStatusFailed), + CurrentChain: args.SourceChain, Tx: txHash.Hex()}) + return *sr, errors.Wrap(err, "wait for tx") + } + recordFn(provider.SwapHistory{Actions: sourceChainSentAction, Status: string(provider.TxStatusSuccess), + CurrentChain: args.SourceChain, Tx: txHash.Hex()}) + } + + var record HistoryRecord + if actionNumber <= 3 { + recordFn(provider.SwapHistory{Actions: targetChainSendingAction, Status: string(provider.TxStatusPending), + CurrentChain: args.SourceChain, Tx: txHash.Hex()}) + record, err = b.WaitForBridge(ctx, wallet.GetAddress(true), txHash) + if err != nil { + recordFn(provider.SwapHistory{Actions: targetChainSendingAction, Status: string(provider.TxStatusFailed), + CurrentChain: args.SourceChain, Tx: txHash.Hex()}) + sr.Error = err.Error() + return *sr, errors.Wrap(err, "wait for bridge") + } + log.Debugf("bridge result: %+v", record) + if record.Result != 3 { + recordFn(provider.SwapHistory{Actions: targetChainSendingAction, Status: string(provider.TxStatusFailed), + CurrentChain: args.SourceChain, Tx: txHash.Hex()}) + return *sr, errors.Errorf("bridge failed, result: %d", record.Result) + } + sr.Order = record + recordFn(provider.SwapHistory{Actions: targetChainReceivedAction, Status: string(provider.TxStatusSuccess), + CurrentChain: args.SourceChain, Tx: txHash.Hex()}) + sr.Status = provider.TxStatusSuccess + } + return *sr, nil +} + +func (b *Bridge) GetCost(ctx context.Context, args provider.SwapParams) (provider.TokenInCosts, error) { + if args.TargetChain == "" { + return nil, errors.Errorf("chain is empty") + } + if args.TargetToken == "" { + return nil, errors.Errorf("target token is empty") + } + + if args.SourceChain == "" { + sourceChainId, err := b.GetSourceChain(ctx, args.TargetChain, args.TargetToken, + args.Sender.GetAddress(true).Hex(), args.Amount) + if err != nil { + return nil, err + } + args.SourceChain = constant.GetChainName(sourceChainId) + } + if args.SourceToken == "" { + args.SourceToken = b.config.GetTokenInfoOnChain(args.TargetToken, args.SourceChain).Name + } + + if err := args.Sender.CheckFullAccess(ctx); err != nil { + return nil, errors.Errorf("wallet %s private key error: %s;", + args.Sender.GetAddress(true), err) + } + return provider.TokenInCosts{ + provider.TokenInCost{ + TokenName: args.TargetToken, + CostAmount: args.Amount, + }, + }, nil +} + +func (b *Bridge) CheckToken(ctx context.Context, tokenName, tokenInChainName, tokenOutChainName string, amount decimal.Decimal) (bool, error) { + supportedChains, err := GetTokenSupportedChains(tokenName) + if err != nil { + return false, err + } + for _, v := range supportedChains { + if v.FromChain == tokenInChainName && utils.InArrayFold(tokenOutChainName, v.ToChains) { + return true, nil + } + } + return false, nil +} + +func (b *Bridge) Help() []string { + return []string{"See https://helixbridge.app/"} +} + +func (b *Bridge) Name() string { + return "helixbridge" +} + +func (b *Bridge) Type() configs.LiquidityProviderType { + return configs.Bridge +} diff --git a/utils/provider/bridge/helix/init.go b/utils/provider/bridge/helix/init.go new file mode 100644 index 0000000..facb831 --- /dev/null +++ b/utils/provider/bridge/helix/init.go @@ -0,0 +1,45 @@ +package helix + +import ( + "omni-balance/utils/configs" + "omni-balance/utils/provider" +) + +func init() { + provider.Register(configs.Bridge, New) +} + +type BridgeType string + +const ( + LnV2DefaultType BridgeType = "lnv2-default" + LnV2OppositeType BridgeType = "lnv2-opposite" + LnV3Type BridgeType = "lnv3" + sourceChainSendingAction = "sourceChainSending" + sourceChainSentAction = "sourceChainSent" + targetChainSendingAction = "targetChainSending" + targetChainReceivedAction = "targetChainReceived" +) + +var ( + BRIDGES = map[BridgeType]func(opts Options) Transfer{ + LnV2DefaultType: NewV2Default, + LnV2OppositeType: NewV2Opposite, + LnV3Type: NewV3, + } +) + +func Action2Int(action string) int { + switch action { + case sourceChainSendingAction: + return 1 + case sourceChainSentAction: + return 2 + case targetChainSendingAction: + return 3 + case targetChainReceivedAction: + return 4 + default: + return 0 + } +} diff --git a/utils/provider/bridge/helix/lnv2_opposite.go b/utils/provider/bridge/helix/lnv2_opposite.go new file mode 100644 index 0000000..f6e034d --- /dev/null +++ b/utils/provider/bridge/helix/lnv2_opposite.go @@ -0,0 +1,70 @@ +package helix + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "math/big" + "omni-balance/utils/chains" + "omni-balance/utils/provider/bridge/helix/abi_v2_opposite" +) + +type V2Opposite struct { + opts Options +} + +func NewV2Opposite(opts Options) Transfer { + return &V2Opposite{opts: opts} +} + +func (v2 *V2Opposite) getContract(_, _ string) (common.Address, common.Address) { + return common.HexToAddress("0x48d769d5C7ff75703cDd1543A1a2ed9bC9044A23"), common.HexToAddress("0x48d769d5C7ff75703cDd1543A1a2ed9bC9044A23") +} + +func (v2 *V2Opposite) Do(_ context.Context, opts TransferOptions) (tx *types.LegacyTx, err error) { + var ( + sourceContractAddress, _ = v2.getContract(v2.opts.SourceChain, v2.opts.TargetChain) + targetChain = v2.opts.Config.GetChainConfig(v2.opts.TargetChain) + targetToken = v2.opts.Config.GetTokenInfoOnChain(v2.opts.TargetTokenName, v2.opts.TargetChain) + sourceToken = v2.opts.Config.GetTokenInfoOnChain(v2.opts.SourceTokenName, v2.opts.SourceChain) + isNativeToken = v2.opts.Config.IsNativeToken(v2.opts.SourceChain, sourceToken.Name) + transferId [32]byte + _ = copy(transferId[:], opts.TransferId.Bytes()) + snapshot = abi_v2_opposite.LnOppositeBridgeSourceSnapshot{ + RemoteChainId: big.NewInt(int64(targetChain.Id)), + Provider: opts.Relayer, + SourceToken: common.HexToAddress(sourceToken.ContractAddress), + TargetToken: common.HexToAddress(targetToken.ContractAddress), + TransferId: transferId, + TotalFee: opts.TotalFee.BigInt(), + DepositedMargin: opts.DepositedMargin.BigInt(), + } + ) + amount := decimal.NewFromBigInt(chains.EthToWei(v2.opts.Amount, sourceToken.Decimals), 0) + data, err := v2.transferAndLockMargin(snapshot, amount.BigInt(), v2.opts.Recipient) + if err != nil { + return nil, errors.Wrap(err, "transferAndLockMargin") + } + + a := &types.LegacyTx{ + To: &sourceContractAddress, + Value: amount.Add(opts.TotalFee).BigInt(), + Data: data, + } + if !isNativeToken { + a.Value = nil + } + return a, nil +} + +func (v2 *V2Opposite) transferAndLockMargin(_snapshot abi_v2_opposite.LnOppositeBridgeSourceSnapshot, + _amount *big.Int, _receiver common.Address) ([]byte, error) { + + abiObj, err := abi_v2_opposite.AbiV2OppositeMetaData.GetAbi() + if err != nil { + return nil, errors.Wrap(err, "GetAbi") + } + return abiObj.Pack("transferAndLockMargin", _snapshot, _amount, _receiver) +} diff --git a/utils/provider/bridge/helix/lnv2_opposite_test.go b/utils/provider/bridge/helix/lnv2_opposite_test.go new file mode 100644 index 0000000..eff07af --- /dev/null +++ b/utils/provider/bridge/helix/lnv2_opposite_test.go @@ -0,0 +1,85 @@ +package helix + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/shopspring/decimal" + "github.com/stretchr/testify/assert" + "omni-balance/utils/constant" + "testing" +) + +func TestV2Opposite_Do(t *testing.T) { + args := []struct { + name string + expectedData string + sourceChain string + targetChain string + amount decimal.Decimal + tokenName string + recipient common.Address + sender common.Address + relayer common.Address + transferId common.Hash + withdrawNonce uint64 + DepositedMargin decimal.Decimal + totalFee decimal.Decimal + to common.Address + }{ + { + name: "arbitrum->RING->ethereum", + expectedData: "2656c14700000000000000000000000000000000000000000000000000000000000000010000000000000000000000003b9e571adecb0c277486036d6097e9c2cccfa9d90000000000000000000000009e523234d36973f9e38642886197d023c88e307e0000000000000000000000009469d013805bffb7d3debe5e7839237e535ec48376a404f716bf0df99f9224f551175a2ab1d549b76d70f694b6b999a16ff3676100000000000000000000000000000000000000000000006cf0be29b1954b6400000000000000000000000000000000000000000000003f870857a3e0e38000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000178d8546c5f78e01133858958355b06ec3406a1a", + sourceChain: constant.Arbitrum, + targetChain: constant.Ethereum, + amount: decimal.New(0, 0), + tokenName: "RING", + recipient: common.HexToAddress("0x178D8546C5f78e01133858958355B06EC3406A1A"), + sender: common.HexToAddress("0x178D8546C5f78e01133858958355B06EC3406A1A"), + relayer: common.HexToAddress("0x3b9e571adecb0c277486036d6097e9c2cccfa9d9"), + transferId: common.HexToHash("0x76a404f716bf0df99f9224f551175a2ab1d549b76d70f694b6b999a16ff36761"), + totalFee: decimal.RequireFromString("2009595708618000000000"), + to: common.HexToAddress("0x48d769d5C7ff75703cDd1543A1a2ed9bC9044A23"), + DepositedMargin: decimal.RequireFromString("300000000000000000000000"), + }, + { + name: "darwinia-dvm->RING->ethereum", + expectedData: "2656c14700000000000000000000000000000000000000000000000000000000000000010000000000000000000000003b9e571adecb0c277486036d6097e9c2cccfa9d900000000000000000000000000000000000000000000000000000000000000000000000000000000000000009469d013805bffb7d3debe5e7839237e535ec4838cb641af960bee6a76f153defd3a6c19908f6f1e5aa68041f030e62b47d2d1b50000000000000000000000000000000000000000000000a3aedf842ccc11da00000000000000000000000000000000000000000000002a5a058fc295ed0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000178d8546c5f78e01133858958355b06ec3406a1a", + sourceChain: constant.DarwiniaDvm, + targetChain: constant.Ethereum, + amount: decimal.New(0, 0), + tokenName: "RING", + recipient: common.HexToAddress("0x178D8546C5f78e01133858958355B06EC3406A1A"), + sender: common.HexToAddress("0x178D8546C5f78e01133858958355B06EC3406A1A"), + relayer: common.HexToAddress("0x3b9e571adecb0c277486036d6097e9c2cccfa9d9"), + transferId: common.HexToHash("0x8cb641af960bee6a76f153defd3a6c19908f6f1e5aa68041f030e62b47d2d1b5"), + totalFee: decimal.RequireFromString("3019420219625000000000"), + to: common.HexToAddress("0x48d769d5C7ff75703cDd1543A1a2ed9bC9044A23"), + DepositedMargin: decimal.RequireFromString("200000000000000000000000"), + }, + } + + for _, arg := range args { + t.Run(arg.name, func(t *testing.T) { + v2 := NewV2Opposite(Options{ + SourceTokenName: arg.tokenName, + TargetTokenName: arg.tokenName, + SourceChain: arg.sourceChain, + TargetChain: arg.targetChain, + Config: *conf, + Sender: arg.sender, + Recipient: arg.recipient, + Amount: arg.amount, + }) + tx, err := v2.Do(context.Background(), TransferOptions{ + Relayer: arg.relayer, + TransferId: arg.transferId, + TotalFee: arg.totalFee, + WithdrawNonce: arg.withdrawNonce, + DepositedMargin: arg.DepositedMargin, + }) + assert.NoError(t, err) + assert.Equal(t, arg.expectedData, common.Bytes2Hex(tx.Data)) + assert.Equal(t, arg.to.String(), tx.To.String()) + }) + } +} diff --git a/utils/provider/bridge/helix/utils.go b/utils/provider/bridge/helix/utils.go new file mode 100644 index 0000000..da0cbc7 --- /dev/null +++ b/utils/provider/bridge/helix/utils.go @@ -0,0 +1,417 @@ +package helix + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "github.com/ethereum/go-ethereum/common" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "net/http" + "omni-balance/utils" + "omni-balance/utils/chains" + "omni-balance/utils/constant" + "omni-balance/utils/error_types" + "strings" + "sync" + "time" +) + +// WaitForBridge waits for the bridge transaction to be confirmed and retrieves the history record +// for the transaction. It uses a time ticker to periodically check for the record. If the context +// is canceled, it returns a context canceled error. Otherwise, it retrieves the history record and +// checks if it is a valid record. If the record is not valid, it returns the record and an error +// indicating the reason. Otherwise, it returns the record and nil error. +// +// Parameters: +// - ctx: The context for the operation +// - sender: The sender address +// - tx: The transaction hash +// +// Returns: +// - record: The history record +// - error: The error, or nil if the record is valid. +func (b *Bridge) WaitForBridge(ctx context.Context, sender common.Address, tx common.Hash) (HistoryRecord, error) { + var ( + t = time.NewTicker(time.Second * 3) + maxTry = 60 + tryCount int + ) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return HistoryRecord{}, context.Canceled + case <-t.C: + tryCount++ + if tryCount > maxTry { + return HistoryRecord{}, errors.New("wait for bridge timeout") + } + record, err := b.RetrieveHistoryRecords(sender, tx) + if err != nil && !errors.Is(err, error_types.ErrNotFound) { + logrus.Errorf("wait for bridge timeout, err: %s", err.Error()) + continue + } + if record.Result == 0 || record.ResponseTxHash == "" { + logrus.Debugf("wait for %s bridge, requests tx is %s, result: %d", sender.Hex(), tx.Hex(), record.Result) + continue + } + if record.Result == 3 { + return record, nil + } + return record, errors.Errorf("bridge failed, result: %d", record.Result) + } + } +} + +func (b *Bridge) RetrieveHistoryRecords(sender common.Address, tx common.Hash) (HistoryRecord, error) { + record, err := GetHistoryRecords(sender, tx) + if err != nil { + return HistoryRecord{}, err + } + return record, nil +} + +func (b *Bridge) IsValidRecord(record HistoryRecord) (string, bool) { + if record.ResponseTxHash == "" { + return "waiting for bridge", false + } + if record.Result == 0 { + return "", false + } + if record.Result != 3 { + return fmt.Sprintf("bridge failed, result: %d", record.Result), false + } + return "", true +} + +// GetValidChains checks the balance on each chain in the given list and filters out chains that do not meet +// the required balance. It retrieves the chain configuration and token information for each chain, and then +// creates an EVM client to interact with the chain. It calls the GetTokenBalance method to get the token balance +// for the specified wallet address. If the balance is greater than or equal to the required amount, the chain +// is considered valid and its chain ID is added to the validChains list. The method returns the list of valid +// chain IDs. +// +// Parameters: +// - ctx: The context for the operation +// - chains: The list of chain names to check +// - tokenName: The name of the token +// - wallet: The wallet address +// - amount: The required amount +// +// Returns: +// - validChains: The list of valid chain IDs +// +// Note: Chains with a chain ID of 0 or a token contract address of "" are considered invalid and are skipped. +func (b *Bridge) GetValidChains(ctx context.Context, targetChainName string, sourceChains []string, tokenName, + wallet string, amount decimal.Decimal) (validChains []int64) { + + var ( + w sync.WaitGroup + m sync.Mutex + ) + for _, chain := range sourceChains { + w.Add(1) + go func(chainName string) { + defer w.Done() + chain := b.config.GetChainConfig(chainName) + token := b.config.GetTokenInfoOnChain(tokenName, chainName) + if chain.Id == 0 || token.ContractAddress == "" { + return + } + client, err := chains.NewTryClient(ctx, chain.RpcEndpoints) + if err != nil { + logrus.Warnf("get %s chain client error: %s", chainName, err) + return + } + defer client.Close() + + balance, err := chains.GetTokenBalance(ctx, client, token.ContractAddress, wallet, token.Decimals) + if err != nil { + logrus.Warnf("get %s chain %s token balance error: %s", chainName, token.Name, err) + return + } + if !balance.GreaterThanOrEqual(amount) { + return + } + + maxLimit, err := GetMaxTransfer( + chainName, + targetChainName, + amount, + common.HexToAddress(token.ContractAddress), + ) + if err != nil { + logrus.Warnf("get %s chain %s token max transfer error: %s", chainName, token.Name, err) + return + } + if maxLimit.GreaterThanOrEqual(amount) && !maxLimit.Equal(decimal.Zero) { + return + } + m.Lock() + defer m.Unlock() + validChains = append(validChains, int64(constant.GetChainId(chainName))) + }(chain) + } + w.Wait() + return validChains +} + +// FindSourceChain selects the source chains that have a supported token and sufficient balance +// for swapping to the targetChain. It retrieves the supported chains for the given token, +// filters the chains based on the targetChain, and then checks the token balance on each +// remaining chain. If the balance is greater than or equal to the required amount, +// the chain is considered a valid source chain. The method returns a list of valid source chain IDs. +// It returns an error if there are no supported chains or if there is an error retrieving the supported chains. +// Parameters: +// - ctx: The context for the operation +// - targetChainName: The name of the target chain +// - TokenName: The name of the token +// - wallet: The wallet address +// - amount: The required amount +// Returns: +// - sourceChainIds: The list of valid source chain IDs +// - err: The error, or nil if there is no error +func (b *Bridge) FindSourceChain(ctx context.Context, targetChainName, TokenName, wallet string, + amount decimal.Decimal) (sourceChainIds []int64, err error) { + + supportedChains, err := GetTokenSupportedChains(TokenName) + if err != nil { + return nil, errors.Wrap(err, "get token supported chains") + } + var chains []string + for _, v := range supportedChains { + if !utils.InArrayFold(targetChainName, v.ToChains) { + continue + } + chains = append(chains, v.FromChain) + } + + // No supported chain + if len(chains) == 0 { + return nil, error_types.ErrUnsupportedTokenAndChain + } + + // Check other chains for the token balance + return b.GetValidChains(ctx, targetChainName, chains, TokenName, wallet, amount), nil +} + +// GetSourceChain retrieves the source chains that have a supported token and sufficient balance for swapping to the targetChain. +// It calls the FindSourceChain method to filter the chains that meet the requirements. +// If there are no supported chains or if there is an error retrieving the supported chains, it returns an error. +// Otherwise, it checks if there are valid source chain IDs. If there are no valid source chain IDs, it returns an error. +// Otherwise, it selects a source chain randomly and returns the source chain ID. +// +// Parameters: +// - ctx: The context for the operation +// - targetChainName: The name of the target chain +// - TokenName: The name of the token +// - wallet: The wallet address +// - amount: The required amount +// +// Returns: +// - sourceChainId: The selected source chain ID +// - err: The error, or nil if there is no error +func (b *Bridge) GetSourceChain(ctx context.Context, targetChainName, TokenName, wallet string, + amount decimal.Decimal) (sourceChainId int64, err error) { + + sourceChainIds, err := b.FindSourceChain(ctx, targetChainName, TokenName, wallet, amount) + if err != nil { + return 0, err + } + if len(sourceChainIds) == 0 { + return 0, error_types.ErrUnsupportedTokenAndChain + } + return utils.Choose(sourceChainIds), nil +} + +type SortedLnBridgeRelayInfosResult struct { + Data struct { + SortedLnBridgeRelayInfos struct { + TransferLimit string `json:"transferLimit"` + Records []struct { + SendToken common.Address `json:"sendToken"` + Relayer common.Address `json:"relayer"` + Margin decimal.Decimal `json:"margin"` + BaseFee decimal.Decimal `json:"baseFee"` + ProtocolFee decimal.Decimal `json:"protocolFee"` + LiquidityFeeRate decimal.Decimal `json:"liquidityFeeRate"` + LastTransferId common.Hash `json:"lastTransferId"` + WithdrawNonce decimal.Decimal `json:"withdrawNonce"` + Bridge string `json:"bridge"` + Typename string `json:"__typename"` + } `json:"records"` + Typename string `json:"__typename"` + } `json:"sortedLnBridgeRelayInfos"` + } `json:"data"` +} + +type SortedLnBridgeRelayInfoParams struct { + OperationName string `json:"operationName"` + Variables Variables `json:"variables"` + Query string `json:"query"` +} + +type Variables struct { + Amount string `json:"amount"` + Decimals int32 `json:"decimals"` + Token string `json:"token"` + FromChain string `json:"fromChain"` + ToChain string `json:"toChain"` +} + +// GetSortedLnBridgeRelayInfos amount must be wei +func GetSortedLnBridgeRelayInfos(amount decimal.Decimal, decimals int32, fromChain, toChain string, + token common.Address) (*SortedLnBridgeRelayInfosResult, error) { + + var query = "query sortedLnBridgeRelayInfos($amount: String, $decimals: Int, $bridge: String, $token: String, $fromChain: String, $toChain: String) {\n sortedLnBridgeRelayInfos(\n amount: $amount\n decimals: $decimals\n bridge: $bridge\n token: $token\n fromChain: $fromChain\n toChain: $toChain\n ) {\n transferLimit\n records {\n sendToken\n relayer\n margin\n baseFee\n protocolFee\n liquidityFeeRate\n lastTransferId\n withdrawNonce\n bridge\n __typename\n }\n __typename\n }\n}" + queryParams := SortedLnBridgeRelayInfoParams{ + OperationName: "sortedLnBridgeRelayInfos", + Variables: Variables{ + Amount: amount.String(), + Decimals: decimals, + Token: token.Hex(), + FromChain: fromChain, + ToChain: toChain, + }, + Query: query, + } + var body = bytes.NewBuffer(nil) + if err := json.NewEncoder(body).Encode(queryParams); err != nil { + return nil, err + } + resp, err := http.Post("https://apollo.helixbridge.app/graphql", "application/json", body) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var result = new(SortedLnBridgeRelayInfosResult) + if err := json.NewDecoder(resp.Body).Decode(result); err != nil { + return nil, err + } + return result, nil +} + +type HistoryRecordsParams struct { + OperationName string `json:"operationName"` + Variables HistoryRecordsVariables `json:"variables"` + Query string `json:"query"` +} + +type HistoryRecordsVariables struct { + Bridges []BridgeType `json:"bridges"` + Sender string `json:"sender"` + Row int `json:"row"` + Page int `json:"page"` +} + +func GetHistoryRecords(sender common.Address, tx common.Hash) (HistoryRecord, error) { + query := "query GetHistory($bridges: [String], $sender: String, $page: Int, $row: Int) {\n historyRecords(bridges: $bridges, sender: $sender, page: $page, row: $row) {\n total\n records {\n requestTxHash\n responseTxHash\n fromChain\n toChain\n startTime\n sendToken\n sendAmount\n confirmedBlocks\n result\n id\n __typename\n }\n __typename\n }\n}" + hrp := &HistoryRecordsParams{ + OperationName: "GetHistory", + Variables: HistoryRecordsVariables{ + Bridges: []BridgeType{ + LnV2DefaultType, + LnV2OppositeType, + LnV3Type, + }, + Sender: sender.Hex(), + Row: 0, + Page: 10, + }, + Query: query, + } + var body = bytes.NewBuffer(nil) + if err := json.NewEncoder(body).Encode(hrp); err != nil { + return HistoryRecord{}, err + } + resp, err := http.Post("https://apollo.helixbridge.app/graphql", "application/json", body) + if err != nil { + return HistoryRecord{}, err + } + defer resp.Body.Close() + var result = new(HistoryRecordsResult) + if err := json.NewDecoder(resp.Body).Decode(result); err != nil { + return HistoryRecord{}, err + } + for _, v := range result.Data.HistoryRecords.Records { + if !strings.EqualFold(v.RequestTxHash, tx.Hex()) { + continue + } + return v, nil + } + return HistoryRecord{}, error_types.ErrNotFound +} + +type GetSupportChainsResult struct { + Data struct { + QueryLnBridgeSupportChains []QueryLnBridgeSupportChains `json:"queryLnBridgeSupportChains"` + } `json:"data"` +} + +type QueryLnBridgeSupportChains struct { + FromChain string `json:"fromChain"` + ToChains []string `json:"toChains"` + Typename string `json:"__typename"` +} + +func GetTokenSupportedChains(tokenName string) ([]QueryLnBridgeSupportChains, error) { + var query = "query GetSupportChains($token: String!) {\n queryLnBridgeSupportChains(tokenKey: $token) {\n fromChain\n toChains\n __typename\n }\n}" + var queryBody = map[string]interface{}{ + "operationName": "GetSupportChains", + "query": query, + "variables": map[string]string{ + "token": strings.ToUpper(tokenName), + }, + } + var body = bytes.NewBuffer(nil) + if err := json.NewEncoder(body).Encode(queryBody); err != nil { + return nil, err + } + resp, err := http.Post("https://apollo.helixbridge.app/graphql", "application/json", body) + if err != nil { + return nil, err + } + defer resp.Body.Close() + var result GetSupportChainsResult + if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { + return nil, err + } + return result.Data.QueryLnBridgeSupportChains, nil +} + +func GetMaxTransfer(fromChain, toChain string, balance decimal.Decimal, + tokenAddress common.Address) (decimal.Decimal, error) { + + var query = "query GetMaxTransfer($token: String, $balance: String, $fromChain: String, $toChain: String) {\n queryMaxTransfer(\n token: $token\n balance: $balance\n fromChain: $fromChain\n toChain: $toChain\n )\n}" + var queryBody = map[string]interface{}{ + "operationName": "GetMaxTransfer", + "query": query, + "variables": map[string]string{ + "token": tokenAddress.Hex(), + "balance": balance.String(), + "fromChain": fromChain, + "toChain": toChain, + }, + } + var body = bytes.NewBuffer(nil) + if err := json.NewEncoder(body).Encode(queryBody); err != nil { + return decimal.Zero, err + } + resp, err := http.Post("https://apollo.helixbridge.app/graphql", "application/json", body) + if err != nil { + return decimal.Zero, err + } + defer resp.Body.Close() + var result = new(struct { + Data struct { + QueryMaxTransfer string `json:"queryMaxTransfer"` + } `json:"data"` + }) + if err := json.NewDecoder(resp.Body).Decode(result); err != nil { + return decimal.Zero, err + } + return decimal.NewFromString(result.Data.QueryMaxTransfer) +} diff --git a/utils/provider/bridge/helix/v2_default.go b/utils/provider/bridge/helix/v2_default.go new file mode 100644 index 0000000..72e9b92 --- /dev/null +++ b/utils/provider/bridge/helix/v2_default.go @@ -0,0 +1,90 @@ +package helix + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "math/big" + "omni-balance/utils/chains" + "omni-balance/utils/provider/bridge/helix/abi_v2_default" + "strings" +) + +type V2Default struct { + opts Options +} + +func NewV2Default(opts Options) Transfer { + return &V2Default{opts: opts} +} + +func (v *V2Default) getContract(sourceChain, targetChain string) ( + sourceContractAddress, targetContractAddress common.Address) { + + switch { + case strings.EqualFold("zksync", sourceChain): + sourceContractAddress = common.HexToAddress("0x767Bc046c989f5e63683fB530f939DD34b91ceAC") + targetContractAddress = common.HexToAddress("0x94C614DAeFDbf151E1BB53d6A201ae5fF56A9337") + case strings.EqualFold("zksync-sepolia", sourceChain): + sourceContractAddress = common.HexToAddress("0xBe23e871318E49C747CB909AC65aCCFAEAac3a37") + targetContractAddress = common.HexToAddress("0x8429D7Dfd91D6F970ba89fFC005e67D15f1E4739") + case strings.EqualFold("zksync-sepolia", targetChain): + sourceContractAddress = common.HexToAddress("0x8429D7Dfd91D6F970ba89fFC005e67D15f1E4739") + targetContractAddress = common.HexToAddress("0xBe23e871318E49C747CB909AC65aCCFAEAac3a37") + case strings.EqualFold("zksync", targetChain): + sourceContractAddress = common.HexToAddress("0x94C614DAeFDbf151E1BB53d6A201ae5fF56A9337") + targetContractAddress = common.HexToAddress("0x767Bc046c989f5e63683fB530f939DD34b91ceAC") + default: + sourceContractAddress = common.HexToAddress("0x94C614DAeFDbf151E1BB53d6A201ae5fF56A9337") + targetContractAddress = common.HexToAddress("0x94C614DAeFDbf151E1BB53d6A201ae5fF56A9337") + } + return +} + +func (v *V2Default) TransferAndLockMargin(_snapshot abi_v2_default.LnDefaultBridgeSourceSnapshot, + _amount *big.Int, _receiver common.Address) ([]byte, error) { + + abiObj, err := abi_v2_default.HelixMetaData.GetAbi() + if err != nil { + return nil, errors.Wrap(err, "GetAbi") + } + return abiObj.Pack("transferAndLockMargin", _snapshot, _amount, _receiver) +} + +func (v *V2Default) Do(_ context.Context, opts TransferOptions) (tx *types.LegacyTx, err error) { + var ( + sourceContractAddress, _ = v.getContract(v.opts.SourceChain, v.opts.TargetChain) + targetChain = v.opts.Config.GetChainConfig(v.opts.TargetChain) + targetToken = v.opts.Config.GetTokenInfoOnChain(v.opts.TargetTokenName, v.opts.TargetChain) + sourceToken = v.opts.Config.GetTokenInfoOnChain(v.opts.SourceTokenName, v.opts.SourceChain) + isNativeToken = v.opts.Config.IsNativeToken(v.opts.SourceChain, sourceToken.Name) + transferId [32]byte + _ = copy(transferId[:], opts.TransferId.Bytes()) + snapshot = abi_v2_default.LnDefaultBridgeSourceSnapshot{ + RemoteChainId: big.NewInt(int64(targetChain.Id)), + Provider: opts.Relayer, + SourceToken: common.HexToAddress(sourceToken.ContractAddress), + TargetToken: common.HexToAddress(targetToken.ContractAddress), + TransferId: transferId, + TotalFee: opts.TotalFee.BigInt(), + WithdrawNonce: opts.WithdrawNonce, + } + ) + amount := decimal.NewFromBigInt(chains.EthToWei(v.opts.Amount, sourceToken.Decimals), 0) + data, err := v.TransferAndLockMargin(snapshot, amount.BigInt(), v.opts.Recipient) + if err != nil { + return nil, errors.Wrap(err, "transferAndLockMargin") + } + + a := &types.LegacyTx{ + To: &sourceContractAddress, + Value: amount.Add(opts.TotalFee).BigInt(), + Data: data, + } + if !isNativeToken { + a.Value = nil + } + return a, nil +} diff --git a/utils/provider/bridge/helix/v2_default_test.go b/utils/provider/bridge/helix/v2_default_test.go new file mode 100644 index 0000000..0610b86 --- /dev/null +++ b/utils/provider/bridge/helix/v2_default_test.go @@ -0,0 +1,194 @@ +package helix + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/shopspring/decimal" + "github.com/stretchr/testify/assert" + "omni-balance/utils/configs" + "omni-balance/utils/constant" + "testing" +) + +var conf = &configs.Config{ + Chains: []configs.Chain{ + { + Name: "polygon", + RpcEndpoints: nil, + NativeToken: "MATIC", + Tokens: []configs.Token{ + { + Name: "RING", + ContractAddress: "0x9C1C23E60B72Bc88a043bf64aFdb16A02540Ae8f", + Decimals: 18, + }, + }, + Id: 137, + }, + + { + Name: "ethereum", + RpcEndpoints: nil, + NativeToken: "ETH", + Tokens: []configs.Token{ + { + Name: "RING", + ContractAddress: "0x9469d013805bffb7d3debe5e7839237e535ec483", + Decimals: 18, + }, + }, + Id: 1, + }, + { + Name: "darwinia", + RpcEndpoints: nil, + NativeToken: "RING", + Tokens: []configs.Token{ + { + Name: "RING", + ContractAddress: constant.ZeroAddress.Hex(), + Decimals: 18, + }, + }, + Id: 46, + }, + { + Name: "arbitrum", + RpcEndpoints: nil, + NativeToken: "ETH", + Tokens: []configs.Token{ + { + Name: "ETH", + ContractAddress: constant.ZeroAddress.Hex(), + Decimals: 18, + }, + { + Name: "RING", + ContractAddress: "0x9e523234D36973f9e38642886197D023C88e307e", + Decimals: 18, + }, + { + Name: "USDT", + ContractAddress: "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9", + Decimals: 6, + }, + }, + Id: 42161, + }, + { + Name: "op", + RpcEndpoints: nil, + Tokens: []configs.Token{ + { + Name: "USDT", + ContractAddress: "0x94b008aA00579c1307B0EF2c499aD98a8ce58e58", + Decimals: 6, + }, + }, + Id: 10, + }, + { + Name: "blast", + RpcEndpoints: nil, + Tokens: []configs.Token{ + { + Name: "ETH", + ContractAddress: constant.ZeroAddress.Hex(), + Decimals: 18, + }, + }, + Id: 81457, + }, + }, +} + +func init() { + conf.Init() +} + +func TestV2Default_Do(t *testing.T) { + args := []struct { + name string + expectedData string + sourceChain string + targetChain string + amount decimal.Decimal + tokenName string + recipient common.Address + sender common.Address + relayer common.Address + transferId common.Hash + withdrawNonce uint64 + totalFee decimal.Decimal + to common.Address + }{ + { + name: "ethereum->RING->darwinia-dvm", + expectedData: "0be175a5000000000000000000000000000000000000000000000000000000000000002e0000000000000000000000003b9e571adecb0c277486036d6097e9c2cccfa9d90000000000000000000000009469d013805bffb7d3debe5e7839237e535ec4830000000000000000000000000000000000000000000000000000000000000000ce6cf916269ec90c387e8fa1ef25b09296a310ea99a525872f9cc1e3b1f1080500000000000000000000000000000000000000000000001043561a882930000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000178d8546c5f78e01133858958355b06ec3406a1a", + sourceChain: "ethereum", + targetChain: "darwinia-dvm", + amount: decimal.New(0, 0), + tokenName: "RING", + recipient: common.HexToAddress("0x178D8546C5f78e01133858958355B06EC3406A1A"), + sender: common.HexToAddress("0x178D8546C5f78e01133858958355B06EC3406A1A"), + relayer: common.HexToAddress("0x3b9e571adecb0c277486036d6097e9c2cccfa9d9"), + transferId: common.HexToHash("0xce6cf916269ec90c387e8fa1ef25b09296a310ea99a525872f9cc1e3b1f10805"), + totalFee: decimal.RequireFromString("300000000000000000000"), + to: common.HexToAddress("0x94C614DAeFDbf151E1BB53d6A201ae5fF56A9337"), + }, + { + name: "arbitrum->RING->polygon", + expectedData: "0be175a500000000000000000000000000000000000000000000000000000000000000890000000000000000000000003b9e571adecb0c277486036d6097e9c2cccfa9d90000000000000000000000009e523234d36973f9e38642886197d023c88e307e0000000000000000000000009c1c23e60b72bc88a043bf64afdb16a02540ae8f71e5800b0122a77638334639f447eb4d85ce9e8256a090cbeb1e7839de15211a00000000000000000000000000000000000000000000000ad78ebc5ac620000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000178d8546c5f78e01133858958355b06ec3406a1a", + sourceChain: "arbitrum", + targetChain: "polygon", + amount: decimal.New(0, 0), + tokenName: "RING", + recipient: common.HexToAddress("0x178D8546C5f78e01133858958355B06EC3406A1A"), + sender: common.HexToAddress("0x178D8546C5f78e01133858958355B06EC3406A1A"), + relayer: common.HexToAddress("0x3b9e571adecb0c277486036d6097e9c2cccfa9d9"), + transferId: common.HexToHash("0x71e5800b0122a77638334639f447eb4d85ce9e8256a090cbeb1e7839de15211a"), + totalFee: decimal.RequireFromString("200000000000000000000"), + withdrawNonce: 1, + to: common.HexToAddress("0x94C614DAeFDbf151E1BB53d6A201ae5fF56A9337"), + }, + { + name: "arbitrum->RING->polygon", + expectedData: "0be175a500000000000000000000000000000000000000000000000000000000000000890000000000000000000000003b9e571adecb0c277486036d6097e9c2cccfa9d90000000000000000000000009e523234d36973f9e38642886197d023c88e307e0000000000000000000000009c1c23e60b72bc88a043bf64afdb16a02540ae8f71e5800b0122a77638334639f447eb4d85ce9e8256a090cbeb1e7839de15211a00000000000000000000000000000000000000000000000ad78ebc5ac620000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000178d8546c5f78e01133858958355b06ec3406a1a", + sourceChain: "arbitrum", + targetChain: "polygon", + amount: decimal.New(0, 0), + tokenName: "RING", + recipient: common.HexToAddress("0x178D8546C5f78e01133858958355B06EC3406A1A"), + sender: common.HexToAddress("0x178D8546C5f78e01133858958355B06EC3406A1A"), + relayer: common.HexToAddress("0x3b9e571adecb0c277486036d6097e9c2cccfa9d9"), + transferId: common.HexToHash("0x71e5800b0122a77638334639f447eb4d85ce9e8256a090cbeb1e7839de15211a"), + totalFee: decimal.RequireFromString("200000000000000000000"), + withdrawNonce: 1, + to: common.HexToAddress("0x94C614DAeFDbf151E1BB53d6A201ae5fF56A9337"), + }, + } + + for _, arg := range args { + t.Run(arg.name, func(t *testing.T) { + v2 := NewV2Default(Options{ + SourceTokenName: arg.tokenName, + TargetTokenName: arg.tokenName, + SourceChain: arg.sourceChain, + TargetChain: arg.targetChain, + Config: *conf, + Sender: arg.sender, + Recipient: arg.recipient, + Amount: arg.amount, + }) + tx, err := v2.Do(context.Background(), TransferOptions{ + Relayer: arg.relayer, + TransferId: arg.transferId, + TotalFee: arg.totalFee, + WithdrawNonce: arg.withdrawNonce, + }) + assert.NoError(t, err) + assert.Equal(t, arg.expectedData, common.Bytes2Hex(tx.Data)) + assert.Equal(t, arg.to.String(), tx.To.String()) + }) + } +} diff --git a/utils/provider/bridge/helix/v3.go b/utils/provider/bridge/helix/v3.go new file mode 100644 index 0000000..a1e5cc0 --- /dev/null +++ b/utils/provider/bridge/helix/v3.go @@ -0,0 +1,86 @@ +package helix + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "math/big" + "omni-balance/utils/chains" + "omni-balance/utils/provider/bridge/helix/abi_v3" + "strings" + "time" +) + +type V3 struct { + opts Options +} + +func NewV3(opts Options) Transfer { + return &V3{opts: opts} +} + +func (v *V3) getContract(sourceChain, targetChain string) (sourceAddress common.Address, targetAddress common.Address) { + sourceAddress = common.HexToAddress("0xbA5D580B18b6436411562981e02c8A9aA1776D10") + targetAddress = common.HexToAddress("0xbA5D580B18b6436411562981e02c8A9aA1776D10") + if strings.EqualFold(sourceChain, "blast") { + sourceAddress = common.HexToAddress("0xB180D7DcB5CC161C862aD60442FA37527546cAFC") + } + if strings.EqualFold(targetChain, "blast") { + targetAddress = common.HexToAddress("0xB180D7DcB5CC161C862aD60442FA37527546cAFC") + } + + if strings.EqualFold(sourceChain, "astar-zkevm") { + sourceAddress = common.HexToAddress("0xD476650e03a45E70202b0bcAfa04E1513920f83a") + } + if strings.EqualFold(targetChain, "astar-zkevm") { + targetAddress = common.HexToAddress("0xD476650e03a45E70202b0bcAfa04E1513920f83a") + } + return +} + +func (v *V3) Do(_ context.Context, opts TransferOptions) (tx *types.LegacyTx, err error) { + var ( + sourceContractAddress, _ = v.getContract(v.opts.SourceChain, v.opts.TargetChain) + targetChain = v.opts.Config.GetChainConfig(v.opts.TargetChain) + targetToken = v.opts.Config.GetTokenInfoOnChain(v.opts.TargetTokenName, v.opts.TargetChain) + sourceToken = v.opts.Config.GetTokenInfoOnChain(v.opts.SourceTokenName, v.opts.SourceChain) + isNativeToken = v.opts.Config.IsNativeToken(v.opts.SourceChain, v.opts.SourceTokenName) + ) + if opts.timestamp <= 0 { + opts.timestamp = time.Now().Unix() + } + amount := decimal.NewFromBigInt(chains.EthToWei(v.opts.Amount, sourceToken.Decimals), 0) + data, err := v.lockAndRemoteRelease(abi_v3.LnBridgeSourceV3TransferParams{ + RemoteChainId: big.NewInt(int64(targetChain.Id)), + Provider: opts.Relayer, + SourceToken: common.HexToAddress(sourceToken.ContractAddress), + TargetToken: common.HexToAddress(targetToken.ContractAddress), + TotalFee: opts.TotalFee.BigInt(), + Amount: amount.BigInt(), + Receiver: v.opts.Recipient, + Timestamp: big.NewInt(opts.timestamp), + }) + if err != nil { + return nil, errors.Wrap(err, "lockAndRemoteRelease") + } + + a := &types.LegacyTx{ + To: &sourceContractAddress, + Value: amount.Add(opts.TotalFee).BigInt(), + Data: data, + } + if !isNativeToken { + a.Value = nil + } + return a, nil +} + +func (v *V3) lockAndRemoteRelease(args abi_v3.LnBridgeSourceV3TransferParams) ([]byte, error) { + abiObj, err := abi_v3.AbiV3MetaData.GetAbi() + if err != nil { + return nil, errors.Wrap(err, "GetAbi") + } + return abiObj.Pack("lockAndRemoteRelease", args) +} diff --git a/utils/provider/bridge/helix/v3_test.go b/utils/provider/bridge/helix/v3_test.go new file mode 100644 index 0000000..4f1c2f5 --- /dev/null +++ b/utils/provider/bridge/helix/v3_test.go @@ -0,0 +1,112 @@ +package helix + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/shopspring/decimal" + "github.com/stretchr/testify/assert" + "math/big" + "testing" +) + +func TestV3_Do(t *testing.T) { + conf.Init() + args := []struct { + name string + expectedData string + sourceChain string + targetChain string + amount decimal.Decimal + tokenName string + recipient common.Address + sender common.Address + relayer common.Address + transferId common.Hash + withdrawNonce uint64 + DepositedMargin decimal.Decimal + totalFee decimal.Decimal + to common.Address + timestamp int64 + Value *big.Int + }{ + { + name: "arbitrum->USDT->op", + expectedData: "9cd13471000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000003b9e571adecb0c277486036d6097e9c2cccfa9d9000000000000000000000000fd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb900000000000000000000000094b008aa00579c1307b0ef2c499ad98a8ce58e580000000000000000000000000000000000000000000000000000000000061a800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000178d8546c5f78e01133858958355b06ec3406a1a00000000000000000000000000000000000000000000000000000000664434b9", + sourceChain: "arbitrum", + targetChain: "op", + amount: decimal.New(0, 0), + tokenName: "USDT", + recipient: common.HexToAddress("0x178D8546C5f78e01133858958355B06EC3406A1A"), + sender: common.HexToAddress("0x178D8546C5f78e01133858958355B06EC3406A1A"), + relayer: common.HexToAddress("0x3b9e571adecb0c277486036d6097e9c2cccfa9d9"), + transferId: common.HexToHash(""), + totalFee: decimal.RequireFromString("400000"), + to: common.HexToAddress("0xbA5D580B18b6436411562981e02c8A9aA1776D10"), + timestamp: 1715745977, + }, + { + name: "arbitrum->eth->blast", + expectedData: "9cd134710000000000000000000000000000000000000000000000000000000000013e310000000000000000000000003b9e571adecb0c277486036d6097e9c2cccfa9d900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000051dac207a0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000178d8546c5f78e01133858958355b06ec3406a1a00000000000000000000000000000000000000000000000000000000664437e2", + sourceChain: "arbitrum", + targetChain: "blast", + amount: decimal.New(0, 0), + tokenName: "ETH", + recipient: common.HexToAddress("0x178D8546C5f78e01133858958355B06EC3406A1A"), + sender: common.HexToAddress("0x178D8546C5f78e01133858958355B06EC3406A1A"), + relayer: common.HexToAddress("0x3b9e571adecb0c277486036d6097e9c2cccfa9d9"), + transferId: common.HexToHash(""), + totalFee: decimal.RequireFromString("90000000000000"), + to: common.HexToAddress("0xbA5D580B18b6436411562981e02c8A9aA1776D10"), + timestamp: 1715746786, + Value: big.NewInt(90000000000000), + }, + { + name: "darwinia-rng>arbitrum:v3", + expectedData: "9cd13471000000000000000000000000000000000000000000000000000000000000a4b1000000000000000000000000ec1d823af449b27f3e6fce58049d20b8e1c84fa500000000000000000000000000000000000000000000000000000000000000000000000000000000000000009e523234d36973f9e38642886197d023c88e307e0000000000000000000000000000000000000000000000174f766f41cebe80000000000000000000000000000000000000000000000000000de0b6b3a7640000000000000000000000000000178d8546c5f78e01133858958355b06ec3406a1a0000000000000000000000000000000000000000000000000000000066531c28", + sourceChain: "darwinia-dvm", + targetChain: "arbitrum", + amount: decimal.New(1, 0), + tokenName: "RING", + recipient: common.HexToAddress("0x178D8546C5f78e01133858958355B06EC3406A1A"), + sender: common.HexToAddress("0x178D8546C5f78e01133858958355B06EC3406A1A"), + relayer: common.HexToAddress("0xec1d823af449b27f3e6fce58049d20b8e1c84fa5"), + transferId: common.HexToHash(""), + totalFee: decimal.RequireFromString("430001000000000000000"), + to: common.HexToAddress("0xbA5D580B18b6436411562981e02c8A9aA1776D10"), + timestamp: 1716722728, + Value: decimal.RequireFromString("431001000000000000000").BigInt(), + }, + // 0错误:x9cd13471000000000000000000000000000000000000000000000000000000000000a4b1000000000000000000000000ec1d823af449b27f3e6fce58049d20b8e1c84fa500000000000000000000000000000000000000000000000000000000000000000000000000000000000000009e523234d36973f9e38642886197d023c88e307e0000000000000000000000000000000000000000000000174f72e1c329f800000000000000000000000000000000000000000000000000000de0b6b3a7640000000000000000000000000000178d8546c5f78e01133858958355b06ec3406a1a0000000000000000000000000000000000000000000000000000000066532283 + // 正确:0x9cd13471000000000000000000000000000000000000000000000000000000000000a4b1000000000000000000000000ec1d823af449b27f3e6fce58049d20b8e1c84fa500000000000000000000000000000000000000000000000000000000000000000000000000000000000000009e523234d36973f9e38642886197d023c88e307e0000000000000000000000000000000000000000000000174f766f41cebe80000000000000000000000000000000000000000000000000000de0b6b3a7640000000000000000000000000000178d8546c5f78e01133858958355b06ec3406a1a0000000000000000000000000000000000000000000000000000000066531c28 + // 正确:0x9cd13471000000000000000000000000000000000000000000000000000000000000a4b1000000000000000000000000ec1d823af449b27f3e6fce58049d20b8e1c84fa500000000000000000000000000000000000000000000000000000000000000000000000000000000000000009e523234d36973f9e38642886197d023c88e307e0000000000000000000000000000000000000000000000174f766f41cebe80000000000000000000000000000000000000000000000000000de0b6b3a7640000000000000000000000000000178d8546c5f78e01133858958355b06ec3406a1a00000000000000000000000000000000000000000000000000000000665323ec + // 正确:0x9cd13471000000000000000000000000000000000000000000000000000000000000a4b1000000000000000000000000ec1d823af449b27f3e6fce58049d20b8e1c84fa500000000000000000000000000000000000000000000000000000000000000000000000000000000000000009e523234d36973f9e38642886197d023c88e307e0000000000000000000000000000000000000000000000174f766f41cebe80000000000000000000000000000000000000000000000000000de0b6b3a7640000000000000000000000000000178d8546c5f78e01133858958355b06ec3406a1a0000000000000000000000000000000000000000000000000000000066531c28 + // 错误:0x9cd13471000000000000000000000000000000000000000000000000000000000000a4b1000000000000000000000000ec1d823af449b27f3e6fce58049d20b8e1c84fa500000000000000000000000000000000000000000000000000000000000000000000000000000000000000009e523234d36973f9e38642886197d023c88e307e0000000000000000000000000000000000000000000000174f72e1c329f800000000000000000000000000000000000000000000000000000de0b6b3a7640000000000000000000000000000178d8546c5f78e01133858958355b06ec3406a1a0000000000000000000000000000000000000000000000000000000066532374 + } + + for _, arg := range args { + t.Run(arg.name, func(t *testing.T) { + v3 := NewV3(Options{ + SourceTokenName: arg.tokenName, + TargetTokenName: arg.tokenName, + SourceChain: arg.sourceChain, + TargetChain: arg.targetChain, + Config: *conf, + Sender: arg.sender, + Recipient: arg.recipient, + Amount: arg.amount, + }) + tx, err := v3.Do(context.Background(), TransferOptions{ + Relayer: arg.relayer, + TransferId: arg.transferId, + TotalFee: arg.totalFee, + WithdrawNonce: arg.withdrawNonce, + DepositedMargin: arg.DepositedMargin, + timestamp: arg.timestamp, + }) + assert.NoError(t, err) + assert.Equal(t, arg.expectedData, common.Bytes2Hex(tx.Data)) + assert.Equal(t, arg.to.String(), tx.To.String()) + assert.Equal(t, tx.Value.String(), arg.Value.String()) + }) + } +} diff --git a/utils/provider/bridge/okx/okx.go b/utils/provider/bridge/okx/okx.go new file mode 100644 index 0000000..12f0e55 --- /dev/null +++ b/utils/provider/bridge/okx/okx.go @@ -0,0 +1,260 @@ +package okx + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "omni-balance/utils" + "omni-balance/utils/chains" + "omni-balance/utils/configs" + "omni-balance/utils/constant" + "omni-balance/utils/error_types" + "omni-balance/utils/provider" + "strings" +) + +func init() { + provider.Register(configs.Bridge, New) +} + +type OKX struct { + conf configs.Config + Key Config +} + +func New(conf configs.Config, noInit ...bool) (provider.Provider, error) { + o := new(OKX) + if len(noInit) > 0 && noInit[0] { + return o, nil + } + if err := conf.GetProvidersConfig(o.Name(), o.Type(), &o.Key); err != nil { + return nil, err + } + o.conf = conf + + return o, nil +} + +func (o *OKX) GetCost(ctx context.Context, args provider.SwapParams) (provider.TokenInCosts, error) { + var ( + err error + costAmount decimal.Decimal + ) + if args.SourceChain == "" || args.SourceToken == "" { + args.SourceToken, args.SourceChain, costAmount, err = o.GetBestTokenInChain(ctx, args) + if err != nil { + return nil, err + } + } + return provider.TokenInCosts{ + { + TokenName: args.SourceToken, + CostAmount: costAmount, + }, + }, nil +} + +func (o *OKX) CheckToken(ctx context.Context, tokenName, tokenInChainName, tokenOutChainName string, amount decimal.Decimal) (bool, error) { + tokenOut := o.conf.GetTokenInfoOnChain(tokenName, tokenOutChainName) + tokenIn := o.conf.GetTokenInfoOnChain(tokenName, tokenInChainName) + amountWei := decimal.NewFromBigInt(chains.EthToWei(decimal.RequireFromString("1"), tokenIn.Decimals), 0) + quote, err := o.Quote(ctx, QuoteParams{ + Amount: amountWei, + FormChainId: constant.GetChainId(tokenInChainName), + ToChainId: constant.GetChainId(tokenOutChainName), + ToTokenAddress: common.HexToAddress(tokenOut.ContractAddress), + FromTokenAddress: common.HexToAddress(tokenIn.ContractAddress), + }) + if err != nil { + return false, err + } + if len(quote.RouterList) == 0 { + return false, error_types.ErrUnsupportedTokenAndChain + } + return true, nil +} + +func (o *OKX) Swap(ctx context.Context, args provider.SwapParams) (provider.SwapResult, error) { + var ( + err error + targetChain = o.conf.GetChainConfig(args.TargetChain) + tokenOut = o.conf.GetTokenInfoOnChain(args.TargetToken, targetChain.Name) + tokenOutAmount = args.Amount + tokenOutAmountWei = decimal.NewFromBigInt(chains.EthToWei(tokenOutAmount, tokenOut.Decimals), 0) + tokenIn configs.Token + tokenInAmount decimal.Decimal + tokenInAmountWei decimal.Decimal + costAmount decimal.Decimal + history = args.LastHistory + tx = history.Tx + actionNumber = Action2Int(history.Actions) + isActionSuccess = history.Status == provider.TxStatusSuccess.String() + sourceChain configs.Chain + ) + + if args.SourceChain == "" || args.SourceToken == "" { + args.SourceToken, args.SourceChain, costAmount, err = o.GetBestTokenInChain(ctx, args) + if err != nil { + return provider.SwapResult{}, err + } + } + if args.SourceChain == "" { + return provider.SwapResult{}, errors.New("source chain is empty") + } + + tokenIn = o.conf.GetTokenInfoOnChain(args.SourceToken, args.SourceChain) + + if args.SourceToken != args.TargetToken { + tokenInAmount = costAmount + tokenInAmountWei = decimal.NewFromBigInt(chains.EthToWei(tokenInAmount, tokenIn.Decimals), 0) + } else { + tokenInAmount = tokenOutAmount + tokenInAmountWei = decimal.NewFromBigInt(chains.EthToWei(tokenInAmount, tokenIn.Decimals), 0) + } + sourceChain = o.conf.GetChainConfig(args.SourceChain) + isTokenInNative := o.conf.IsNativeToken(sourceChain.Name, tokenIn.Name) + + if tokenOutAmount.LessThanOrEqual(decimal.Zero) { + return provider.SwapResult{}, errors.New("token out amount is zero") + } + log := utils.GetLogFromCtx(ctx).WithFields(logrus.Fields{ + "sourceChain": sourceChain.Name, + "tokenIn": tokenIn.Name, + "targetChain": targetChain.Name, + "tokenOut": tokenOut.Name, + "tokenInAmount": tokenInAmount, + "wallet": args.Sender.GetAddress(), + "realOperatorAddress": args.Sender.GetAddress(true), + }) + + client, err := chains.NewTryClient(ctx, sourceChain.RpcEndpoints) + if err != nil { + return provider.SwapResult{}, err + } + var ( + result = new(provider.SwapResult).SetTokenInName(tokenIn.Name). + SetTokenInChainName(sourceChain.Name). + SetProviderType(o.Type()). + SetProviderName(o.Name()). + SetStatus(provider.TxStatusPending) + sh = &provider.SwapHistory{ + ProviderName: o.Name(), + ProviderType: string(o.Type()), + Amount: args.Amount, + } + ) + + if !isTokenInNative && actionNumber <= 1 && !isActionSuccess { + log.Debug("the source token is not native token, need approve") + approveTransaction, err := o.approveTransaction(ctx, sourceChain.Id, + common.HexToAddress(tokenIn.ContractAddress), tokenInAmountWei) + if err != nil { + err = errors.Wrap(err, "get approve transaction from okx error") + return result.SetError(err).SetStatus(provider.TxStatusFailed).Out(), err + } + log.Debugf("get approve transaction from okx, the spender is %s", approveTransaction.DexContractAddress) + sh = sh.SetActions(ApproveTransactionAction) + args.RecordFn(sh.SetStatus(provider.TxStatusPending).Out()) + err = chains.TokenApprove(ctx, chains.TokenApproveParams{ + ChainId: int64(sourceChain.Id), + TokenAddress: common.HexToAddress(tokenIn.ContractAddress), + Owner: args.Sender.GetAddress(true), + SendTransaction: args.Sender.SendTransaction, + WaitTransaction: args.Sender.WaitTransaction, + Spender: common.HexToAddress(approveTransaction.DexContractAddress), + // for save next gas, multiply 2 + AmountWei: tokenInAmountWei.Mul(decimal.RequireFromString("2")), + Client: client, + }) + if err != nil { + args.RecordFn(sh.SetStatus(provider.TxStatusFailed).Out(), err) + return result.SetError(err).SetStatus(provider.TxStatusFailed).Out(), err + } + log.Debugf("approve transaction success") + args.RecordFn(sh.SetStatus(provider.TxStatusSuccess).Out()) + } + + if !isActionSuccess && actionNumber <= 2 { + amount := args.Amount.Copy() + args.Amount = tokenInAmount + log = log.WithField("swap_params", utils.ToMap(args)) + log.Debug("start build tx") + buildTx, err := o.buildTx(ctx, args) + if err != nil { + return result.SetError(err).SetStatus(provider.TxStatusFailed).Out(), errors.Wrap(err, "build tx error") + } + + log.WithField("tx_data", buildTx.ToMap()).Debugf("get tx data from okx") + args.Amount = amount + if buildTx.ToTokenAmount.Div(tokenOutAmountWei).LessThan(decimal.RequireFromString("0.5")) { + err = errors.Errorf("minmum receive is too low, minmum receive: %s, amount: %s", + buildTx.ToTokenAmount, tokenOutAmountWei) + return result.SetError(err).SetStatus(provider.TxStatusFailed).Out(), err + } + if !isTokenInNative && !buildTx.Tx.Value.IsZero() { + err = errors.Errorf("tokenin is not native token, but value is not zero") + return result.SetError(err).SetStatus(provider.TxStatusFailed).Out(), err + } + if isTokenInNative && buildTx.Tx.Value.IsZero() { + err = errors.Errorf("tokenin is native token, but value is zero") + return result.SetError(err).SetStatus(provider.TxStatusFailed).Out(), err + } + if isTokenInNative && buildTx.Tx.Value.GreaterThan(tokenInAmountWei.Mul(decimal.RequireFromString("1.5"))) { + err = errors.Errorf("tx value is too high, tx value: %s, amount: %s", buildTx.Tx.Value, tokenInAmountWei) + return result.SetError(err).SetStatus(provider.TxStatusFailed).Out(), err + } + sh = sh.SetActions(SourceChainSendingAction) + args.RecordFn(sh.SetStatus(provider.TxStatusPending).Out()) + log.Debug("sending tx on chain") + //return provider.SwapResult{}, nil + txHash, err := args.Sender.SendTransaction(ctx, &types.LegacyTx{ + To: &buildTx.Tx.To, + Value: buildTx.Tx.Value.BigInt(), + Data: common.Hex2Bytes(strings.TrimPrefix(buildTx.Tx.Data, "0x")), + }, client) + if err != nil { + args.RecordFn(sh.SetStatus(provider.TxStatusFailed).Out(), err) + return result.SetError(err).SetStatus(provider.TxStatusFailed).Out(), errors.Wrap(err, "send tx error") + } + log = log.WithField("tx", txHash) + log.Debug("sending tx on chain success") + args.RecordFn(sh.SetStatus(provider.TxStatusSuccess).SetTx(txHash.Hex()).Out()) + tx = txHash.Hex() + } + result.Tx = tx + sh.SetActions(WaitForTxAction).SetTx(tx) + args.RecordFn(sh.SetStatus(provider.TxStatusPending).Out()) + log.Debugf("waiting for tx on chain") + if err := args.Sender.WaitTransaction(ctx, common.HexToHash(tx), client); err != nil { + args.RecordFn(sh.SetStatus(provider.TxStatusFailed).Out(), err) + return result.SetError(err).SetStatus(provider.TxStatusFailed).Out(), errors.Wrap(err, "wait tx error") + } + log.Debug("waiting for tx in okx") + if err := o.WaitForTx(ctx, common.HexToHash(tx), sourceChain.Id); err != nil { + args.RecordFn(sh.SetStatus(provider.TxStatusFailed).Out(), err) + return result.SetError(err).SetStatus(provider.TxStatusFailed).Out(), errors.Wrap(err, "wait okx error") + } + log.Debugf("waiting for tx success in okx") + args.RecordFn(sh.SetStatus(provider.TxStatusSuccess).SetCurrentChain(targetChain.Name).Out()) + return result.SetStatus(provider.TxStatusSuccess).SetCurrentChain(targetChain.Name).SetTx(tx).SetOrderId(tx).Out(), nil +} + +func (o *OKX) Help() []string { + var result []string + for _, v := range utils.ExtractTagFromStruct(&Config{}, "yaml", "help") { + result = append(result, v["yaml"]+": "+v["help"]) + } + result = append(result, "You can get these configs from https://www.okx.com/zh-hans/web3/build/docs/waas/introduction-to-developer-portal-interface") + return result +} + +func (o *OKX) Name() string { + return "okx" +} + +func (o *OKX) Type() configs.LiquidityProviderType { + return configs.Bridge +} diff --git a/utils/provider/bridge/okx/utils.go b/utils/provider/bridge/okx/utils.go new file mode 100644 index 0000000..51791d3 --- /dev/null +++ b/utils/provider/bridge/okx/utils.go @@ -0,0 +1,271 @@ +package okx + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "github.com/ethereum/go-ethereum/common" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "io" + "net/url" + "omni-balance/utils" + "omni-balance/utils/chains" + "omni-balance/utils/constant" + "omni-balance/utils/provider" + "strconv" + "strings" + "time" +) + +type QuoteParams struct { + Amount decimal.Decimal + FormChainId int + ToChainId int + ToTokenAddress common.Address + FromTokenAddress common.Address +} + +func (o *OKX) Quote(ctx context.Context, args QuoteParams) (QuoteData, error) { + var params = url.Values{} + params.Set("amount", args.Amount.String()) + params.Set("fromChainId", strconv.Itoa(args.FormChainId)) + params.Set("toChainId", strconv.Itoa(args.ToChainId)) + params.Set("toTokenAddress", StandardizeZeroAddress(args.ToTokenAddress).Hex()) + params.Set("fromTokenAddress", StandardizeZeroAddress(args.FromTokenAddress).Hex()) + // see https://www.okx.com/zh-hans/web3/build/docs/waas/dex-get-route-information + params.Set("slippage", "0.01") + var result OksResp + if err := o.request(ctx, "GET", "/api/v5/dex/cross-chain/quote", params, nil, &result); err != nil { + return QuoteData{}, errors.Wrap(err, "quote") + } + return result.Quote() +} + +func (o *OKX) request(ctx context.Context, method string, path string, params url.Values, body map[string]interface{}, dest *OksResp) error { + signature, timestamp := createSignature(method, path, params, body, o.Key.SecretKey) + headers := map[string]string{ + "OK-ACCESS-KEY": o.Key.ApiKey, + "OK-ACCESS-SIGN": signature, + "OK-ACCESS-TIMESTAMP": timestamp, + "OK-ACCESS-PASSPHRASE": o.Key.Passphrase, + "OK-ACCESS-PROJECT": o.Key.Project, + "content-type": "application/json", + } + var headersList []string + for k, v := range headers { + headersList = append(headersList, k, v) + } + var bodyReader io.Reader + if len(body) != 0 { + data, _ := json.Marshal(body) + bodyReader = bytes.NewReader(data) + } + u, _ := url.Parse("https://www.okx.com") + u.RawPath = path + u.Path = path + u.RawQuery = params.Encode() + utils.GetLogFromCtx(ctx).Debugf("request url: %s", u.String()) + if err := utils.Request(ctx, method, u.String(), bodyReader, dest, headersList...); err != nil { + return err + } + return dest.Error() +} + +func (o *OKX) GetBestTokenInChain(ctx context.Context, args provider.SwapParams) (tokenInName, tokenInChainName string, tokenInAmount decimal.Decimal, err error) { + log := utils.GetLogFromCtx(ctx) + if args.TargetToken == "" || args.TargetChain == "" { + return "", "", tokenInAmount, errors.New("target token or target chain is empty") + } + var ( + tokenOut = o.conf.GetTokenInfoOnChain(args.TargetToken, args.TargetChain) + ) + for _, sourceToken := range o.conf.SourceToken { + for _, v := range sourceToken.Chains { + if strings.EqualFold(v, args.TargetChain) && sourceToken.Name == args.TargetToken { + continue + } + currentLog := log.WithField("TokenIn", sourceToken.Name).WithField("sourceChain", v). + WithField("TargetToken", args.TargetToken).WithField("TargetChain", args.TargetChain) + currentLog.Debug("start check tokenIn") + chain := o.conf.GetChainConfig(v) + tokenIn := o.conf.GetTokenInfoOnChain(sourceToken.Name, v) + if tokenIn.ContractAddress == "" { + continue + } + client, err := chains.NewTryClient(ctx, chain.RpcEndpoints) + if err != nil { + currentLog.Debugf("new client error: %s", err) + continue + } + + tokenInTestBalance := decimal.RequireFromString("1") + tokenInTestBalanceWei := decimal.NewFromBigInt(chains.EthToWei(tokenInTestBalance, tokenIn.Decimals), 0) + quote, err := o.Quote(ctx, QuoteParams{ + Amount: tokenInTestBalanceWei, + FormChainId: chain.Id, + ToChainId: constant.GetChainId(args.TargetChain), + ToTokenAddress: common.HexToAddress(tokenOut.ContractAddress), + FromTokenAddress: common.HexToAddress(tokenIn.ContractAddress), + }) + if err != nil { + logrus.Debugf("get quote error: %s", err) + } + if len(quote.RouterList) == 0 { + currentLog.Debugf("no router list") + continue + } + currentLog = currentLog.WithField("quote", utils.ToMap(quote)) + currentLog.Debug("get quote success") + + minimumReceived := chains.WeiToEth(quote.RouterList[0].MinimumReceived.BigInt(), tokenOut.Decimals) + needBalance := tokenInTestBalance.Div(minimumReceived).Mul(args.Amount) + + balance, err := chains.GetTokenBalance(ctx, client, tokenIn.ContractAddress, + args.Sender.GetAddress(true).Hex(), tokenIn.Decimals) + if err != nil { + currentLog.Debugf("get balance error: %s", err) + continue + } + + log.Debugf("need %s balance: %s, wallet %s balance: %s on %s", + tokenIn.Name, needBalance, tokenIn.Name, balance, v) + if needBalance.GreaterThan(balance) { + currentLog.Debugf("%s need balance: %s, balance: %s", tokenIn.Name, needBalance, balance) + continue + } + if tokenInAmount.Equal(decimal.Zero) { + tokenInAmount = needBalance + } + if tokenInAmount.GreaterThan(needBalance) { + currentLog.Debugf("need balance: %s, balance: %s", needBalance, balance) + continue + } + tokenInAmount = needBalance + tokenInName = sourceToken.Name + tokenInChainName = v + } + } + log.Debugf("best tokenInName: %s, tokenInChainName: %s, tokenInAmount: %s", tokenInName, tokenInChainName, tokenInAmount) + return + +} + +func (o *OKX) approveTransaction(ctx context.Context, chainId int, tokenAddress common.Address, amountWei decimal.Decimal) (ApproveTransaction, error) { + params := &url.Values{} + params.Set("chainId", strconv.Itoa(chainId)) + params.Set("tokenContractAddress", tokenAddress.Hex()) + params.Set("approveAmount", amountWei.String()) + var result OksResp + if err := o.request(ctx, "GET", "/api/v5/dex/aggregator/approve-transaction", *params, nil, &result); err != nil { + return ApproveTransaction{}, err + } + return result.ApproveTransaction() +} + +func (o *OKX) buildTx(ctx context.Context, args provider.SwapParams) (BuildTxData, error) { + var ( + tokenIn = o.conf.GetTokenInfoOnChain(args.SourceToken, args.SourceChain) + tokenOut = o.conf.GetTokenInfoOnChain(args.TargetToken, args.TargetChain) + tokenInChain = o.conf.GetChainConfig(args.SourceChain) + tokenOutChain = o.conf.GetChainConfig(args.TargetChain) + amountWei = chains.EthToWei(args.Amount, tokenIn.Decimals) + ) + if tokenIn.Name == "" || + tokenOut.Name == "" || + tokenInChain.Name == "" || + tokenOutChain.Name == "" || + tokenIn.ContractAddress == "" || + tokenOut.ContractAddress == "" { + return BuildTxData{}, errors.New("token info is empty") + } + params := &url.Values{} + params.Set("fromChainId", strconv.Itoa(tokenInChain.Id)) + params.Set("toChainId", strconv.Itoa(tokenOutChain.Id)) + params.Set("fromTokenAddress", StandardizeZeroAddress(common.HexToAddress(tokenIn.ContractAddress)).Hex()) + params.Set("toTokenAddress", StandardizeZeroAddress(common.HexToAddress(tokenOut.ContractAddress)).Hex()) + params.Set("amount", amountWei.String()) + params.Set("slippage", "0.01") + params.Set("sort", "1") + params.Set("userWalletAddress", args.Sender.GetAddress(true).Hex()) + if args.Receiver != "" && !strings.EqualFold(args.Receiver, args.Sender.GetAddress(true).Hex()) { + params.Set("receiveAddress", args.Receiver) + } + var tx OksResp + if err := o.request(ctx, "GET", "/api/v5/dex/cross-chain/build-tx", *params, nil, &tx); err != nil { + return BuildTxData{}, err + } + return tx.BuildTx() +} + +func (o *OKX) TxStatus(ctx context.Context, hash common.Hash, sourceChainId int) (Status, error) { + params := &url.Values{} + params.Set("hash", hash.Hex()) + params.Set("chainId", strconv.Itoa(sourceChainId)) + var txStatus OksResp + if err := o.request(ctx, "GET", "/api/v5/dex/cross-chain/status", *params, nil, &txStatus); err != nil { + return Status{}, err + } + return txStatus.TxStatus() +} + +func (o *OKX) WaitForTx(ctx context.Context, hash common.Hash, sourceChainId int) error { + log := utils.GetLogFromCtx(ctx).WithFields(logrus.Fields{ + "chain_id": sourceChainId, + "hash": hash, + }) + var t = time.NewTicker(time.Second * 2) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return errors.New("context done") + case <-t.C: + s, err := o.TxStatus(ctx, hash, sourceChainId) + if err != nil { + return err + } + log = log.WithField("okx_ts_status", s.ToMap()) + log.Debugf("tx status: %s, detail status: %s", s.Status, okxWaitForTxStatus[s.DetailStatus]) + switch s.Status { + case "PENDING": + continue + case "SUCCESS": + return nil + case "FAILURE", "REFUND": + return errors.New(okxWaitForTxStatus[s.DetailStatus]) + default: + return errors.Errorf("unknown status: %s, detail status: %s", s.Status, s.DetailStatus) + } + } + } +} + +func sign(message, secretKey string) string { + h := hmac.New(sha256.New, []byte(secretKey)) + h.Write([]byte(message)) + return base64.StdEncoding.EncodeToString(h.Sum(nil)) +} + +func createSignature(method, requestPath string, params url.Values, body map[string]interface{}, secretKey string) (string, string) { + timestamp := time.Now().UTC().Format(time.RFC3339) + message := preHash(timestamp, method, requestPath, params, body) + signature := sign(message, secretKey) + return signature, timestamp +} + +func preHash(timestamp, method, requestPath string, params url.Values, body map[string]interface{}) string { + var queryString string + if params != nil { + queryString = "?" + params.Encode() + } + if body != nil { + data, _ := json.Marshal(body) + queryString = string(data) + } + return timestamp + method + requestPath + queryString +} diff --git a/utils/provider/bridge/okx/vars.go b/utils/provider/bridge/okx/vars.go new file mode 100644 index 0000000..f4bec86 --- /dev/null +++ b/utils/provider/bridge/okx/vars.go @@ -0,0 +1,299 @@ +package okx + +import ( + "encoding/json" + "github.com/ethereum/go-ethereum/common" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "omni-balance/utils/constant" +) + +var ( + ApproveTransactionAction = "ApproveTransaction" + SourceChainSendingAction = "sourceChainSending" + WaitForTxAction = "WaitForTx" +) + +var ( + /* + WAITING (订单处理中) + FROM_SUCCESS (源链订单成功) + BRIDGE_PENDING (跨链桥订单执行中) + SUCCESS (跨链兑换订单成功) + REFUND (订单退款) + FAILURE (订单失败) + */ + okxWaitForTxStatus = map[string]string{ + "WAITING": "order processing", + "FROM_SUCCESS": "source chain order success", + "BRIDGE_PENDING": "cross chain bridge order execution", + "SUCCESS": "cross chain exchange order success", + "REFUND": "order refund", + "FAILURE": "order failure", + } +) + +var okxZeroAddress = common.HexToAddress("0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE") + +type OksResp struct { + Code string `json:"code"` + Data interface{} `json:"data"` + Msg string `json:"msg"` +} + +func (o OksResp) ToInstance(dest interface{}) error { + data, _ := json.Marshal(o.Data) + return json.Unmarshal(data, dest) +} + +func (o OksResp) TxStatus() (Status, error) { + var s []Status + if err := o.ToInstance(&s); err != nil { + return Status{}, errors.Wrap(err, "unmarshal tx status") + } + if len(s) == 0 { + return Status{}, errors.New("empty tx status") + } + return s[0], nil +} + +func (o OksResp) ApproveTransaction() (ApproveTransaction, error) { + var result []ApproveTransaction + if err := o.ToInstance(&result); err != nil { + return ApproveTransaction{}, errors.Wrap(err, "unmarshal approve transaction") + } + if len(result) == 0 { + return ApproveTransaction{}, errors.New("empty approve transaction") + } + return result[0], nil +} + +func (o OksResp) BuildTx() (BuildTxData, error) { + var result []BuildTxData + if err := o.ToInstance(&result); err != nil { + return BuildTxData{}, errors.Wrap(err, "unmarshal build tx") + } + if len(result) == 0 { + return BuildTxData{}, errors.New("empty build tx") + } + return result[0], nil +} + +func (o OksResp) Quote() (QuoteData, error) { + var result []QuoteData + if err := o.ToInstance(&result); err != nil { + return QuoteData{}, errors.Wrap(err, "unmarshal quote") + } + if len(result) == 0 { + return QuoteData{}, errors.New("empty quote") + } + return result[0], nil +} + +type Status struct { + BridgeHash string `json:"bridgeHash"` + FromChainId int `json:"fromChainId"` + ToChainId int `json:"toChainId"` + //ToAmount decimal.Decimal `json:"toAmount"` + ErrorMsg string `json:"errorMsg"` + ToTxHash string `json:"toTxHash"` + FromTxHash string `json:"fromTxHash"` + SourceChainGasfee string `json:"sourceChainGasfee"` + DestinationChainGasfee string `json:"destinationChainGasfee"` + CrossChainFee struct { + Symbol string `json:"symbol"` + Address string `json:"address"` + Amount string `json:"amount"` + } `json:"crossChainFee"` + DetailStatus string `json:"detailStatus"` + Status string `json:"status"` +} + +type ApproveTransaction struct { + Data string `json:"data"` + DexContractAddress string `json:"dexContractAddress"` + GasLimit string `json:"gasLimit"` + GasPrice string `json:"gasPrice"` +} + +type BuildTxData struct { + FromTokenAmount string `json:"fromTokenAmount"` + Router struct { + BridgeId int `json:"bridgeId"` + BridgeName string `json:"bridgeName"` + CrossChainFee string `json:"crossChainFee"` + OtherNativeFee string `json:"otherNativeFee"` + CrossChainFeeTokenAddress string `json:"crossChainFeeTokenAddress"` + } `json:"router"` + ToTokenAmount decimal.Decimal `json:"toTokenAmount"` + Tx struct { + Data string `json:"data"` + From common.Address `json:"from"` + To common.Address `json:"to"` + Value decimal.Decimal `json:"value"` + GasLimit decimal.Decimal `json:"gasLimit"` + GasPrice decimal.Decimal `json:"gasPrice"` + MaxPriorityFeePerGas string `json:"maxPriorityFeePerGas"` + } `json:"tx"` +} + +type QuoteData struct { + FromChainId int `json:"fromChainId"` + FromToken struct { + Decimals int `json:"decimals"` + TokenContractAddress string `json:"tokenContractAddress"` + TokenSymbol string `json:"tokenSymbol"` + } `json:"fromToken"` + FromTokenAmount string `json:"fromTokenAmount"` + ToChainId int `json:"toChainId"` + ToToken struct { + Decimals int `json:"decimals"` + TokenContractAddress string `json:"tokenContractAddress"` + TokenSymbol string `json:"tokenSymbol"` + } `json:"toToken"` + RouterList []struct { + EstimateTime string `json:"estimateTime"` + FromDexRouterList []struct { + Router string `json:"router"` + RouterPercent string `json:"routerPercent"` + SubRouterList []struct { + DexProtocol []struct { + DexName string `json:"dexName"` + Percent string `json:"percent"` + } `json:"dexProtocol"` + FromToken struct { + Decimals int `json:"decimals"` + TokenContractAddress string `json:"tokenContractAddress"` + TokenSymbol string `json:"tokenSymbol"` + } `json:"fromToken"` + ToToken struct { + Decimals int `json:"decimals"` + TokenContractAddress string `json:"tokenContractAddress"` + TokenSymbol string `json:"tokenSymbol"` + } `json:"toToken"` + } `json:"subRouterList"` + } `json:"fromDexRouterList"` + MinimumReceived decimal.Decimal `json:"minimumReceived"` + NeedApprove int `json:"needApprove"` + Router struct { + BridgeId int `json:"bridgeId"` + BridgeName string `json:"bridgeName"` + CrossChainFee string `json:"crossChainFee"` + OtherNativeFee string `json:"otherNativeFee"` + CrossChainFeeTokenAddress string `json:"crossChainFeeTokenAddress"` + } `json:"router"` + ToDexRouterList []struct { + Router string `json:"router"` + RouterPercent string `json:"routerPercent"` + SubRouterList []struct { + DexProtocol []struct { + DexName string `json:"dexName"` + Percent string `json:"percent"` + } `json:"dexProtocol"` + FromToken struct { + Decimals int `json:"decimals"` + TokenContractAddress string `json:"tokenContractAddress"` + TokenSymbol string `json:"tokenSymbol"` + } `json:"fromToken"` + ToToken struct { + Decimals int `json:"decimals"` + TokenContractAddress string `json:"tokenContractAddress"` + TokenSymbol string `json:"tokenSymbol"` + } `json:"toToken"` + } `json:"subRouterList"` + } `json:"toDexRouterList"` + ToTokenAmount string `json:"toTokenAmount"` + } `json:"routerList"` +} + +type SupportedChain struct { + OksResp + Data []SupportedChainData `json:"data"` +} + +type SupportedChainData struct { + ChainId int `json:"chainId"` + ChainName string `json:"chainName"` + DexTokenApproveAddress string `json:"dexTokenApproveAddress"` +} + +type Config struct { + ApiKey string `json:"api_key" yaml:"api_key" comment:"api key"` + SecretKey string `json:"secret_key" yaml:"secret_key"` + Passphrase string `json:"passphrase" yaml:"passphrase"` + Project string `json:"project" yaml:"project"` +} + +func (r OksResp) Error() error { + if r.Code != "0" { + return errors.Errorf(r.Msg) + } + return nil +} + +func (s Status) ToMap() map[string]interface{} { + var result = make(map[string]interface{}) + data, _ := json.Marshal(s) + _ = json.Unmarshal(data, &result) + return result +} + +func (b BuildTxData) ToMap() map[string]interface{} { + var result = make(map[string]interface{}) + data, _ := json.Marshal(b) + _ = json.Unmarshal(data, &result) + return result +} + +func (s SupportedChain) Standardize() SupportedChain { + var result = &SupportedChain{ + OksResp: s.OksResp, + } + + for _, v := range s.Data { + chainName := constant.GetChainName(v.ChainId) + if chainName == "" { + continue + } + result.Data = append(result.Data, SupportedChainData{ + ChainId: v.ChainId, + ChainName: chainName, + DexTokenApproveAddress: v.DexTokenApproveAddress, + }) + } + return *result +} + +// StandardizeZeroAddress standardizes the zero address. +// If the provided zeroAddress is equal to constant.ZeroAddress, it returns okxZeroAddress; otherwise, it returns the original address. +// Parameter: +// zeroAddress common.Address - The address to be standardized. +// Return: +// common.Address - The standardized okxZeroAddress +func StandardizeZeroAddress(address common.Address) common.Address { + if address.Cmp(constant.ZeroAddress) == 0 { + return okxZeroAddress + } + return address +} + +// StandardizeZeroAddress2Evm standardizes the zero address to the okxZeroAddress. +func StandardizeZeroAddress2Evm(address common.Address) common.Address { + if address.Cmp(okxZeroAddress) == 0 { + return constant.ZeroAddress + } + return address +} + +func Action2Int(action string) int { + switch action { + case ApproveTransactionAction: + return 1 + case SourceChainSendingAction: + return 2 + case WaitForTxAction: + return 3 + default: + return 0 + } +} diff --git a/utils/provider/cex/gate/gate.io.go b/utils/provider/cex/gate/gate.io.go new file mode 100644 index 0000000..c455d8d --- /dev/null +++ b/utils/provider/cex/gate/gate.io.go @@ -0,0 +1,418 @@ +package gate + +import ( + "context" + "fmt" + "github.com/antihax/optional" + "github.com/gateio/gateapi-go/v6" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "omni-balance/utils" + "omni-balance/utils/configs" + "omni-balance/utils/error_types" + "omni-balance/utils/provider" + "strings" + "time" +) + +var ( + PurchasingAction = "purchasing" + PurchasedAction = "purchased" + WithdrawingAction = "withdrawing" + WithdrawnAction = "withdrawn" + + successStatus = "success" + pendingStatus = "pending" + failStatus = "fail" +) + +func StatusToInt(status string) int { + switch status { + case successStatus: + return 3 + case pendingStatus: + return 1 + case failStatus: + return 2 + default: + return 0 + } +} + +func Action2Int(action string) int { + switch action { + case PurchasingAction: + return 1 + case PurchasedAction: + return 2 + case WithdrawingAction: + return 3 + case WithdrawnAction: + return 4 + default: + return 0 + } +} + +type Gate struct { + authConfig gateConfig + config configs.Config + client *gateapi.APIClient +} + +type gateConfig struct { + Key string `json:"key" yaml:"key" help:"API key"` + Secret string `json:"secret" yaml:"secret" help:"API secret"` +} + +func New(conf configs.Config, noInit ...bool) (provider.Provider, error) { + if len(noInit) > 0 && noInit[0] { + return &Gate{}, nil + } + d := &Gate{ + config: conf, + } + + err := conf.GetProvidersConfig(d.Name(), configs.CEX, &d.authConfig) + if err != nil { + return nil, errors.Wrap(err, "get gate config") + } + c := gateapi.NewConfiguration() + c.Key = d.authConfig.Key + c.Secret = d.authConfig.Secret + d.client = gateapi.NewAPIClient(c) + _, _, err = d.client.AccountApi.GetAccountDetail(context.Background()) + if err != nil { + return nil, errors.Wrap(err, "init gate api") + } + return d, nil +} + +func (g *Gate) Swap(ctx context.Context, args provider.SwapParams) (provider.SwapResult, error) { + var ( + recordFn = func(s provider.SwapHistory, errs ...error) { + s.ProviderType = string(g.Type()) + s.ProviderName = g.Name() + s.Amount = args.Amount + if args.RecordFn == nil { + return + } + args.RecordFn(s, errs...) + } + log = logrus.WithFields(logrus.Fields{ + "provider": g.Name(), + "amount": args.Amount, + "tokenOut": args.TargetToken, + "targetChain": args.TargetChain, + }) + wallet = args.Sender + ) + + isSenderInVerifiedAddress, err := g.IsVerifiedAddress(ctx, wallet.GetAddress(true).Hex(), args.TargetToken, args.TargetChain) + if err != nil { + return provider.SwapResult{}, errors.Wrap(err, "check sender address") + } + if !isSenderInVerifiedAddress { + return provider.SwapResult{}, errors.Errorf("%s not in gate.io verified address for %s", + args.Sender, args.TargetToken) + } + + actionNumber := Action2Int(args.LastHistory.Actions) + + tokenInCosts, err := g.GetCost(ctx, args) + if err != nil { + return provider.SwapResult{}, err + } + log.Debugf("tokenInCosts: %+v", tokenInCosts) + tokenIn, err := tokenInCosts.GetBest() + if err != nil { + return provider.SwapResult{}, errors.Wrapf(err, "%s get best token in cost", g.Name()) + } + log.Debugf("get best token in cost: %s %s", tokenIn.TokenName, tokenIn.CostAmount) + + accounts, _, err := g.client.SpotApi.ListSpotAccounts(context.Background(), &gateapi.ListSpotAccountsOpts{}) + if err != nil { + return provider.SwapResult{}, errors.Wrap(err, "list spot accounts") + } + if len(accounts) == 0 { + return provider.SwapResult{}, errors.Errorf("no %s in spot account", tokenIn.TokenName) + } + var ( + buyAmount = args.Amount + tokenInAccount gateapi.SpotAccount + tokenOutAccount gateapi.SpotAccount + ) + if strings.EqualFold(tokenIn.TokenName, args.TargetToken) { + return provider.SwapResult{}, errors.Errorf("token in and token out are the same") + } + for _, account := range accounts { + log.Debugf("account: %+v, tokenInName: %s, tokenOutName: %s", account, tokenIn.TokenName, args.TargetToken) + if strings.EqualFold(account.Currency, tokenIn.TokenName) { + tokenInAccount = account + } + if strings.EqualFold(account.Currency, args.TargetToken) { + tokenOutAccount = account + continue + } + } + log.Debugf("token in account: %+v, token out account: %+v", tokenInAccount, tokenOutAccount) + + if actionNumber <= 1 && decimal.RequireFromString(tokenInAccount.Available).LessThan(tokenIn.CostAmount) { + return provider.SwapResult{}, errors.Errorf("not enough %s in spot account, available: %s, need: %s", + tokenIn.TokenName, tokenInAccount.Available, tokenIn.CostAmount) + } + + var result = &provider.SwapResult{ + ProviderType: g.Type(), + ProviderName: g.Name(), + TokenInName: tokenIn.TokenName, + OrderId: args.LastHistory.Tx, + } + + if buyAmount.GreaterThan(decimal.Zero) && actionNumber <= 1 && StatusToInt(args.LastHistory.Status) <= 2 { // buy token + recordFn(provider.SwapHistory{Actions: PurchasingAction, Status: pendingStatus}) + order, err := g.buyToken(ctx, tokenIn, args.TargetToken, buyAmount.Abs(), func(order gateapi.Order) bool { + logrus.Debugf("wait for order %s filled, the status is %s", order.Id, order.Status) + return false + }) + if err != nil { + recordFn(provider.SwapHistory{Actions: PurchasingAction, Status: failStatus}, err) + return provider.SwapResult{}, err + } + result.Order = order + result.OrderId = order.Id + recordFn(provider.SwapHistory{Actions: PurchasedAction, Status: successStatus, Tx: result.OrderId}) + } + + // 提现 + var withdrawOrderId = args.LastHistory.Tx + + if actionNumber < 4 && StatusToInt(args.LastHistory.Status) <= 2 { + balance, _ := decimal.NewFromString(tokenOutAccount.Available) + if balance.LessThanOrEqual(decimal.Zero) { + err = errors.Errorf("not enough %s in spot account", args.TargetToken) + recordFn(provider.SwapHistory{ + Actions: WithdrawingAction, Status: failStatus, CurrentChain: args.SourceChain, Tx: result.OrderId}, err) + return provider.SwapResult{}, err + } + if balance.LessThanOrEqual(args.Amount) { + args.Amount = balance + } + recordFn(provider.SwapHistory{Actions: WithdrawingAction, Status: pendingStatus, Tx: result.OrderId}) + withdrawOrder, _, err := g.client.WithdrawalApi.Withdraw(ctx, gateapi.LedgerRecord{ + Amount: args.Amount.String(), + Currency: args.TargetToken, + Address: wallet.GetAddress(true).Hex(), + Chain: ChainName2GateChainName(args.TargetChain), + }) + if err != nil { + recordFn(provider.SwapHistory{Actions: WithdrawingAction, Status: failStatus, CurrentChain: args.SourceChain, Tx: result.OrderId}, err) + return provider.SwapResult{}, errors.Wrap(err, "withdraw") + } + withdrawOrderId = withdrawOrder.Id + result.Order = withdrawOrder + recordFn(provider.SwapHistory{Actions: WithdrawnAction, Status: pendingStatus, CurrentChain: args.SourceChain, Tx: withdrawOrder.Id}) + } + + for { + logrus.Debugf("wait for %s withdraw order done", withdrawOrderId) + withdrawalRecords, _, err := g.client.WalletApi.ListWithdrawals(ctx, &gateapi.ListWithdrawalsOpts{ + Currency: optional.NewString(args.TargetToken), + }) + if err != nil { + return *result, errors.Wrap(err, "list withdraw status") + } + if len(withdrawalRecords) == 0 { + return *result, errors.Errorf("withdraw order not found") + } + var withdrawalRecord gateapi.WithdrawalRecord + for index, v := range withdrawalRecords { + if withdrawOrderId == "" && + strings.EqualFold(v.Chain, ChainName2GateChainName(args.TargetChain)) && + strings.EqualFold(v.Currency, args.TargetToken) { + withdrawalRecord = withdrawalRecords[index] + break + } + if v.Id == withdrawOrderId { + withdrawalRecord = withdrawalRecords[index] + break + } + } + if withdrawalRecord.Status == "" { + return *result, errors.Errorf("withdraw order not found") + } + switch strings.ToUpper(withdrawalRecord.Status) { + case "DONE": + recordFn(provider.SwapHistory{Actions: WithdrawnAction, Status: successStatus, CurrentChain: args.TargetChain, Tx: withdrawalRecord.Txid}) + result.Tx = withdrawalRecord.Txid + result.Status = provider.TxStatusSuccess + result.CurrentChain = args.TargetChain + result.OrderId = withdrawalRecord.Id + result.Order = withdrawalRecord + log.Infof("withdraw done, txid: %s", withdrawalRecord.Txid) + return *result, nil + case "CANCEL", "FAIL": + recordFn(provider.SwapHistory{ + Actions: WithdrawnAction, + Status: failStatus, + CurrentChain: args.SourceChain, + Tx: withdrawalRecord.Id}) + return *result, errors.Errorf("withdraw failed, status: %s", withdrawalRecord.Status) + case "REQUEST", "BCODE", "EXTPEND", "VERIFY", "PROCES", "PEND", "LOCKED": + time.Sleep(time.Second) + continue + default: + recordFn(provider.SwapHistory{ + Actions: WithdrawnAction, + Status: failStatus, + CurrentChain: args.SourceChain, + Tx: withdrawalRecord.Txid}) + return *result, errors.Errorf("unknown status: %+v", withdrawalRecord) + } + } +} + +func (g *Gate) GetCost(ctx context.Context, args provider.SwapParams) (provider.TokenInCosts, error) { + log := logrus.WithFields(logrus.Fields{ + "tokenOut": args.TargetToken, + "targetChain": args.TargetChain, + "amount": args.Amount, + "wallet": args.Sender, + }) + verifiedAddress, _, err := g.client.WalletApi.ListSavedAddress(ctx, args.TargetToken, &gateapi.ListSavedAddressOpts{}) + if err != nil { + return nil, errors.Wrap(err, "list saved address") + } + if len(verifiedAddress) == 0 { + return nil, errors.Errorf("%s not in gate.io verified address for %s", args.Sender, args.TargetToken) + } + chains, err := g.GetTokenOutChain(ctx, args.TargetToken) + if err != nil { + return nil, errors.Wrap(err, "get token out chains") + } + log.Debugf("token %s out chains: %+v", args.TargetToken, chains) + if !utils.InArray(args.TargetChain, chains) { + providers, err := provider.GetTokenCrossChainProviders(ctx, provider.GetTokenCrossChainProvidersParams{ + SourceChains: chains, + TargetChain: args.TargetChain, + TokenName: args.TargetToken, + Amount: args.Amount, + Conf: g.config, + }) + if err != nil { + return nil, errors.Wrap(err, "get token cross chain providers") + } + if len(providers) == 0 { + return nil, error_types.ErrUnsupportedTokenAndChain + } + } + + currency, _, err := g.client.SpotApi.GetCurrency(ctx, TokenName2GateTokenName(args.TargetToken)) + if err != nil { + return nil, errors.Wrap(err, "get currency") + } + log.Debugf("currency: %+v", currency) + if currency.Delisted || + currency.WithdrawDisabled { + return nil, error_types.ErrUnsupportedTokenAndChain + } + + // 检查是否有余额 + accounts, _, err := g.client.SpotApi.ListSpotAccounts(ctx, &gateapi.ListSpotAccountsOpts{}) + if err != nil { + return nil, errors.Wrap(err, "list spot accounts") + } + var ( + tokenIns []gateapi.SpotAccount + ) + + for index, v := range accounts { + log.Debugf("spot %s token balance: %s", v.Currency, v.Available) + if strings.EqualFold(v.Currency, TokenName2GateTokenName(args.TargetToken)) { + continue + } + for _, tokenIn := range g.config.SourceToken { + if !strings.EqualFold(v.Currency, tokenIn.Name) { + continue + } + tokenIns = append(tokenIns, accounts[index]) + continue + } + } + + currencyPairs, _, err := g.client.SpotApi.ListCurrencyPairs(ctx) + if err != nil { + return nil, errors.Wrap(err, "list currency pairs") + } + var ( + tokenInNames []string + pairs []string + ) + for _, v := range currencyPairs { + if !strings.EqualFold(v.Base, args.TargetToken) { + continue + } + for _, tokenIn := range tokenIns { + if !strings.EqualFold(tokenIn.Currency, v.Quote) { + continue + } + log.Debugf("currency pair: %s_%s", v.Base, v.Quote) + tokenInNames = append(tokenInNames, tokenIn.Currency) + pairs = append(pairs, strings.ToLower(fmt.Sprintf("%s_%s", v.Base, v.Quote))) + } + } + if len(tokenInNames) == 0 { + return nil, errors.Errorf("no token in") + } + + pairsList, err := g.Tickers(pairs...) + if err != nil { + return nil, errors.Wrap(err, "get market list") + } + if len(pairsList) == 0 { + return nil, errors.Errorf("no market list") + } + var providerTokenIns []provider.TokenInCost + for _, v := range pairsList { + if strings.EqualFold(v.TokenName, args.TargetToken) { + providerTokenIns = append(providerTokenIns, provider.TokenInCost{ + TokenName: strings.ToUpper(v.TokenName), + CostAmount: args.Amount, + }) + continue + } + providerTokenIns = append(providerTokenIns, provider.TokenInCost{ + TokenName: strings.ToUpper(v.TokenName), + CostAmount: v.Price.Mul(args.Amount), + }) + } + return providerTokenIns, nil +} + +func (g *Gate) CheckToken(ctx context.Context, tokenName, tokenInChainName, tokenOutChainName string, amount decimal.Decimal) (bool, error) { + // 检查token提现 + token, _, err := g.client.SpotApi.GetCurrency(ctx, TokenName2GateTokenName(tokenName)) + if err != nil { + return false, errors.Wrap(err, "get currency") + } + return !token.WithdrawDisabled, err +} + +func (g *Gate) Help() []string { + var result []string + for _, v := range utils.ExtractTagFromStruct(&gateConfig{}, "yaml", "help") { + result = append(result, v["yaml"]+": "+v["help"]) + } + result = append(result, "api key must be granted with the following permissions: Spot Trade, Wallet, Withdraw, Account") + result = append(result, "API Key Type must be selected as API v4 Key, and since gate.io has a limitation, it cannot be used with sub-accounts") + return result +} + +func (g *Gate) Name() string { + return "gate.io" +} + +func (g *Gate) Type() configs.LiquidityProviderType { + return configs.CEX +} diff --git a/utils/provider/cex/gate/init.go b/utils/provider/cex/gate/init.go new file mode 100644 index 0000000..9bed324 --- /dev/null +++ b/utils/provider/cex/gate/init.go @@ -0,0 +1,10 @@ +package gate + +import ( + "omni-balance/utils/configs" + "omni-balance/utils/provider" +) + +func init() { + provider.Register(configs.CEX, New) +} diff --git a/utils/provider/cex/gate/utils.go b/utils/provider/cex/gate/utils.go new file mode 100644 index 0000000..732b971 --- /dev/null +++ b/utils/provider/cex/gate/utils.go @@ -0,0 +1,203 @@ +package gate + +import ( + "context" + "encoding/json" + "fmt" + "github.com/antihax/optional" + "github.com/gateio/gateapi-go/v6" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "net/http" + "omni-balance/utils" + "omni-balance/utils/constant" + "omni-balance/utils/error_types" + "omni-balance/utils/provider" + "strings" + "time" +) + +var ( + gateChain2StandardName = map[string]string{ + "ETH": constant.Ethereum, + "ARBEVM": constant.Arbitrum, + "BSC": constant.Bsc, + "KAVAEVM": constant.Kava, + "MATIC": constant.Polygon, + "OPETH": constant.Optimism, + "CELO": constant.Celo, + "OPBNB": constant.OpBNB, + "BNB": constant.Bnb, + } + gateTokenName2StandardName = map[string]string{ + "ARBEVM": "ARB", + } +) + +type Ticker struct { + Low string `json:"low"` + Volume string `json:"volume"` + Last string `json:"last"` + Open string `json:"open"` + Deal string `json:"deal"` + Close string `json:"close"` + Change string `json:"change"` + High string `json:"high"` + Result string `json:"result"` + Avg float64 `json:"avg"` + RateChangePercentage string `json:"rate_change_percentage"` + RateChangePercentageUtc0 int `json:"rate_change_percentage_utc0"` + RateChangePercentageUtc8 int `json:"rate_change_percentage_utc8"` +} + +type TickerResult struct { + TokenName string + Price decimal.Decimal +} + +func TokenName2GateTokenName(tokenName string) string { + for k, v := range gateTokenName2StandardName { + if strings.EqualFold(tokenName, v) { + return k + } + } + return tokenName +} + +func ChainName2GateChainName(chainName string) string { + for k, v := range gateChain2StandardName { + if strings.EqualFold(chainName, v) { + return k + } + } + return chainName +} + +func (g *Gate) ticker(pairs string) (TickerResult, error) { + req, err := http.NewRequest("GET", fmt.Sprintf("https://data.gateapi.io/api/1/ticker/%s", pairs), nil) + if err != nil { + return TickerResult{}, err + } + req.Header.Set("content-type", "application/json") + resp, err := http.DefaultClient.Do(req) + if err != nil { + return TickerResult{}, err + } + defer resp.Body.Close() + var result = new(Ticker) + if err = json.NewDecoder(resp.Body).Decode(&result); err != nil { + return TickerResult{}, err + } + if !strings.EqualFold(result.Result, "true") { + return TickerResult{}, errors.Errorf("pairs %s not found", pairs) + } + pairsList := strings.Split(pairs, "_") + return TickerResult{ + TokenName: pairsList[1], + Price: decimal.RequireFromString(result.Last), + }, nil +} + +func (g *Gate) Tickers(pairs ...string) (result []TickerResult, err error) { + for _, v := range pairs { + ticker, err := g.ticker(v) + if err != nil { + return nil, errors.Wrap(err, "ticker") + } + result = append(result, ticker) + } + return result, nil +} + +func (g *Gate) GetTokenOutChain(ctx context.Context, token string) ([]string, error) { + chains, _, err := g.client.WalletApi.ListCurrencyChains(ctx, token) + if err != nil { + return nil, errors.Wrap(err, "list currency chains") + } + var supportedChains []string + for _, v := range chains { + if _, ok := gateChain2StandardName[v.Chain]; !ok { + logrus.Debugf("chain %s not supported in %s", v.Chain, token) + continue + } + if v.IsWithdrawDisabled == 1 { + continue + } + supportedChains = append(supportedChains, gateChain2StandardName[v.Chain]) + } + if len(supportedChains) == 0 { + return nil, error_types.ErrUnsupportedTokenAndChain + } + return supportedChains, nil +} + +func (g *Gate) buyToken(ctx context.Context, tokenIn provider.TokenInCost, targetToken string, amount decimal.Decimal, + f func(gateapi.Order) bool) (order gateapi.Order, err error) { + + currencyPair := utils.GetCurrencyPair(targetToken, "_", tokenIn.TokenName) + order = gateapi.Order{ + Text: "t-ob", + CurrencyPair: currencyPair, + Type: "limit", + Side: "buy", + Price: tokenIn.CostAmount.Div(amount).String(), + Amount: amount.String(), + } + logrus.WithFields(logrus.Fields{ + "order": order, + }).Debugf("buy token") + + // place order + order, _, err = g.client.SpotApi.CreateOrder(ctx, order) + if err != nil { + return order, errors.Wrap(err, "create order") + } + if order.Status == "cancelled" { + return order, errors.Errorf("order status is %s", order.Status) + } + // wait for order filled + for order.Status == "open" { + order, _, err = g.client.SpotApi.GetOrder(ctx, order.Id, fmt.Sprintf("%s_%s", tokenIn.TokenName, targetToken), nil) + if err != nil { + return order, errors.Wrap(err, "get order") + } + if order.Status == "closed" { + break + } + if f(order) { + break + } + time.Sleep(time.Second) + } + if order.Status == "cancelled" { + return order, errors.Errorf("order status is %s", order.Status) + } + return order, nil +} + +func (g *Gate) IsVerifiedAddress(ctx context.Context, address, tokenName, chainName string) (bool, error) { + verifiedAddress, _, err := g.client.WalletApi.ListSavedAddress(ctx, tokenName, + &gateapi.ListSavedAddressOpts{Chain: optional.NewString(ChainName2GateChainName(chainName))}) + if err != nil { + return false, errors.Wrap(err, "list saved address") + } + if len(verifiedAddress) == 0 { + return false, errors.Errorf("%s not in gate.io verified address for %s on %s", address, tokenName, chainName) + } + var ( + isSenderInVerifiedAddress bool + ) + for _, v := range verifiedAddress { + if v.Verified == "0" { + continue + } + if !strings.EqualFold(v.Address, address) || + !strings.EqualFold(v.Chain, ChainName2GateChainName(chainName)) { + continue + } + isSenderInVerifiedAddress = true + break + } + return isSenderInVerifiedAddress, nil +} diff --git a/utils/provider/dex/snowswap/snow_router/snow_router.go b/utils/provider/dex/snowswap/snow_router/snow_router.go new file mode 100644 index 0000000..1e93a8f --- /dev/null +++ b/utils/provider/dex/snowswap/snow_router/snow_router.go @@ -0,0 +1,776 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package snow_router + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription + _ = abi.ConvertType +) + +// SnowRouterMetaData contains all meta data concerning the SnowRouter contract. +var SnowRouterMetaData = &bind.MetaData{ + ABI: "[{\"type\":\"constructor\",\"inputs\":[{\"name\":\"_factory\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"_WETH\",\"type\":\"address\",\"internalType\":\"address\"}],\"stateMutability\":\"nonpayable\"},{\"name\":\"WETH\",\"type\":\"function\",\"inputs\":[],\"outputs\":[{\"name\":\"\",\"type\":\"address\",\"internalType\":\"address\"}],\"stateMutability\":\"view\"},{\"name\":\"addLiquidity\",\"type\":\"function\",\"inputs\":[{\"name\":\"tokenA\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"tokenB\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"amountADesired\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountBDesired\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountAMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountBMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"to\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"deadline\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"outputs\":[{\"name\":\"amountA\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountB\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"liquidity\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"stateMutability\":\"nonpayable\"},{\"name\":\"addLiquidityETH\",\"type\":\"function\",\"inputs\":[{\"name\":\"token\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"amountTokenDesired\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountTokenMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountETHMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"to\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"deadline\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"outputs\":[{\"name\":\"amountToken\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountETH\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"liquidity\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"stateMutability\":\"payable\"},{\"name\":\"factory\",\"type\":\"function\",\"inputs\":[],\"outputs\":[{\"name\":\"\",\"type\":\"address\",\"internalType\":\"address\"}],\"stateMutability\":\"view\"},{\"name\":\"getAmountIn\",\"type\":\"function\",\"inputs\":[{\"name\":\"amountOut\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"reserveIn\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"reserveOut\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"outputs\":[{\"name\":\"amountIn\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"stateMutability\":\"pure\"},{\"name\":\"getAmountOut\",\"type\":\"function\",\"inputs\":[{\"name\":\"amountIn\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"reserveIn\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"reserveOut\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"outputs\":[{\"name\":\"amountOut\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"stateMutability\":\"pure\"},{\"name\":\"getAmountsIn\",\"type\":\"function\",\"inputs\":[{\"name\":\"amountOut\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"path\",\"type\":\"address[]\",\"internalType\":\"address[]\"}],\"outputs\":[{\"name\":\"amounts\",\"type\":\"uint256[]\",\"internalType\":\"uint256[]\"}],\"stateMutability\":\"view\"},{\"name\":\"getAmountsOut\",\"type\":\"function\",\"inputs\":[{\"name\":\"amountIn\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"path\",\"type\":\"address[]\",\"internalType\":\"address[]\"}],\"outputs\":[{\"name\":\"amounts\",\"type\":\"uint256[]\",\"internalType\":\"uint256[]\"}],\"stateMutability\":\"view\"},{\"name\":\"quote\",\"type\":\"function\",\"inputs\":[{\"name\":\"amountA\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"reserveA\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"reserveB\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"outputs\":[{\"name\":\"amountB\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"stateMutability\":\"pure\"},{\"name\":\"removeLiquidity\",\"type\":\"function\",\"inputs\":[{\"name\":\"tokenA\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"tokenB\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"liquidity\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountAMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountBMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"to\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"deadline\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"outputs\":[{\"name\":\"amountA\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountB\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"stateMutability\":\"nonpayable\"},{\"name\":\"removeLiquidityETH\",\"type\":\"function\",\"inputs\":[{\"name\":\"token\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"liquidity\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountTokenMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountETHMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"to\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"deadline\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"outputs\":[{\"name\":\"amountToken\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountETH\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"stateMutability\":\"nonpayable\"},{\"name\":\"removeLiquidityETHSupportingFeeOnTransferTokens\",\"type\":\"function\",\"inputs\":[{\"name\":\"token\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"liquidity\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountTokenMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountETHMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"to\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"deadline\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"outputs\":[{\"name\":\"amountETH\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"stateMutability\":\"nonpayable\"},{\"name\":\"removeLiquidityETHWithPermit\",\"type\":\"function\",\"inputs\":[{\"name\":\"token\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"liquidity\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountTokenMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountETHMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"to\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"deadline\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"approveMax\",\"type\":\"bool\",\"internalType\":\"bool\"},{\"name\":\"v\",\"type\":\"uint8\",\"internalType\":\"uint8\"},{\"name\":\"r\",\"type\":\"bytes32\",\"internalType\":\"bytes32\"},{\"name\":\"s\",\"type\":\"bytes32\",\"internalType\":\"bytes32\"}],\"outputs\":[{\"name\":\"amountToken\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountETH\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"stateMutability\":\"nonpayable\"},{\"name\":\"removeLiquidityETHWithPermitSupportingFeeOnTransferTokens\",\"type\":\"function\",\"inputs\":[{\"name\":\"token\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"liquidity\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountTokenMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountETHMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"to\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"deadline\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"approveMax\",\"type\":\"bool\",\"internalType\":\"bool\"},{\"name\":\"v\",\"type\":\"uint8\",\"internalType\":\"uint8\"},{\"name\":\"r\",\"type\":\"bytes32\",\"internalType\":\"bytes32\"},{\"name\":\"s\",\"type\":\"bytes32\",\"internalType\":\"bytes32\"}],\"outputs\":[{\"name\":\"amountETH\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"stateMutability\":\"nonpayable\"},{\"name\":\"removeLiquidityWithPermit\",\"type\":\"function\",\"inputs\":[{\"name\":\"tokenA\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"tokenB\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"liquidity\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountAMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountBMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"to\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"deadline\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"approveMax\",\"type\":\"bool\",\"internalType\":\"bool\"},{\"name\":\"v\",\"type\":\"uint8\",\"internalType\":\"uint8\"},{\"name\":\"r\",\"type\":\"bytes32\",\"internalType\":\"bytes32\"},{\"name\":\"s\",\"type\":\"bytes32\",\"internalType\":\"bytes32\"}],\"outputs\":[{\"name\":\"amountA\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountB\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"stateMutability\":\"nonpayable\"},{\"name\":\"swapETHForExactTokens\",\"type\":\"function\",\"inputs\":[{\"name\":\"amountOut\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"path\",\"type\":\"address[]\",\"internalType\":\"address[]\"},{\"name\":\"to\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"deadline\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"outputs\":[{\"name\":\"amounts\",\"type\":\"uint256[]\",\"internalType\":\"uint256[]\"}],\"stateMutability\":\"payable\"},{\"name\":\"swapExactETHForTokens\",\"type\":\"function\",\"inputs\":[{\"name\":\"amountOutMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"path\",\"type\":\"address[]\",\"internalType\":\"address[]\"},{\"name\":\"to\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"deadline\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"outputs\":[{\"name\":\"amounts\",\"type\":\"uint256[]\",\"internalType\":\"uint256[]\"}],\"stateMutability\":\"payable\"},{\"name\":\"swapExactETHForTokensSupportingFeeOnTransferTokens\",\"type\":\"function\",\"inputs\":[{\"name\":\"amountOutMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"path\",\"type\":\"address[]\",\"internalType\":\"address[]\"},{\"name\":\"to\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"deadline\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"outputs\":[],\"stateMutability\":\"payable\"},{\"name\":\"swapExactTokensForETH\",\"type\":\"function\",\"inputs\":[{\"name\":\"amountIn\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountOutMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"path\",\"type\":\"address[]\",\"internalType\":\"address[]\"},{\"name\":\"to\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"deadline\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"outputs\":[{\"name\":\"amounts\",\"type\":\"uint256[]\",\"internalType\":\"uint256[]\"}],\"stateMutability\":\"nonpayable\"},{\"name\":\"swapExactTokensForETHSupportingFeeOnTransferTokens\",\"type\":\"function\",\"inputs\":[{\"name\":\"amountIn\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountOutMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"path\",\"type\":\"address[]\",\"internalType\":\"address[]\"},{\"name\":\"to\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"deadline\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"outputs\":[],\"stateMutability\":\"nonpayable\"},{\"name\":\"swapExactTokensForTokens\",\"type\":\"function\",\"inputs\":[{\"name\":\"amountIn\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountOutMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"path\",\"type\":\"address[]\",\"internalType\":\"address[]\"},{\"name\":\"to\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"deadline\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"outputs\":[{\"name\":\"amounts\",\"type\":\"uint256[]\",\"internalType\":\"uint256[]\"}],\"stateMutability\":\"nonpayable\"},{\"name\":\"swapExactTokensForTokensSupportingFeeOnTransferTokens\",\"type\":\"function\",\"inputs\":[{\"name\":\"amountIn\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountOutMin\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"path\",\"type\":\"address[]\",\"internalType\":\"address[]\"},{\"name\":\"to\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"deadline\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"outputs\":[],\"stateMutability\":\"nonpayable\"},{\"name\":\"swapTokensForExactETH\",\"type\":\"function\",\"inputs\":[{\"name\":\"amountOut\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountInMax\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"path\",\"type\":\"address[]\",\"internalType\":\"address[]\"},{\"name\":\"to\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"deadline\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"outputs\":[{\"name\":\"amounts\",\"type\":\"uint256[]\",\"internalType\":\"uint256[]\"}],\"stateMutability\":\"nonpayable\"},{\"name\":\"swapTokensForExactTokens\",\"type\":\"function\",\"inputs\":[{\"name\":\"amountOut\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"amountInMax\",\"type\":\"uint256\",\"internalType\":\"uint256\"},{\"name\":\"path\",\"type\":\"address[]\",\"internalType\":\"address[]\"},{\"name\":\"to\",\"type\":\"address\",\"internalType\":\"address\"},{\"name\":\"deadline\",\"type\":\"uint256\",\"internalType\":\"uint256\"}],\"outputs\":[{\"name\":\"amounts\",\"type\":\"uint256[]\",\"internalType\":\"uint256[]\"}],\"stateMutability\":\"nonpayable\"},{\"type\":\"receive\",\"stateMutability\":\"payable\"}]", +} + +// SnowRouterABI is the input ABI used to generate the binding from. +// Deprecated: Use SnowRouterMetaData.ABI instead. +var SnowRouterABI = SnowRouterMetaData.ABI + +// SnowRouter is an auto generated Go binding around an Ethereum contract. +type SnowRouter struct { + SnowRouterCaller // Read-only binding to the contract + SnowRouterTransactor // Write-only binding to the contract + SnowRouterFilterer // Log filterer for contract events +} + +// SnowRouterCaller is an auto generated read-only Go binding around an Ethereum contract. +type SnowRouterCaller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// SnowRouterTransactor is an auto generated write-only Go binding around an Ethereum contract. +type SnowRouterTransactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// SnowRouterFilterer is an auto generated log filtering Go binding around an Ethereum contract events. +type SnowRouterFilterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// SnowRouterSession is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type SnowRouterSession struct { + Contract *SnowRouter // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// SnowRouterCallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type SnowRouterCallerSession struct { + Contract *SnowRouterCaller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// SnowRouterTransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type SnowRouterTransactorSession struct { + Contract *SnowRouterTransactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// SnowRouterRaw is an auto generated low-level Go binding around an Ethereum contract. +type SnowRouterRaw struct { + Contract *SnowRouter // Generic contract binding to access the raw methods on +} + +// SnowRouterCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type SnowRouterCallerRaw struct { + Contract *SnowRouterCaller // Generic read-only contract binding to access the raw methods on +} + +// SnowRouterTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type SnowRouterTransactorRaw struct { + Contract *SnowRouterTransactor // Generic write-only contract binding to access the raw methods on +} + +// NewSnowRouter creates a new instance of SnowRouter, bound to a specific deployed contract. +func NewSnowRouter(address common.Address, backend bind.ContractBackend) (*SnowRouter, error) { + contract, err := bindSnowRouter(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &SnowRouter{SnowRouterCaller: SnowRouterCaller{contract: contract}, SnowRouterTransactor: SnowRouterTransactor{contract: contract}, SnowRouterFilterer: SnowRouterFilterer{contract: contract}}, nil +} + +// NewSnowRouterCaller creates a new read-only instance of SnowRouter, bound to a specific deployed contract. +func NewSnowRouterCaller(address common.Address, caller bind.ContractCaller) (*SnowRouterCaller, error) { + contract, err := bindSnowRouter(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &SnowRouterCaller{contract: contract}, nil +} + +// NewSnowRouterTransactor creates a new write-only instance of SnowRouter, bound to a specific deployed contract. +func NewSnowRouterTransactor(address common.Address, transactor bind.ContractTransactor) (*SnowRouterTransactor, error) { + contract, err := bindSnowRouter(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &SnowRouterTransactor{contract: contract}, nil +} + +// NewSnowRouterFilterer creates a new log filterer instance of SnowRouter, bound to a specific deployed contract. +func NewSnowRouterFilterer(address common.Address, filterer bind.ContractFilterer) (*SnowRouterFilterer, error) { + contract, err := bindSnowRouter(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &SnowRouterFilterer{contract: contract}, nil +} + +// bindSnowRouter binds a generic wrapper to an already deployed contract. +func bindSnowRouter(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := SnowRouterMetaData.GetAbi() + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_SnowRouter *SnowRouterRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _SnowRouter.Contract.SnowRouterCaller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_SnowRouter *SnowRouterRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _SnowRouter.Contract.SnowRouterTransactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_SnowRouter *SnowRouterRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _SnowRouter.Contract.SnowRouterTransactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_SnowRouter *SnowRouterCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _SnowRouter.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_SnowRouter *SnowRouterTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _SnowRouter.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_SnowRouter *SnowRouterTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _SnowRouter.Contract.contract.Transact(opts, method, params...) +} + +// WETH is a free data retrieval call binding the contract method 0xad5c4648. +// +// Solidity: function WETH() view returns(address) +func (_SnowRouter *SnowRouterCaller) WETH(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _SnowRouter.contract.Call(opts, &out, "WETH") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// WETH is a free data retrieval call binding the contract method 0xad5c4648. +// +// Solidity: function WETH() view returns(address) +func (_SnowRouter *SnowRouterSession) WETH() (common.Address, error) { + return _SnowRouter.Contract.WETH(&_SnowRouter.CallOpts) +} + +// WETH is a free data retrieval call binding the contract method 0xad5c4648. +// +// Solidity: function WETH() view returns(address) +func (_SnowRouter *SnowRouterCallerSession) WETH() (common.Address, error) { + return _SnowRouter.Contract.WETH(&_SnowRouter.CallOpts) +} + +// Factory is a free data retrieval call binding the contract method 0xc45a0155. +// +// Solidity: function factory() view returns(address) +func (_SnowRouter *SnowRouterCaller) Factory(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _SnowRouter.contract.Call(opts, &out, "factory") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// Factory is a free data retrieval call binding the contract method 0xc45a0155. +// +// Solidity: function factory() view returns(address) +func (_SnowRouter *SnowRouterSession) Factory() (common.Address, error) { + return _SnowRouter.Contract.Factory(&_SnowRouter.CallOpts) +} + +// Factory is a free data retrieval call binding the contract method 0xc45a0155. +// +// Solidity: function factory() view returns(address) +func (_SnowRouter *SnowRouterCallerSession) Factory() (common.Address, error) { + return _SnowRouter.Contract.Factory(&_SnowRouter.CallOpts) +} + +// GetAmountIn is a free data retrieval call binding the contract method 0x85f8c259. +// +// Solidity: function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) pure returns(uint256 amountIn) +func (_SnowRouter *SnowRouterCaller) GetAmountIn(opts *bind.CallOpts, amountOut *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) { + var out []interface{} + err := _SnowRouter.contract.Call(opts, &out, "getAmountIn", amountOut, reserveIn, reserveOut) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// GetAmountIn is a free data retrieval call binding the contract method 0x85f8c259. +// +// Solidity: function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) pure returns(uint256 amountIn) +func (_SnowRouter *SnowRouterSession) GetAmountIn(amountOut *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) { + return _SnowRouter.Contract.GetAmountIn(&_SnowRouter.CallOpts, amountOut, reserveIn, reserveOut) +} + +// GetAmountIn is a free data retrieval call binding the contract method 0x85f8c259. +// +// Solidity: function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) pure returns(uint256 amountIn) +func (_SnowRouter *SnowRouterCallerSession) GetAmountIn(amountOut *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) { + return _SnowRouter.Contract.GetAmountIn(&_SnowRouter.CallOpts, amountOut, reserveIn, reserveOut) +} + +// GetAmountOut is a free data retrieval call binding the contract method 0x054d50d4. +// +// Solidity: function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) pure returns(uint256 amountOut) +func (_SnowRouter *SnowRouterCaller) GetAmountOut(opts *bind.CallOpts, amountIn *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) { + var out []interface{} + err := _SnowRouter.contract.Call(opts, &out, "getAmountOut", amountIn, reserveIn, reserveOut) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// GetAmountOut is a free data retrieval call binding the contract method 0x054d50d4. +// +// Solidity: function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) pure returns(uint256 amountOut) +func (_SnowRouter *SnowRouterSession) GetAmountOut(amountIn *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) { + return _SnowRouter.Contract.GetAmountOut(&_SnowRouter.CallOpts, amountIn, reserveIn, reserveOut) +} + +// GetAmountOut is a free data retrieval call binding the contract method 0x054d50d4. +// +// Solidity: function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) pure returns(uint256 amountOut) +func (_SnowRouter *SnowRouterCallerSession) GetAmountOut(amountIn *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) { + return _SnowRouter.Contract.GetAmountOut(&_SnowRouter.CallOpts, amountIn, reserveIn, reserveOut) +} + +// GetAmountsIn is a free data retrieval call binding the contract method 0x1f00ca74. +// +// Solidity: function getAmountsIn(uint256 amountOut, address[] path) view returns(uint256[] amounts) +func (_SnowRouter *SnowRouterCaller) GetAmountsIn(opts *bind.CallOpts, amountOut *big.Int, path []common.Address) ([]*big.Int, error) { + var out []interface{} + err := _SnowRouter.contract.Call(opts, &out, "getAmountsIn", amountOut, path) + + if err != nil { + return *new([]*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new([]*big.Int)).(*[]*big.Int) + + return out0, err + +} + +// GetAmountsIn is a free data retrieval call binding the contract method 0x1f00ca74. +// +// Solidity: function getAmountsIn(uint256 amountOut, address[] path) view returns(uint256[] amounts) +func (_SnowRouter *SnowRouterSession) GetAmountsIn(amountOut *big.Int, path []common.Address) ([]*big.Int, error) { + return _SnowRouter.Contract.GetAmountsIn(&_SnowRouter.CallOpts, amountOut, path) +} + +// GetAmountsIn is a free data retrieval call binding the contract method 0x1f00ca74. +// +// Solidity: function getAmountsIn(uint256 amountOut, address[] path) view returns(uint256[] amounts) +func (_SnowRouter *SnowRouterCallerSession) GetAmountsIn(amountOut *big.Int, path []common.Address) ([]*big.Int, error) { + return _SnowRouter.Contract.GetAmountsIn(&_SnowRouter.CallOpts, amountOut, path) +} + +// GetAmountsOut is a free data retrieval call binding the contract method 0xd06ca61f. +// +// Solidity: function getAmountsOut(uint256 amountIn, address[] path) view returns(uint256[] amounts) +func (_SnowRouter *SnowRouterCaller) GetAmountsOut(opts *bind.CallOpts, amountIn *big.Int, path []common.Address) ([]*big.Int, error) { + var out []interface{} + err := _SnowRouter.contract.Call(opts, &out, "getAmountsOut", amountIn, path) + + if err != nil { + return *new([]*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new([]*big.Int)).(*[]*big.Int) + + return out0, err + +} + +// GetAmountsOut is a free data retrieval call binding the contract method 0xd06ca61f. +// +// Solidity: function getAmountsOut(uint256 amountIn, address[] path) view returns(uint256[] amounts) +func (_SnowRouter *SnowRouterSession) GetAmountsOut(amountIn *big.Int, path []common.Address) ([]*big.Int, error) { + return _SnowRouter.Contract.GetAmountsOut(&_SnowRouter.CallOpts, amountIn, path) +} + +// GetAmountsOut is a free data retrieval call binding the contract method 0xd06ca61f. +// +// Solidity: function getAmountsOut(uint256 amountIn, address[] path) view returns(uint256[] amounts) +func (_SnowRouter *SnowRouterCallerSession) GetAmountsOut(amountIn *big.Int, path []common.Address) ([]*big.Int, error) { + return _SnowRouter.Contract.GetAmountsOut(&_SnowRouter.CallOpts, amountIn, path) +} + +// Quote is a free data retrieval call binding the contract method 0xad615dec. +// +// Solidity: function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) pure returns(uint256 amountB) +func (_SnowRouter *SnowRouterCaller) Quote(opts *bind.CallOpts, amountA *big.Int, reserveA *big.Int, reserveB *big.Int) (*big.Int, error) { + var out []interface{} + err := _SnowRouter.contract.Call(opts, &out, "quote", amountA, reserveA, reserveB) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// Quote is a free data retrieval call binding the contract method 0xad615dec. +// +// Solidity: function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) pure returns(uint256 amountB) +func (_SnowRouter *SnowRouterSession) Quote(amountA *big.Int, reserveA *big.Int, reserveB *big.Int) (*big.Int, error) { + return _SnowRouter.Contract.Quote(&_SnowRouter.CallOpts, amountA, reserveA, reserveB) +} + +// Quote is a free data retrieval call binding the contract method 0xad615dec. +// +// Solidity: function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) pure returns(uint256 amountB) +func (_SnowRouter *SnowRouterCallerSession) Quote(amountA *big.Int, reserveA *big.Int, reserveB *big.Int) (*big.Int, error) { + return _SnowRouter.Contract.Quote(&_SnowRouter.CallOpts, amountA, reserveA, reserveB) +} + +// AddLiquidity is a paid mutator transaction binding the contract method 0xe8e33700. +// +// Solidity: function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns(uint256 amountA, uint256 amountB, uint256 liquidity) +func (_SnowRouter *SnowRouterTransactor) AddLiquidity(opts *bind.TransactOpts, tokenA common.Address, tokenB common.Address, amountADesired *big.Int, amountBDesired *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.contract.Transact(opts, "addLiquidity", tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline) +} + +// AddLiquidity is a paid mutator transaction binding the contract method 0xe8e33700. +// +// Solidity: function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns(uint256 amountA, uint256 amountB, uint256 liquidity) +func (_SnowRouter *SnowRouterSession) AddLiquidity(tokenA common.Address, tokenB common.Address, amountADesired *big.Int, amountBDesired *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.AddLiquidity(&_SnowRouter.TransactOpts, tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline) +} + +// AddLiquidity is a paid mutator transaction binding the contract method 0xe8e33700. +// +// Solidity: function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns(uint256 amountA, uint256 amountB, uint256 liquidity) +func (_SnowRouter *SnowRouterTransactorSession) AddLiquidity(tokenA common.Address, tokenB common.Address, amountADesired *big.Int, amountBDesired *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.AddLiquidity(&_SnowRouter.TransactOpts, tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline) +} + +// AddLiquidityETH is a paid mutator transaction binding the contract method 0xf305d719. +// +// Solidity: function addLiquidityETH(address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) payable returns(uint256 amountToken, uint256 amountETH, uint256 liquidity) +func (_SnowRouter *SnowRouterTransactor) AddLiquidityETH(opts *bind.TransactOpts, token common.Address, amountTokenDesired *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.contract.Transact(opts, "addLiquidityETH", token, amountTokenDesired, amountTokenMin, amountETHMin, to, deadline) +} + +// AddLiquidityETH is a paid mutator transaction binding the contract method 0xf305d719. +// +// Solidity: function addLiquidityETH(address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) payable returns(uint256 amountToken, uint256 amountETH, uint256 liquidity) +func (_SnowRouter *SnowRouterSession) AddLiquidityETH(token common.Address, amountTokenDesired *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.AddLiquidityETH(&_SnowRouter.TransactOpts, token, amountTokenDesired, amountTokenMin, amountETHMin, to, deadline) +} + +// AddLiquidityETH is a paid mutator transaction binding the contract method 0xf305d719. +// +// Solidity: function addLiquidityETH(address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) payable returns(uint256 amountToken, uint256 amountETH, uint256 liquidity) +func (_SnowRouter *SnowRouterTransactorSession) AddLiquidityETH(token common.Address, amountTokenDesired *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.AddLiquidityETH(&_SnowRouter.TransactOpts, token, amountTokenDesired, amountTokenMin, amountETHMin, to, deadline) +} + +// RemoveLiquidity is a paid mutator transaction binding the contract method 0xbaa2abde. +// +// Solidity: function removeLiquidity(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns(uint256 amountA, uint256 amountB) +func (_SnowRouter *SnowRouterTransactor) RemoveLiquidity(opts *bind.TransactOpts, tokenA common.Address, tokenB common.Address, liquidity *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.contract.Transact(opts, "removeLiquidity", tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline) +} + +// RemoveLiquidity is a paid mutator transaction binding the contract method 0xbaa2abde. +// +// Solidity: function removeLiquidity(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns(uint256 amountA, uint256 amountB) +func (_SnowRouter *SnowRouterSession) RemoveLiquidity(tokenA common.Address, tokenB common.Address, liquidity *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.RemoveLiquidity(&_SnowRouter.TransactOpts, tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline) +} + +// RemoveLiquidity is a paid mutator transaction binding the contract method 0xbaa2abde. +// +// Solidity: function removeLiquidity(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns(uint256 amountA, uint256 amountB) +func (_SnowRouter *SnowRouterTransactorSession) RemoveLiquidity(tokenA common.Address, tokenB common.Address, liquidity *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.RemoveLiquidity(&_SnowRouter.TransactOpts, tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline) +} + +// RemoveLiquidityETH is a paid mutator transaction binding the contract method 0x02751cec. +// +// Solidity: function removeLiquidityETH(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) returns(uint256 amountToken, uint256 amountETH) +func (_SnowRouter *SnowRouterTransactor) RemoveLiquidityETH(opts *bind.TransactOpts, token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.contract.Transact(opts, "removeLiquidityETH", token, liquidity, amountTokenMin, amountETHMin, to, deadline) +} + +// RemoveLiquidityETH is a paid mutator transaction binding the contract method 0x02751cec. +// +// Solidity: function removeLiquidityETH(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) returns(uint256 amountToken, uint256 amountETH) +func (_SnowRouter *SnowRouterSession) RemoveLiquidityETH(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.RemoveLiquidityETH(&_SnowRouter.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline) +} + +// RemoveLiquidityETH is a paid mutator transaction binding the contract method 0x02751cec. +// +// Solidity: function removeLiquidityETH(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) returns(uint256 amountToken, uint256 amountETH) +func (_SnowRouter *SnowRouterTransactorSession) RemoveLiquidityETH(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.RemoveLiquidityETH(&_SnowRouter.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline) +} + +// RemoveLiquidityETHSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0xaf2979eb. +// +// Solidity: function removeLiquidityETHSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) returns(uint256 amountETH) +func (_SnowRouter *SnowRouterTransactor) RemoveLiquidityETHSupportingFeeOnTransferTokens(opts *bind.TransactOpts, token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.contract.Transact(opts, "removeLiquidityETHSupportingFeeOnTransferTokens", token, liquidity, amountTokenMin, amountETHMin, to, deadline) +} + +// RemoveLiquidityETHSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0xaf2979eb. +// +// Solidity: function removeLiquidityETHSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) returns(uint256 amountETH) +func (_SnowRouter *SnowRouterSession) RemoveLiquidityETHSupportingFeeOnTransferTokens(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.RemoveLiquidityETHSupportingFeeOnTransferTokens(&_SnowRouter.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline) +} + +// RemoveLiquidityETHSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0xaf2979eb. +// +// Solidity: function removeLiquidityETHSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) returns(uint256 amountETH) +func (_SnowRouter *SnowRouterTransactorSession) RemoveLiquidityETHSupportingFeeOnTransferTokens(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.RemoveLiquidityETHSupportingFeeOnTransferTokens(&_SnowRouter.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline) +} + +// RemoveLiquidityETHWithPermit is a paid mutator transaction binding the contract method 0xded9382a. +// +// Solidity: function removeLiquidityETHWithPermit(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountToken, uint256 amountETH) +func (_SnowRouter *SnowRouterTransactor) RemoveLiquidityETHWithPermit(opts *bind.TransactOpts, token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _SnowRouter.contract.Transact(opts, "removeLiquidityETHWithPermit", token, liquidity, amountTokenMin, amountETHMin, to, deadline, approveMax, v, r, s) +} + +// RemoveLiquidityETHWithPermit is a paid mutator transaction binding the contract method 0xded9382a. +// +// Solidity: function removeLiquidityETHWithPermit(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountToken, uint256 amountETH) +func (_SnowRouter *SnowRouterSession) RemoveLiquidityETHWithPermit(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _SnowRouter.Contract.RemoveLiquidityETHWithPermit(&_SnowRouter.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline, approveMax, v, r, s) +} + +// RemoveLiquidityETHWithPermit is a paid mutator transaction binding the contract method 0xded9382a. +// +// Solidity: function removeLiquidityETHWithPermit(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountToken, uint256 amountETH) +func (_SnowRouter *SnowRouterTransactorSession) RemoveLiquidityETHWithPermit(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _SnowRouter.Contract.RemoveLiquidityETHWithPermit(&_SnowRouter.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline, approveMax, v, r, s) +} + +// RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x5b0d5984. +// +// Solidity: function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountETH) +func (_SnowRouter *SnowRouterTransactor) RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens(opts *bind.TransactOpts, token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _SnowRouter.contract.Transact(opts, "removeLiquidityETHWithPermitSupportingFeeOnTransferTokens", token, liquidity, amountTokenMin, amountETHMin, to, deadline, approveMax, v, r, s) +} + +// RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x5b0d5984. +// +// Solidity: function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountETH) +func (_SnowRouter *SnowRouterSession) RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _SnowRouter.Contract.RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens(&_SnowRouter.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline, approveMax, v, r, s) +} + +// RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x5b0d5984. +// +// Solidity: function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountETH) +func (_SnowRouter *SnowRouterTransactorSession) RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _SnowRouter.Contract.RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens(&_SnowRouter.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline, approveMax, v, r, s) +} + +// RemoveLiquidityWithPermit is a paid mutator transaction binding the contract method 0x2195995c. +// +// Solidity: function removeLiquidityWithPermit(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountA, uint256 amountB) +func (_SnowRouter *SnowRouterTransactor) RemoveLiquidityWithPermit(opts *bind.TransactOpts, tokenA common.Address, tokenB common.Address, liquidity *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _SnowRouter.contract.Transact(opts, "removeLiquidityWithPermit", tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline, approveMax, v, r, s) +} + +// RemoveLiquidityWithPermit is a paid mutator transaction binding the contract method 0x2195995c. +// +// Solidity: function removeLiquidityWithPermit(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountA, uint256 amountB) +func (_SnowRouter *SnowRouterSession) RemoveLiquidityWithPermit(tokenA common.Address, tokenB common.Address, liquidity *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _SnowRouter.Contract.RemoveLiquidityWithPermit(&_SnowRouter.TransactOpts, tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline, approveMax, v, r, s) +} + +// RemoveLiquidityWithPermit is a paid mutator transaction binding the contract method 0x2195995c. +// +// Solidity: function removeLiquidityWithPermit(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountA, uint256 amountB) +func (_SnowRouter *SnowRouterTransactorSession) RemoveLiquidityWithPermit(tokenA common.Address, tokenB common.Address, liquidity *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _SnowRouter.Contract.RemoveLiquidityWithPermit(&_SnowRouter.TransactOpts, tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline, approveMax, v, r, s) +} + +// SwapETHForExactTokens is a paid mutator transaction binding the contract method 0xfb3bdb41. +// +// Solidity: function swapETHForExactTokens(uint256 amountOut, address[] path, address to, uint256 deadline) payable returns(uint256[] amounts) +func (_SnowRouter *SnowRouterTransactor) SwapETHForExactTokens(opts *bind.TransactOpts, amountOut *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.contract.Transact(opts, "swapETHForExactTokens", amountOut, path, to, deadline) +} + +// SwapETHForExactTokens is a paid mutator transaction binding the contract method 0xfb3bdb41. +// +// Solidity: function swapETHForExactTokens(uint256 amountOut, address[] path, address to, uint256 deadline) payable returns(uint256[] amounts) +func (_SnowRouter *SnowRouterSession) SwapETHForExactTokens(amountOut *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.SwapETHForExactTokens(&_SnowRouter.TransactOpts, amountOut, path, to, deadline) +} + +// SwapETHForExactTokens is a paid mutator transaction binding the contract method 0xfb3bdb41. +// +// Solidity: function swapETHForExactTokens(uint256 amountOut, address[] path, address to, uint256 deadline) payable returns(uint256[] amounts) +func (_SnowRouter *SnowRouterTransactorSession) SwapETHForExactTokens(amountOut *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.SwapETHForExactTokens(&_SnowRouter.TransactOpts, amountOut, path, to, deadline) +} + +// SwapExactETHForTokens is a paid mutator transaction binding the contract method 0x7ff36ab5. +// +// Solidity: function swapExactETHForTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable returns(uint256[] amounts) +func (_SnowRouter *SnowRouterTransactor) SwapExactETHForTokens(opts *bind.TransactOpts, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.contract.Transact(opts, "swapExactETHForTokens", amountOutMin, path, to, deadline) +} + +// SwapExactETHForTokens is a paid mutator transaction binding the contract method 0x7ff36ab5. +// +// Solidity: function swapExactETHForTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable returns(uint256[] amounts) +func (_SnowRouter *SnowRouterSession) SwapExactETHForTokens(amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.SwapExactETHForTokens(&_SnowRouter.TransactOpts, amountOutMin, path, to, deadline) +} + +// SwapExactETHForTokens is a paid mutator transaction binding the contract method 0x7ff36ab5. +// +// Solidity: function swapExactETHForTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable returns(uint256[] amounts) +func (_SnowRouter *SnowRouterTransactorSession) SwapExactETHForTokens(amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.SwapExactETHForTokens(&_SnowRouter.TransactOpts, amountOutMin, path, to, deadline) +} + +// SwapExactETHForTokensSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0xb6f9de95. +// +// Solidity: function swapExactETHForTokensSupportingFeeOnTransferTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable returns() +func (_SnowRouter *SnowRouterTransactor) SwapExactETHForTokensSupportingFeeOnTransferTokens(opts *bind.TransactOpts, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.contract.Transact(opts, "swapExactETHForTokensSupportingFeeOnTransferTokens", amountOutMin, path, to, deadline) +} + +// SwapExactETHForTokensSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0xb6f9de95. +// +// Solidity: function swapExactETHForTokensSupportingFeeOnTransferTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable returns() +func (_SnowRouter *SnowRouterSession) SwapExactETHForTokensSupportingFeeOnTransferTokens(amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.SwapExactETHForTokensSupportingFeeOnTransferTokens(&_SnowRouter.TransactOpts, amountOutMin, path, to, deadline) +} + +// SwapExactETHForTokensSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0xb6f9de95. +// +// Solidity: function swapExactETHForTokensSupportingFeeOnTransferTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable returns() +func (_SnowRouter *SnowRouterTransactorSession) SwapExactETHForTokensSupportingFeeOnTransferTokens(amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.SwapExactETHForTokensSupportingFeeOnTransferTokens(&_SnowRouter.TransactOpts, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForETH is a paid mutator transaction binding the contract method 0x18cbafe5. +// +// Solidity: function swapExactTokensForETH(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_SnowRouter *SnowRouterTransactor) SwapExactTokensForETH(opts *bind.TransactOpts, amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.contract.Transact(opts, "swapExactTokensForETH", amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForETH is a paid mutator transaction binding the contract method 0x18cbafe5. +// +// Solidity: function swapExactTokensForETH(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_SnowRouter *SnowRouterSession) SwapExactTokensForETH(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.SwapExactTokensForETH(&_SnowRouter.TransactOpts, amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForETH is a paid mutator transaction binding the contract method 0x18cbafe5. +// +// Solidity: function swapExactTokensForETH(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_SnowRouter *SnowRouterTransactorSession) SwapExactTokensForETH(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.SwapExactTokensForETH(&_SnowRouter.TransactOpts, amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForETHSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x791ac947. +// +// Solidity: function swapExactTokensForETHSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns() +func (_SnowRouter *SnowRouterTransactor) SwapExactTokensForETHSupportingFeeOnTransferTokens(opts *bind.TransactOpts, amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.contract.Transact(opts, "swapExactTokensForETHSupportingFeeOnTransferTokens", amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForETHSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x791ac947. +// +// Solidity: function swapExactTokensForETHSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns() +func (_SnowRouter *SnowRouterSession) SwapExactTokensForETHSupportingFeeOnTransferTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.SwapExactTokensForETHSupportingFeeOnTransferTokens(&_SnowRouter.TransactOpts, amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForETHSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x791ac947. +// +// Solidity: function swapExactTokensForETHSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns() +func (_SnowRouter *SnowRouterTransactorSession) SwapExactTokensForETHSupportingFeeOnTransferTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.SwapExactTokensForETHSupportingFeeOnTransferTokens(&_SnowRouter.TransactOpts, amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForTokens is a paid mutator transaction binding the contract method 0x38ed1739. +// +// Solidity: function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_SnowRouter *SnowRouterTransactor) SwapExactTokensForTokens(opts *bind.TransactOpts, amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.contract.Transact(opts, "swapExactTokensForTokens", amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForTokens is a paid mutator transaction binding the contract method 0x38ed1739. +// +// Solidity: function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_SnowRouter *SnowRouterSession) SwapExactTokensForTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.SwapExactTokensForTokens(&_SnowRouter.TransactOpts, amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForTokens is a paid mutator transaction binding the contract method 0x38ed1739. +// +// Solidity: function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_SnowRouter *SnowRouterTransactorSession) SwapExactTokensForTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.SwapExactTokensForTokens(&_SnowRouter.TransactOpts, amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForTokensSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x5c11d795. +// +// Solidity: function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns() +func (_SnowRouter *SnowRouterTransactor) SwapExactTokensForTokensSupportingFeeOnTransferTokens(opts *bind.TransactOpts, amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.contract.Transact(opts, "swapExactTokensForTokensSupportingFeeOnTransferTokens", amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForTokensSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x5c11d795. +// +// Solidity: function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns() +func (_SnowRouter *SnowRouterSession) SwapExactTokensForTokensSupportingFeeOnTransferTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.SwapExactTokensForTokensSupportingFeeOnTransferTokens(&_SnowRouter.TransactOpts, amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForTokensSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x5c11d795. +// +// Solidity: function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns() +func (_SnowRouter *SnowRouterTransactorSession) SwapExactTokensForTokensSupportingFeeOnTransferTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.SwapExactTokensForTokensSupportingFeeOnTransferTokens(&_SnowRouter.TransactOpts, amountIn, amountOutMin, path, to, deadline) +} + +// SwapTokensForExactETH is a paid mutator transaction binding the contract method 0x4a25d94a. +// +// Solidity: function swapTokensForExactETH(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_SnowRouter *SnowRouterTransactor) SwapTokensForExactETH(opts *bind.TransactOpts, amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.contract.Transact(opts, "swapTokensForExactETH", amountOut, amountInMax, path, to, deadline) +} + +// SwapTokensForExactETH is a paid mutator transaction binding the contract method 0x4a25d94a. +// +// Solidity: function swapTokensForExactETH(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_SnowRouter *SnowRouterSession) SwapTokensForExactETH(amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.SwapTokensForExactETH(&_SnowRouter.TransactOpts, amountOut, amountInMax, path, to, deadline) +} + +// SwapTokensForExactETH is a paid mutator transaction binding the contract method 0x4a25d94a. +// +// Solidity: function swapTokensForExactETH(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_SnowRouter *SnowRouterTransactorSession) SwapTokensForExactETH(amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.SwapTokensForExactETH(&_SnowRouter.TransactOpts, amountOut, amountInMax, path, to, deadline) +} + +// SwapTokensForExactTokens is a paid mutator transaction binding the contract method 0x8803dbee. +// +// Solidity: function swapTokensForExactTokens(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_SnowRouter *SnowRouterTransactor) SwapTokensForExactTokens(opts *bind.TransactOpts, amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.contract.Transact(opts, "swapTokensForExactTokens", amountOut, amountInMax, path, to, deadline) +} + +// SwapTokensForExactTokens is a paid mutator transaction binding the contract method 0x8803dbee. +// +// Solidity: function swapTokensForExactTokens(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_SnowRouter *SnowRouterSession) SwapTokensForExactTokens(amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.SwapTokensForExactTokens(&_SnowRouter.TransactOpts, amountOut, amountInMax, path, to, deadline) +} + +// SwapTokensForExactTokens is a paid mutator transaction binding the contract method 0x8803dbee. +// +// Solidity: function swapTokensForExactTokens(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_SnowRouter *SnowRouterTransactorSession) SwapTokensForExactTokens(amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _SnowRouter.Contract.SwapTokensForExactTokens(&_SnowRouter.TransactOpts, amountOut, amountInMax, path, to, deadline) +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_SnowRouter *SnowRouterTransactor) Receive(opts *bind.TransactOpts) (*types.Transaction, error) { + return _SnowRouter.contract.RawTransact(opts, nil) // calldata is disallowed for receive function +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_SnowRouter *SnowRouterSession) Receive() (*types.Transaction, error) { + return _SnowRouter.Contract.Receive(&_SnowRouter.TransactOpts) +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_SnowRouter *SnowRouterTransactorSession) Receive() (*types.Transaction, error) { + return _SnowRouter.Contract.Receive(&_SnowRouter.TransactOpts) +} diff --git a/utils/provider/dex/snowswap/snowswap.go b/utils/provider/dex/snowswap/snowswap.go new file mode 100644 index 0000000..1d3df8f --- /dev/null +++ b/utils/provider/dex/snowswap/snowswap.go @@ -0,0 +1,41 @@ +package snowswap + +import ( + "context" + "github.com/shopspring/decimal" + "omni-balance/utils/configs" + "omni-balance/utils/provider" +) + +type Snowswap struct { +} + +func (s Snowswap) GetCost(ctx context.Context, args provider.SwapParams) (provider.TokenInCosts, error) { + //TODO implement me + panic("implement me") +} + +func (s Snowswap) CheckToken(ctx context.Context, tokenName, tokenInChainName, tokenOutChainName string, amount decimal.Decimal) (bool, error) { + //TODO implement me + panic("implement me") +} + +func (s Snowswap) Swap(ctx context.Context, args provider.SwapParams) (result provider.SwapResult, err error) { + //TODO implement me + panic("implement me") +} + +func (s Snowswap) Help() []string { + //TODO implement me + panic("implement me") +} + +func (s Snowswap) Name() string { + //TODO implement me + panic("implement me") +} + +func (s Snowswap) Type() configs.LiquidityProviderType { + //TODO implement me + panic("implement me") +} diff --git a/utils/provider/dex/uniswap/abi/permit2/permit2.go b/utils/provider/dex/uniswap/abi/permit2/permit2.go new file mode 100644 index 0000000..e4710e4 --- /dev/null +++ b/utils/provider/dex/uniswap/abi/permit2/permit2.go @@ -0,0 +1,1392 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package permit2 + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription + _ = abi.ConvertType +) + +// IAllowanceTransferAllowanceTransferDetails is an auto generated low-level Go binding around an user-defined struct. +type IAllowanceTransferAllowanceTransferDetails struct { + From common.Address + To common.Address + Amount *big.Int + Token common.Address +} + +// IAllowanceTransferPermitBatch is an auto generated low-level Go binding around an user-defined struct. +type IAllowanceTransferPermitBatch struct { + Details []IAllowanceTransferPermitDetails + Spender common.Address + SigDeadline *big.Int +} + +// IAllowanceTransferPermitDetails is an auto generated low-level Go binding around an user-defined struct. +type IAllowanceTransferPermitDetails struct { + Token common.Address + Amount *big.Int + Expiration *big.Int + Nonce *big.Int +} + +// IAllowanceTransferPermitSingle is an auto generated low-level Go binding around an user-defined struct. +type IAllowanceTransferPermitSingle struct { + Details IAllowanceTransferPermitDetails + Spender common.Address + SigDeadline *big.Int +} + +// IAllowanceTransferTokenSpenderPair is an auto generated low-level Go binding around an user-defined struct. +type IAllowanceTransferTokenSpenderPair struct { + Token common.Address + Spender common.Address +} + +// ISignatureTransferPermitBatchTransferFrom is an auto generated low-level Go binding around an user-defined struct. +type ISignatureTransferPermitBatchTransferFrom struct { + Permitted []ISignatureTransferTokenPermissions + Nonce *big.Int + Deadline *big.Int +} + +// ISignatureTransferPermitTransferFrom is an auto generated low-level Go binding around an user-defined struct. +type ISignatureTransferPermitTransferFrom struct { + Permitted ISignatureTransferTokenPermissions + Nonce *big.Int + Deadline *big.Int +} + +// ISignatureTransferSignatureTransferDetails is an auto generated low-level Go binding around an user-defined struct. +type ISignatureTransferSignatureTransferDetails struct { + To common.Address + RequestedAmount *big.Int +} + +// ISignatureTransferTokenPermissions is an auto generated low-level Go binding around an user-defined struct. +type ISignatureTransferTokenPermissions struct { + Token common.Address + Amount *big.Int +} + +// Permit2MetaData contains all meta data concerning the Permit2 contract. +var Permit2MetaData = &bind.MetaData{ + ABI: "[{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"AllowanceExpired\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"ExcessiveInvalidation\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"InsufficientAllowance\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"maxAmount\",\"type\":\"uint256\"}],\"name\":\"InvalidAmount\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidContractSignature\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidNonce\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidSignature\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidSignatureLength\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidSigner\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"LengthMismatch\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"signatureDeadline\",\"type\":\"uint256\"}],\"name\":\"SignatureExpired\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint160\",\"name\":\"amount\",\"type\":\"uint160\"},{\"indexed\":false,\"internalType\":\"uint48\",\"name\":\"expiration\",\"type\":\"uint48\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"Lockdown\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint48\",\"name\":\"newNonce\",\"type\":\"uint48\"},{\"indexed\":false,\"internalType\":\"uint48\",\"name\":\"oldNonce\",\"type\":\"uint48\"}],\"name\":\"NonceInvalidation\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint160\",\"name\":\"amount\",\"type\":\"uint160\"},{\"indexed\":false,\"internalType\":\"uint48\",\"name\":\"expiration\",\"type\":\"uint48\"},{\"indexed\":false,\"internalType\":\"uint48\",\"name\":\"nonce\",\"type\":\"uint48\"}],\"name\":\"Permit\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"word\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"mask\",\"type\":\"uint256\"}],\"name\":\"UnorderedNonceInvalidation\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"DOMAIN_SEPARATOR\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint160\",\"name\":\"amount\",\"type\":\"uint160\"},{\"internalType\":\"uint48\",\"name\":\"expiration\",\"type\":\"uint48\"},{\"internalType\":\"uint48\",\"name\":\"nonce\",\"type\":\"uint48\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint160\",\"name\":\"amount\",\"type\":\"uint160\"},{\"internalType\":\"uint48\",\"name\":\"expiration\",\"type\":\"uint48\"}],\"name\":\"approve\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint48\",\"name\":\"newNonce\",\"type\":\"uint48\"}],\"name\":\"invalidateNonces\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"wordPos\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"mask\",\"type\":\"uint256\"}],\"name\":\"invalidateUnorderedNonces\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"internalType\":\"structIAllowanceTransfer.TokenSpenderPair[]\",\"name\":\"approvals\",\"type\":\"tuple[]\"}],\"name\":\"lockdown\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"nonceBitmap\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"components\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint160\",\"name\":\"amount\",\"type\":\"uint160\"},{\"internalType\":\"uint48\",\"name\":\"expiration\",\"type\":\"uint48\"},{\"internalType\":\"uint48\",\"name\":\"nonce\",\"type\":\"uint48\"}],\"internalType\":\"structIAllowanceTransfer.PermitDetails[]\",\"name\":\"details\",\"type\":\"tuple[]\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"sigDeadline\",\"type\":\"uint256\"}],\"internalType\":\"structIAllowanceTransfer.PermitBatch\",\"name\":\"permitBatch\",\"type\":\"tuple\"},{\"internalType\":\"bytes\",\"name\":\"signature\",\"type\":\"bytes\"}],\"name\":\"permit\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"components\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint160\",\"name\":\"amount\",\"type\":\"uint160\"},{\"internalType\":\"uint48\",\"name\":\"expiration\",\"type\":\"uint48\"},{\"internalType\":\"uint48\",\"name\":\"nonce\",\"type\":\"uint48\"}],\"internalType\":\"structIAllowanceTransfer.PermitDetails\",\"name\":\"details\",\"type\":\"tuple\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"sigDeadline\",\"type\":\"uint256\"}],\"internalType\":\"structIAllowanceTransfer.PermitSingle\",\"name\":\"permitSingle\",\"type\":\"tuple\"},{\"internalType\":\"bytes\",\"name\":\"signature\",\"type\":\"bytes\"}],\"name\":\"permit\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"internalType\":\"structISignatureTransfer.TokenPermissions\",\"name\":\"permitted\",\"type\":\"tuple\"},{\"internalType\":\"uint256\",\"name\":\"nonce\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"internalType\":\"structISignatureTransfer.PermitTransferFrom\",\"name\":\"permit\",\"type\":\"tuple\"},{\"components\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"requestedAmount\",\"type\":\"uint256\"}],\"internalType\":\"structISignatureTransfer.SignatureTransferDetails\",\"name\":\"transferDetails\",\"type\":\"tuple\"},{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"signature\",\"type\":\"bytes\"}],\"name\":\"permitTransferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"internalType\":\"structISignatureTransfer.TokenPermissions[]\",\"name\":\"permitted\",\"type\":\"tuple[]\"},{\"internalType\":\"uint256\",\"name\":\"nonce\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"internalType\":\"structISignatureTransfer.PermitBatchTransferFrom\",\"name\":\"permit\",\"type\":\"tuple\"},{\"components\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"requestedAmount\",\"type\":\"uint256\"}],\"internalType\":\"structISignatureTransfer.SignatureTransferDetails[]\",\"name\":\"transferDetails\",\"type\":\"tuple[]\"},{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"signature\",\"type\":\"bytes\"}],\"name\":\"permitTransferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"internalType\":\"structISignatureTransfer.TokenPermissions\",\"name\":\"permitted\",\"type\":\"tuple\"},{\"internalType\":\"uint256\",\"name\":\"nonce\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"internalType\":\"structISignatureTransfer.PermitTransferFrom\",\"name\":\"permit\",\"type\":\"tuple\"},{\"components\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"requestedAmount\",\"type\":\"uint256\"}],\"internalType\":\"structISignatureTransfer.SignatureTransferDetails\",\"name\":\"transferDetails\",\"type\":\"tuple\"},{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"witness\",\"type\":\"bytes32\"},{\"internalType\":\"string\",\"name\":\"witnessTypeString\",\"type\":\"string\"},{\"internalType\":\"bytes\",\"name\":\"signature\",\"type\":\"bytes\"}],\"name\":\"permitWitnessTransferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"internalType\":\"structISignatureTransfer.TokenPermissions[]\",\"name\":\"permitted\",\"type\":\"tuple[]\"},{\"internalType\":\"uint256\",\"name\":\"nonce\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"internalType\":\"structISignatureTransfer.PermitBatchTransferFrom\",\"name\":\"permit\",\"type\":\"tuple\"},{\"components\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"requestedAmount\",\"type\":\"uint256\"}],\"internalType\":\"structISignatureTransfer.SignatureTransferDetails[]\",\"name\":\"transferDetails\",\"type\":\"tuple[]\"},{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"witness\",\"type\":\"bytes32\"},{\"internalType\":\"string\",\"name\":\"witnessTypeString\",\"type\":\"string\"},{\"internalType\":\"bytes\",\"name\":\"signature\",\"type\":\"bytes\"}],\"name\":\"permitWitnessTransferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint160\",\"name\":\"amount\",\"type\":\"uint160\"},{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"}],\"internalType\":\"structIAllowanceTransfer.AllowanceTransferDetails[]\",\"name\":\"transferDetails\",\"type\":\"tuple[]\"}],\"name\":\"transferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint160\",\"name\":\"amount\",\"type\":\"uint160\"},{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"}],\"name\":\"transferFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", +} + +// Permit2ABI is the input ABI used to generate the binding from. +// Deprecated: Use Permit2MetaData.ABI instead. +var Permit2ABI = Permit2MetaData.ABI + +// Permit2 is an auto generated Go binding around an Ethereum contract. +type Permit2 struct { + Permit2Caller // Read-only binding to the contract + Permit2Transactor // Write-only binding to the contract + Permit2Filterer // Log filterer for contract events +} + +// Permit2Caller is an auto generated read-only Go binding around an Ethereum contract. +type Permit2Caller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// Permit2Transactor is an auto generated write-only Go binding around an Ethereum contract. +type Permit2Transactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// Permit2Filterer is an auto generated log filtering Go binding around an Ethereum contract events. +type Permit2Filterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// Permit2Session is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type Permit2Session struct { + Contract *Permit2 // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// Permit2CallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type Permit2CallerSession struct { + Contract *Permit2Caller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// Permit2TransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type Permit2TransactorSession struct { + Contract *Permit2Transactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// Permit2Raw is an auto generated low-level Go binding around an Ethereum contract. +type Permit2Raw struct { + Contract *Permit2 // Generic contract binding to access the raw methods on +} + +// Permit2CallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type Permit2CallerRaw struct { + Contract *Permit2Caller // Generic read-only contract binding to access the raw methods on +} + +// Permit2TransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type Permit2TransactorRaw struct { + Contract *Permit2Transactor // Generic write-only contract binding to access the raw methods on +} + +// NewPermit2 creates a new instance of Permit2, bound to a specific deployed contract. +func NewPermit2(address common.Address, backend bind.ContractBackend) (*Permit2, error) { + contract, err := bindPermit2(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &Permit2{Permit2Caller: Permit2Caller{contract: contract}, Permit2Transactor: Permit2Transactor{contract: contract}, Permit2Filterer: Permit2Filterer{contract: contract}}, nil +} + +// NewPermit2Caller creates a new read-only instance of Permit2, bound to a specific deployed contract. +func NewPermit2Caller(address common.Address, caller bind.ContractCaller) (*Permit2Caller, error) { + contract, err := bindPermit2(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &Permit2Caller{contract: contract}, nil +} + +// NewPermit2Transactor creates a new write-only instance of Permit2, bound to a specific deployed contract. +func NewPermit2Transactor(address common.Address, transactor bind.ContractTransactor) (*Permit2Transactor, error) { + contract, err := bindPermit2(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &Permit2Transactor{contract: contract}, nil +} + +// NewPermit2Filterer creates a new log filterer instance of Permit2, bound to a specific deployed contract. +func NewPermit2Filterer(address common.Address, filterer bind.ContractFilterer) (*Permit2Filterer, error) { + contract, err := bindPermit2(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &Permit2Filterer{contract: contract}, nil +} + +// bindPermit2 binds a generic wrapper to an already deployed contract. +func bindPermit2(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := Permit2MetaData.GetAbi() + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Permit2 *Permit2Raw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Permit2.Contract.Permit2Caller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Permit2 *Permit2Raw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Permit2.Contract.Permit2Transactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Permit2 *Permit2Raw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Permit2.Contract.Permit2Transactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Permit2 *Permit2CallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Permit2.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Permit2 *Permit2TransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Permit2.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Permit2 *Permit2TransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Permit2.Contract.contract.Transact(opts, method, params...) +} + +// DOMAINSEPARATOR is a free data retrieval call binding the contract method 0x3644e515. +// +// Solidity: function DOMAIN_SEPARATOR() view returns(bytes32) +func (_Permit2 *Permit2Caller) DOMAINSEPARATOR(opts *bind.CallOpts) ([32]byte, error) { + var out []interface{} + err := _Permit2.contract.Call(opts, &out, "DOMAIN_SEPARATOR") + + if err != nil { + return *new([32]byte), err + } + + out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) + + return out0, err + +} + +// DOMAINSEPARATOR is a free data retrieval call binding the contract method 0x3644e515. +// +// Solidity: function DOMAIN_SEPARATOR() view returns(bytes32) +func (_Permit2 *Permit2Session) DOMAINSEPARATOR() ([32]byte, error) { + return _Permit2.Contract.DOMAINSEPARATOR(&_Permit2.CallOpts) +} + +// DOMAINSEPARATOR is a free data retrieval call binding the contract method 0x3644e515. +// +// Solidity: function DOMAIN_SEPARATOR() view returns(bytes32) +func (_Permit2 *Permit2CallerSession) DOMAINSEPARATOR() ([32]byte, error) { + return _Permit2.Contract.DOMAINSEPARATOR(&_Permit2.CallOpts) +} + +// Allowance is a free data retrieval call binding the contract method 0x927da105. +// +// Solidity: function allowance(address , address , address ) view returns(uint160 amount, uint48 expiration, uint48 nonce) +func (_Permit2 *Permit2Caller) Allowance(opts *bind.CallOpts, arg0 common.Address, arg1 common.Address, arg2 common.Address) (struct { + Amount *big.Int + Expiration *big.Int + Nonce *big.Int +}, error) { + var out []interface{} + err := _Permit2.contract.Call(opts, &out, "allowance", arg0, arg1, arg2) + + outstruct := new(struct { + Amount *big.Int + Expiration *big.Int + Nonce *big.Int + }) + if err != nil { + return *outstruct, err + } + + outstruct.Amount = *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + outstruct.Expiration = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int) + outstruct.Nonce = *abi.ConvertType(out[2], new(*big.Int)).(**big.Int) + + return *outstruct, err + +} + +// Allowance is a free data retrieval call binding the contract method 0x927da105. +// +// Solidity: function allowance(address , address , address ) view returns(uint160 amount, uint48 expiration, uint48 nonce) +func (_Permit2 *Permit2Session) Allowance(arg0 common.Address, arg1 common.Address, arg2 common.Address) (struct { + Amount *big.Int + Expiration *big.Int + Nonce *big.Int +}, error) { + return _Permit2.Contract.Allowance(&_Permit2.CallOpts, arg0, arg1, arg2) +} + +// Allowance is a free data retrieval call binding the contract method 0x927da105. +// +// Solidity: function allowance(address , address , address ) view returns(uint160 amount, uint48 expiration, uint48 nonce) +func (_Permit2 *Permit2CallerSession) Allowance(arg0 common.Address, arg1 common.Address, arg2 common.Address) (struct { + Amount *big.Int + Expiration *big.Int + Nonce *big.Int +}, error) { + return _Permit2.Contract.Allowance(&_Permit2.CallOpts, arg0, arg1, arg2) +} + +// NonceBitmap is a free data retrieval call binding the contract method 0x4fe02b44. +// +// Solidity: function nonceBitmap(address , uint256 ) view returns(uint256) +func (_Permit2 *Permit2Caller) NonceBitmap(opts *bind.CallOpts, arg0 common.Address, arg1 *big.Int) (*big.Int, error) { + var out []interface{} + err := _Permit2.contract.Call(opts, &out, "nonceBitmap", arg0, arg1) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// NonceBitmap is a free data retrieval call binding the contract method 0x4fe02b44. +// +// Solidity: function nonceBitmap(address , uint256 ) view returns(uint256) +func (_Permit2 *Permit2Session) NonceBitmap(arg0 common.Address, arg1 *big.Int) (*big.Int, error) { + return _Permit2.Contract.NonceBitmap(&_Permit2.CallOpts, arg0, arg1) +} + +// NonceBitmap is a free data retrieval call binding the contract method 0x4fe02b44. +// +// Solidity: function nonceBitmap(address , uint256 ) view returns(uint256) +func (_Permit2 *Permit2CallerSession) NonceBitmap(arg0 common.Address, arg1 *big.Int) (*big.Int, error) { + return _Permit2.Contract.NonceBitmap(&_Permit2.CallOpts, arg0, arg1) +} + +// Approve is a paid mutator transaction binding the contract method 0x87517c45. +// +// Solidity: function approve(address token, address spender, uint160 amount, uint48 expiration) returns() +func (_Permit2 *Permit2Transactor) Approve(opts *bind.TransactOpts, token common.Address, spender common.Address, amount *big.Int, expiration *big.Int) (*types.Transaction, error) { + return _Permit2.contract.Transact(opts, "approve", token, spender, amount, expiration) +} + +// Approve is a paid mutator transaction binding the contract method 0x87517c45. +// +// Solidity: function approve(address token, address spender, uint160 amount, uint48 expiration) returns() +func (_Permit2 *Permit2Session) Approve(token common.Address, spender common.Address, amount *big.Int, expiration *big.Int) (*types.Transaction, error) { + return _Permit2.Contract.Approve(&_Permit2.TransactOpts, token, spender, amount, expiration) +} + +// Approve is a paid mutator transaction binding the contract method 0x87517c45. +// +// Solidity: function approve(address token, address spender, uint160 amount, uint48 expiration) returns() +func (_Permit2 *Permit2TransactorSession) Approve(token common.Address, spender common.Address, amount *big.Int, expiration *big.Int) (*types.Transaction, error) { + return _Permit2.Contract.Approve(&_Permit2.TransactOpts, token, spender, amount, expiration) +} + +// InvalidateNonces is a paid mutator transaction binding the contract method 0x65d9723c. +// +// Solidity: function invalidateNonces(address token, address spender, uint48 newNonce) returns() +func (_Permit2 *Permit2Transactor) InvalidateNonces(opts *bind.TransactOpts, token common.Address, spender common.Address, newNonce *big.Int) (*types.Transaction, error) { + return _Permit2.contract.Transact(opts, "invalidateNonces", token, spender, newNonce) +} + +// InvalidateNonces is a paid mutator transaction binding the contract method 0x65d9723c. +// +// Solidity: function invalidateNonces(address token, address spender, uint48 newNonce) returns() +func (_Permit2 *Permit2Session) InvalidateNonces(token common.Address, spender common.Address, newNonce *big.Int) (*types.Transaction, error) { + return _Permit2.Contract.InvalidateNonces(&_Permit2.TransactOpts, token, spender, newNonce) +} + +// InvalidateNonces is a paid mutator transaction binding the contract method 0x65d9723c. +// +// Solidity: function invalidateNonces(address token, address spender, uint48 newNonce) returns() +func (_Permit2 *Permit2TransactorSession) InvalidateNonces(token common.Address, spender common.Address, newNonce *big.Int) (*types.Transaction, error) { + return _Permit2.Contract.InvalidateNonces(&_Permit2.TransactOpts, token, spender, newNonce) +} + +// InvalidateUnorderedNonces is a paid mutator transaction binding the contract method 0x3ff9dcb1. +// +// Solidity: function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) returns() +func (_Permit2 *Permit2Transactor) InvalidateUnorderedNonces(opts *bind.TransactOpts, wordPos *big.Int, mask *big.Int) (*types.Transaction, error) { + return _Permit2.contract.Transact(opts, "invalidateUnorderedNonces", wordPos, mask) +} + +// InvalidateUnorderedNonces is a paid mutator transaction binding the contract method 0x3ff9dcb1. +// +// Solidity: function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) returns() +func (_Permit2 *Permit2Session) InvalidateUnorderedNonces(wordPos *big.Int, mask *big.Int) (*types.Transaction, error) { + return _Permit2.Contract.InvalidateUnorderedNonces(&_Permit2.TransactOpts, wordPos, mask) +} + +// InvalidateUnorderedNonces is a paid mutator transaction binding the contract method 0x3ff9dcb1. +// +// Solidity: function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) returns() +func (_Permit2 *Permit2TransactorSession) InvalidateUnorderedNonces(wordPos *big.Int, mask *big.Int) (*types.Transaction, error) { + return _Permit2.Contract.InvalidateUnorderedNonces(&_Permit2.TransactOpts, wordPos, mask) +} + +// Lockdown is a paid mutator transaction binding the contract method 0xcc53287f. +// +// Solidity: function lockdown((address,address)[] approvals) returns() +func (_Permit2 *Permit2Transactor) Lockdown(opts *bind.TransactOpts, approvals []IAllowanceTransferTokenSpenderPair) (*types.Transaction, error) { + return _Permit2.contract.Transact(opts, "lockdown", approvals) +} + +// Lockdown is a paid mutator transaction binding the contract method 0xcc53287f. +// +// Solidity: function lockdown((address,address)[] approvals) returns() +func (_Permit2 *Permit2Session) Lockdown(approvals []IAllowanceTransferTokenSpenderPair) (*types.Transaction, error) { + return _Permit2.Contract.Lockdown(&_Permit2.TransactOpts, approvals) +} + +// Lockdown is a paid mutator transaction binding the contract method 0xcc53287f. +// +// Solidity: function lockdown((address,address)[] approvals) returns() +func (_Permit2 *Permit2TransactorSession) Lockdown(approvals []IAllowanceTransferTokenSpenderPair) (*types.Transaction, error) { + return _Permit2.Contract.Lockdown(&_Permit2.TransactOpts, approvals) +} + +// Permit is a paid mutator transaction binding the contract method 0x2a2d80d1. +// +// Solidity: function permit(address owner, ((address,uint160,uint48,uint48)[],address,uint256) permitBatch, bytes signature) returns() +func (_Permit2 *Permit2Transactor) Permit(opts *bind.TransactOpts, owner common.Address, permitBatch IAllowanceTransferPermitBatch, signature []byte) (*types.Transaction, error) { + return _Permit2.contract.Transact(opts, "permit", owner, permitBatch, signature) +} + +// Permit is a paid mutator transaction binding the contract method 0x2a2d80d1. +// +// Solidity: function permit(address owner, ((address,uint160,uint48,uint48)[],address,uint256) permitBatch, bytes signature) returns() +func (_Permit2 *Permit2Session) Permit(owner common.Address, permitBatch IAllowanceTransferPermitBatch, signature []byte) (*types.Transaction, error) { + return _Permit2.Contract.Permit(&_Permit2.TransactOpts, owner, permitBatch, signature) +} + +// Permit is a paid mutator transaction binding the contract method 0x2a2d80d1. +// +// Solidity: function permit(address owner, ((address,uint160,uint48,uint48)[],address,uint256) permitBatch, bytes signature) returns() +func (_Permit2 *Permit2TransactorSession) Permit(owner common.Address, permitBatch IAllowanceTransferPermitBatch, signature []byte) (*types.Transaction, error) { + return _Permit2.Contract.Permit(&_Permit2.TransactOpts, owner, permitBatch, signature) +} + +// Permit0 is a paid mutator transaction binding the contract method 0x2b67b570. +// +// Solidity: function permit(address owner, ((address,uint160,uint48,uint48),address,uint256) permitSingle, bytes signature) returns() +func (_Permit2 *Permit2Transactor) Permit0(opts *bind.TransactOpts, owner common.Address, permitSingle IAllowanceTransferPermitSingle, signature []byte) (*types.Transaction, error) { + return _Permit2.contract.Transact(opts, "permit0", owner, permitSingle, signature) +} + +// Permit0 is a paid mutator transaction binding the contract method 0x2b67b570. +// +// Solidity: function permit(address owner, ((address,uint160,uint48,uint48),address,uint256) permitSingle, bytes signature) returns() +func (_Permit2 *Permit2Session) Permit0(owner common.Address, permitSingle IAllowanceTransferPermitSingle, signature []byte) (*types.Transaction, error) { + return _Permit2.Contract.Permit0(&_Permit2.TransactOpts, owner, permitSingle, signature) +} + +// Permit0 is a paid mutator transaction binding the contract method 0x2b67b570. +// +// Solidity: function permit(address owner, ((address,uint160,uint48,uint48),address,uint256) permitSingle, bytes signature) returns() +func (_Permit2 *Permit2TransactorSession) Permit0(owner common.Address, permitSingle IAllowanceTransferPermitSingle, signature []byte) (*types.Transaction, error) { + return _Permit2.Contract.Permit0(&_Permit2.TransactOpts, owner, permitSingle, signature) +} + +// PermitTransferFrom is a paid mutator transaction binding the contract method 0x30f28b7a. +// +// Solidity: function permitTransferFrom(((address,uint256),uint256,uint256) permit, (address,uint256) transferDetails, address owner, bytes signature) returns() +func (_Permit2 *Permit2Transactor) PermitTransferFrom(opts *bind.TransactOpts, permit ISignatureTransferPermitTransferFrom, transferDetails ISignatureTransferSignatureTransferDetails, owner common.Address, signature []byte) (*types.Transaction, error) { + return _Permit2.contract.Transact(opts, "permitTransferFrom", permit, transferDetails, owner, signature) +} + +// PermitTransferFrom is a paid mutator transaction binding the contract method 0x30f28b7a. +// +// Solidity: function permitTransferFrom(((address,uint256),uint256,uint256) permit, (address,uint256) transferDetails, address owner, bytes signature) returns() +func (_Permit2 *Permit2Session) PermitTransferFrom(permit ISignatureTransferPermitTransferFrom, transferDetails ISignatureTransferSignatureTransferDetails, owner common.Address, signature []byte) (*types.Transaction, error) { + return _Permit2.Contract.PermitTransferFrom(&_Permit2.TransactOpts, permit, transferDetails, owner, signature) +} + +// PermitTransferFrom is a paid mutator transaction binding the contract method 0x30f28b7a. +// +// Solidity: function permitTransferFrom(((address,uint256),uint256,uint256) permit, (address,uint256) transferDetails, address owner, bytes signature) returns() +func (_Permit2 *Permit2TransactorSession) PermitTransferFrom(permit ISignatureTransferPermitTransferFrom, transferDetails ISignatureTransferSignatureTransferDetails, owner common.Address, signature []byte) (*types.Transaction, error) { + return _Permit2.Contract.PermitTransferFrom(&_Permit2.TransactOpts, permit, transferDetails, owner, signature) +} + +// PermitTransferFrom0 is a paid mutator transaction binding the contract method 0xedd9444b. +// +// Solidity: function permitTransferFrom(((address,uint256)[],uint256,uint256) permit, (address,uint256)[] transferDetails, address owner, bytes signature) returns() +func (_Permit2 *Permit2Transactor) PermitTransferFrom0(opts *bind.TransactOpts, permit ISignatureTransferPermitBatchTransferFrom, transferDetails []ISignatureTransferSignatureTransferDetails, owner common.Address, signature []byte) (*types.Transaction, error) { + return _Permit2.contract.Transact(opts, "permitTransferFrom0", permit, transferDetails, owner, signature) +} + +// PermitTransferFrom0 is a paid mutator transaction binding the contract method 0xedd9444b. +// +// Solidity: function permitTransferFrom(((address,uint256)[],uint256,uint256) permit, (address,uint256)[] transferDetails, address owner, bytes signature) returns() +func (_Permit2 *Permit2Session) PermitTransferFrom0(permit ISignatureTransferPermitBatchTransferFrom, transferDetails []ISignatureTransferSignatureTransferDetails, owner common.Address, signature []byte) (*types.Transaction, error) { + return _Permit2.Contract.PermitTransferFrom0(&_Permit2.TransactOpts, permit, transferDetails, owner, signature) +} + +// PermitTransferFrom0 is a paid mutator transaction binding the contract method 0xedd9444b. +// +// Solidity: function permitTransferFrom(((address,uint256)[],uint256,uint256) permit, (address,uint256)[] transferDetails, address owner, bytes signature) returns() +func (_Permit2 *Permit2TransactorSession) PermitTransferFrom0(permit ISignatureTransferPermitBatchTransferFrom, transferDetails []ISignatureTransferSignatureTransferDetails, owner common.Address, signature []byte) (*types.Transaction, error) { + return _Permit2.Contract.PermitTransferFrom0(&_Permit2.TransactOpts, permit, transferDetails, owner, signature) +} + +// PermitWitnessTransferFrom is a paid mutator transaction binding the contract method 0x137c29fe. +// +// Solidity: function permitWitnessTransferFrom(((address,uint256),uint256,uint256) permit, (address,uint256) transferDetails, address owner, bytes32 witness, string witnessTypeString, bytes signature) returns() +func (_Permit2 *Permit2Transactor) PermitWitnessTransferFrom(opts *bind.TransactOpts, permit ISignatureTransferPermitTransferFrom, transferDetails ISignatureTransferSignatureTransferDetails, owner common.Address, witness [32]byte, witnessTypeString string, signature []byte) (*types.Transaction, error) { + return _Permit2.contract.Transact(opts, "permitWitnessTransferFrom", permit, transferDetails, owner, witness, witnessTypeString, signature) +} + +// PermitWitnessTransferFrom is a paid mutator transaction binding the contract method 0x137c29fe. +// +// Solidity: function permitWitnessTransferFrom(((address,uint256),uint256,uint256) permit, (address,uint256) transferDetails, address owner, bytes32 witness, string witnessTypeString, bytes signature) returns() +func (_Permit2 *Permit2Session) PermitWitnessTransferFrom(permit ISignatureTransferPermitTransferFrom, transferDetails ISignatureTransferSignatureTransferDetails, owner common.Address, witness [32]byte, witnessTypeString string, signature []byte) (*types.Transaction, error) { + return _Permit2.Contract.PermitWitnessTransferFrom(&_Permit2.TransactOpts, permit, transferDetails, owner, witness, witnessTypeString, signature) +} + +// PermitWitnessTransferFrom is a paid mutator transaction binding the contract method 0x137c29fe. +// +// Solidity: function permitWitnessTransferFrom(((address,uint256),uint256,uint256) permit, (address,uint256) transferDetails, address owner, bytes32 witness, string witnessTypeString, bytes signature) returns() +func (_Permit2 *Permit2TransactorSession) PermitWitnessTransferFrom(permit ISignatureTransferPermitTransferFrom, transferDetails ISignatureTransferSignatureTransferDetails, owner common.Address, witness [32]byte, witnessTypeString string, signature []byte) (*types.Transaction, error) { + return _Permit2.Contract.PermitWitnessTransferFrom(&_Permit2.TransactOpts, permit, transferDetails, owner, witness, witnessTypeString, signature) +} + +// PermitWitnessTransferFrom0 is a paid mutator transaction binding the contract method 0xfe8ec1a7. +// +// Solidity: function permitWitnessTransferFrom(((address,uint256)[],uint256,uint256) permit, (address,uint256)[] transferDetails, address owner, bytes32 witness, string witnessTypeString, bytes signature) returns() +func (_Permit2 *Permit2Transactor) PermitWitnessTransferFrom0(opts *bind.TransactOpts, permit ISignatureTransferPermitBatchTransferFrom, transferDetails []ISignatureTransferSignatureTransferDetails, owner common.Address, witness [32]byte, witnessTypeString string, signature []byte) (*types.Transaction, error) { + return _Permit2.contract.Transact(opts, "permitWitnessTransferFrom0", permit, transferDetails, owner, witness, witnessTypeString, signature) +} + +// PermitWitnessTransferFrom0 is a paid mutator transaction binding the contract method 0xfe8ec1a7. +// +// Solidity: function permitWitnessTransferFrom(((address,uint256)[],uint256,uint256) permit, (address,uint256)[] transferDetails, address owner, bytes32 witness, string witnessTypeString, bytes signature) returns() +func (_Permit2 *Permit2Session) PermitWitnessTransferFrom0(permit ISignatureTransferPermitBatchTransferFrom, transferDetails []ISignatureTransferSignatureTransferDetails, owner common.Address, witness [32]byte, witnessTypeString string, signature []byte) (*types.Transaction, error) { + return _Permit2.Contract.PermitWitnessTransferFrom0(&_Permit2.TransactOpts, permit, transferDetails, owner, witness, witnessTypeString, signature) +} + +// PermitWitnessTransferFrom0 is a paid mutator transaction binding the contract method 0xfe8ec1a7. +// +// Solidity: function permitWitnessTransferFrom(((address,uint256)[],uint256,uint256) permit, (address,uint256)[] transferDetails, address owner, bytes32 witness, string witnessTypeString, bytes signature) returns() +func (_Permit2 *Permit2TransactorSession) PermitWitnessTransferFrom0(permit ISignatureTransferPermitBatchTransferFrom, transferDetails []ISignatureTransferSignatureTransferDetails, owner common.Address, witness [32]byte, witnessTypeString string, signature []byte) (*types.Transaction, error) { + return _Permit2.Contract.PermitWitnessTransferFrom0(&_Permit2.TransactOpts, permit, transferDetails, owner, witness, witnessTypeString, signature) +} + +// TransferFrom is a paid mutator transaction binding the contract method 0x0d58b1db. +// +// Solidity: function transferFrom((address,address,uint160,address)[] transferDetails) returns() +func (_Permit2 *Permit2Transactor) TransferFrom(opts *bind.TransactOpts, transferDetails []IAllowanceTransferAllowanceTransferDetails) (*types.Transaction, error) { + return _Permit2.contract.Transact(opts, "transferFrom", transferDetails) +} + +// TransferFrom is a paid mutator transaction binding the contract method 0x0d58b1db. +// +// Solidity: function transferFrom((address,address,uint160,address)[] transferDetails) returns() +func (_Permit2 *Permit2Session) TransferFrom(transferDetails []IAllowanceTransferAllowanceTransferDetails) (*types.Transaction, error) { + return _Permit2.Contract.TransferFrom(&_Permit2.TransactOpts, transferDetails) +} + +// TransferFrom is a paid mutator transaction binding the contract method 0x0d58b1db. +// +// Solidity: function transferFrom((address,address,uint160,address)[] transferDetails) returns() +func (_Permit2 *Permit2TransactorSession) TransferFrom(transferDetails []IAllowanceTransferAllowanceTransferDetails) (*types.Transaction, error) { + return _Permit2.Contract.TransferFrom(&_Permit2.TransactOpts, transferDetails) +} + +// TransferFrom0 is a paid mutator transaction binding the contract method 0x36c78516. +// +// Solidity: function transferFrom(address from, address to, uint160 amount, address token) returns() +func (_Permit2 *Permit2Transactor) TransferFrom0(opts *bind.TransactOpts, from common.Address, to common.Address, amount *big.Int, token common.Address) (*types.Transaction, error) { + return _Permit2.contract.Transact(opts, "transferFrom0", from, to, amount, token) +} + +// TransferFrom0 is a paid mutator transaction binding the contract method 0x36c78516. +// +// Solidity: function transferFrom(address from, address to, uint160 amount, address token) returns() +func (_Permit2 *Permit2Session) TransferFrom0(from common.Address, to common.Address, amount *big.Int, token common.Address) (*types.Transaction, error) { + return _Permit2.Contract.TransferFrom0(&_Permit2.TransactOpts, from, to, amount, token) +} + +// TransferFrom0 is a paid mutator transaction binding the contract method 0x36c78516. +// +// Solidity: function transferFrom(address from, address to, uint160 amount, address token) returns() +func (_Permit2 *Permit2TransactorSession) TransferFrom0(from common.Address, to common.Address, amount *big.Int, token common.Address) (*types.Transaction, error) { + return _Permit2.Contract.TransferFrom0(&_Permit2.TransactOpts, from, to, amount, token) +} + +// Permit2ApprovalIterator is returned from FilterApproval and is used to iterate over the raw logs and unpacked data for Approval events raised by the Permit2 contract. +type Permit2ApprovalIterator struct { + Event *Permit2Approval // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *Permit2ApprovalIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(Permit2Approval) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(Permit2Approval) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *Permit2ApprovalIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *Permit2ApprovalIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// Permit2Approval represents a Approval event raised by the Permit2 contract. +type Permit2Approval struct { + Owner common.Address + Token common.Address + Spender common.Address + Amount *big.Int + Expiration *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterApproval is a free log retrieval operation binding the contract event 0xda9fa7c1b00402c17d0161b249b1ab8bbec047c5a52207b9c112deffd817036b. +// +// Solidity: event Approval(address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration) +func (_Permit2 *Permit2Filterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, token []common.Address, spender []common.Address) (*Permit2ApprovalIterator, error) { + + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + var tokenRule []interface{} + for _, tokenItem := range token { + tokenRule = append(tokenRule, tokenItem) + } + var spenderRule []interface{} + for _, spenderItem := range spender { + spenderRule = append(spenderRule, spenderItem) + } + + logs, sub, err := _Permit2.contract.FilterLogs(opts, "Approval", ownerRule, tokenRule, spenderRule) + if err != nil { + return nil, err + } + return &Permit2ApprovalIterator{contract: _Permit2.contract, event: "Approval", logs: logs, sub: sub}, nil +} + +// WatchApproval is a free log subscription operation binding the contract event 0xda9fa7c1b00402c17d0161b249b1ab8bbec047c5a52207b9c112deffd817036b. +// +// Solidity: event Approval(address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration) +func (_Permit2 *Permit2Filterer) WatchApproval(opts *bind.WatchOpts, sink chan<- *Permit2Approval, owner []common.Address, token []common.Address, spender []common.Address) (event.Subscription, error) { + + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + var tokenRule []interface{} + for _, tokenItem := range token { + tokenRule = append(tokenRule, tokenItem) + } + var spenderRule []interface{} + for _, spenderItem := range spender { + spenderRule = append(spenderRule, spenderItem) + } + + logs, sub, err := _Permit2.contract.WatchLogs(opts, "Approval", ownerRule, tokenRule, spenderRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(Permit2Approval) + if err := _Permit2.contract.UnpackLog(event, "Approval", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseApproval is a log parse operation binding the contract event 0xda9fa7c1b00402c17d0161b249b1ab8bbec047c5a52207b9c112deffd817036b. +// +// Solidity: event Approval(address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration) +func (_Permit2 *Permit2Filterer) ParseApproval(log types.Log) (*Permit2Approval, error) { + event := new(Permit2Approval) + if err := _Permit2.contract.UnpackLog(event, "Approval", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// Permit2LockdownIterator is returned from FilterLockdown and is used to iterate over the raw logs and unpacked data for Lockdown events raised by the Permit2 contract. +type Permit2LockdownIterator struct { + Event *Permit2Lockdown // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *Permit2LockdownIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(Permit2Lockdown) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(Permit2Lockdown) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *Permit2LockdownIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *Permit2LockdownIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// Permit2Lockdown represents a Lockdown event raised by the Permit2 contract. +type Permit2Lockdown struct { + Owner common.Address + Token common.Address + Spender common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterLockdown is a free log retrieval operation binding the contract event 0x89b1add15eff56b3dfe299ad94e01f2b52fbcb80ae1a3baea6ae8c04cb2b98a4. +// +// Solidity: event Lockdown(address indexed owner, address token, address spender) +func (_Permit2 *Permit2Filterer) FilterLockdown(opts *bind.FilterOpts, owner []common.Address) (*Permit2LockdownIterator, error) { + + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + + logs, sub, err := _Permit2.contract.FilterLogs(opts, "Lockdown", ownerRule) + if err != nil { + return nil, err + } + return &Permit2LockdownIterator{contract: _Permit2.contract, event: "Lockdown", logs: logs, sub: sub}, nil +} + +// WatchLockdown is a free log subscription operation binding the contract event 0x89b1add15eff56b3dfe299ad94e01f2b52fbcb80ae1a3baea6ae8c04cb2b98a4. +// +// Solidity: event Lockdown(address indexed owner, address token, address spender) +func (_Permit2 *Permit2Filterer) WatchLockdown(opts *bind.WatchOpts, sink chan<- *Permit2Lockdown, owner []common.Address) (event.Subscription, error) { + + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + + logs, sub, err := _Permit2.contract.WatchLogs(opts, "Lockdown", ownerRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(Permit2Lockdown) + if err := _Permit2.contract.UnpackLog(event, "Lockdown", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseLockdown is a log parse operation binding the contract event 0x89b1add15eff56b3dfe299ad94e01f2b52fbcb80ae1a3baea6ae8c04cb2b98a4. +// +// Solidity: event Lockdown(address indexed owner, address token, address spender) +func (_Permit2 *Permit2Filterer) ParseLockdown(log types.Log) (*Permit2Lockdown, error) { + event := new(Permit2Lockdown) + if err := _Permit2.contract.UnpackLog(event, "Lockdown", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// Permit2NonceInvalidationIterator is returned from FilterNonceInvalidation and is used to iterate over the raw logs and unpacked data for NonceInvalidation events raised by the Permit2 contract. +type Permit2NonceInvalidationIterator struct { + Event *Permit2NonceInvalidation // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *Permit2NonceInvalidationIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(Permit2NonceInvalidation) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(Permit2NonceInvalidation) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *Permit2NonceInvalidationIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *Permit2NonceInvalidationIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// Permit2NonceInvalidation represents a NonceInvalidation event raised by the Permit2 contract. +type Permit2NonceInvalidation struct { + Owner common.Address + Token common.Address + Spender common.Address + NewNonce *big.Int + OldNonce *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterNonceInvalidation is a free log retrieval operation binding the contract event 0x55eb90d810e1700b35a8e7e25395ff7f2b2259abd7415ca2284dfb1c246418f3. +// +// Solidity: event NonceInvalidation(address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce) +func (_Permit2 *Permit2Filterer) FilterNonceInvalidation(opts *bind.FilterOpts, owner []common.Address, token []common.Address, spender []common.Address) (*Permit2NonceInvalidationIterator, error) { + + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + var tokenRule []interface{} + for _, tokenItem := range token { + tokenRule = append(tokenRule, tokenItem) + } + var spenderRule []interface{} + for _, spenderItem := range spender { + spenderRule = append(spenderRule, spenderItem) + } + + logs, sub, err := _Permit2.contract.FilterLogs(opts, "NonceInvalidation", ownerRule, tokenRule, spenderRule) + if err != nil { + return nil, err + } + return &Permit2NonceInvalidationIterator{contract: _Permit2.contract, event: "NonceInvalidation", logs: logs, sub: sub}, nil +} + +// WatchNonceInvalidation is a free log subscription operation binding the contract event 0x55eb90d810e1700b35a8e7e25395ff7f2b2259abd7415ca2284dfb1c246418f3. +// +// Solidity: event NonceInvalidation(address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce) +func (_Permit2 *Permit2Filterer) WatchNonceInvalidation(opts *bind.WatchOpts, sink chan<- *Permit2NonceInvalidation, owner []common.Address, token []common.Address, spender []common.Address) (event.Subscription, error) { + + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + var tokenRule []interface{} + for _, tokenItem := range token { + tokenRule = append(tokenRule, tokenItem) + } + var spenderRule []interface{} + for _, spenderItem := range spender { + spenderRule = append(spenderRule, spenderItem) + } + + logs, sub, err := _Permit2.contract.WatchLogs(opts, "NonceInvalidation", ownerRule, tokenRule, spenderRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(Permit2NonceInvalidation) + if err := _Permit2.contract.UnpackLog(event, "NonceInvalidation", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseNonceInvalidation is a log parse operation binding the contract event 0x55eb90d810e1700b35a8e7e25395ff7f2b2259abd7415ca2284dfb1c246418f3. +// +// Solidity: event NonceInvalidation(address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce) +func (_Permit2 *Permit2Filterer) ParseNonceInvalidation(log types.Log) (*Permit2NonceInvalidation, error) { + event := new(Permit2NonceInvalidation) + if err := _Permit2.contract.UnpackLog(event, "NonceInvalidation", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// Permit2PermitIterator is returned from FilterPermit and is used to iterate over the raw logs and unpacked data for Permit events raised by the Permit2 contract. +type Permit2PermitIterator struct { + Event *Permit2Permit // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *Permit2PermitIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(Permit2Permit) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(Permit2Permit) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *Permit2PermitIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *Permit2PermitIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// Permit2Permit represents a Permit event raised by the Permit2 contract. +type Permit2Permit struct { + Owner common.Address + Token common.Address + Spender common.Address + Amount *big.Int + Expiration *big.Int + Nonce *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterPermit is a free log retrieval operation binding the contract event 0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec. +// +// Solidity: event Permit(address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration, uint48 nonce) +func (_Permit2 *Permit2Filterer) FilterPermit(opts *bind.FilterOpts, owner []common.Address, token []common.Address, spender []common.Address) (*Permit2PermitIterator, error) { + + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + var tokenRule []interface{} + for _, tokenItem := range token { + tokenRule = append(tokenRule, tokenItem) + } + var spenderRule []interface{} + for _, spenderItem := range spender { + spenderRule = append(spenderRule, spenderItem) + } + + logs, sub, err := _Permit2.contract.FilterLogs(opts, "Permit", ownerRule, tokenRule, spenderRule) + if err != nil { + return nil, err + } + return &Permit2PermitIterator{contract: _Permit2.contract, event: "Permit", logs: logs, sub: sub}, nil +} + +// WatchPermit is a free log subscription operation binding the contract event 0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec. +// +// Solidity: event Permit(address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration, uint48 nonce) +func (_Permit2 *Permit2Filterer) WatchPermit(opts *bind.WatchOpts, sink chan<- *Permit2Permit, owner []common.Address, token []common.Address, spender []common.Address) (event.Subscription, error) { + + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + var tokenRule []interface{} + for _, tokenItem := range token { + tokenRule = append(tokenRule, tokenItem) + } + var spenderRule []interface{} + for _, spenderItem := range spender { + spenderRule = append(spenderRule, spenderItem) + } + + logs, sub, err := _Permit2.contract.WatchLogs(opts, "Permit", ownerRule, tokenRule, spenderRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(Permit2Permit) + if err := _Permit2.contract.UnpackLog(event, "Permit", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParsePermit is a log parse operation binding the contract event 0xc6a377bfc4eb120024a8ac08eef205be16b817020812c73223e81d1bdb9708ec. +// +// Solidity: event Permit(address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration, uint48 nonce) +func (_Permit2 *Permit2Filterer) ParsePermit(log types.Log) (*Permit2Permit, error) { + event := new(Permit2Permit) + if err := _Permit2.contract.UnpackLog(event, "Permit", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// Permit2UnorderedNonceInvalidationIterator is returned from FilterUnorderedNonceInvalidation and is used to iterate over the raw logs and unpacked data for UnorderedNonceInvalidation events raised by the Permit2 contract. +type Permit2UnorderedNonceInvalidationIterator struct { + Event *Permit2UnorderedNonceInvalidation // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *Permit2UnorderedNonceInvalidationIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(Permit2UnorderedNonceInvalidation) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(Permit2UnorderedNonceInvalidation) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *Permit2UnorderedNonceInvalidationIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *Permit2UnorderedNonceInvalidationIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// Permit2UnorderedNonceInvalidation represents a UnorderedNonceInvalidation event raised by the Permit2 contract. +type Permit2UnorderedNonceInvalidation struct { + Owner common.Address + Word *big.Int + Mask *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterUnorderedNonceInvalidation is a free log retrieval operation binding the contract event 0x3704902f963766a4e561bbaab6e6cdc1b1dd12f6e9e99648da8843b3f46b918d. +// +// Solidity: event UnorderedNonceInvalidation(address indexed owner, uint256 word, uint256 mask) +func (_Permit2 *Permit2Filterer) FilterUnorderedNonceInvalidation(opts *bind.FilterOpts, owner []common.Address) (*Permit2UnorderedNonceInvalidationIterator, error) { + + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + + logs, sub, err := _Permit2.contract.FilterLogs(opts, "UnorderedNonceInvalidation", ownerRule) + if err != nil { + return nil, err + } + return &Permit2UnorderedNonceInvalidationIterator{contract: _Permit2.contract, event: "UnorderedNonceInvalidation", logs: logs, sub: sub}, nil +} + +// WatchUnorderedNonceInvalidation is a free log subscription operation binding the contract event 0x3704902f963766a4e561bbaab6e6cdc1b1dd12f6e9e99648da8843b3f46b918d. +// +// Solidity: event UnorderedNonceInvalidation(address indexed owner, uint256 word, uint256 mask) +func (_Permit2 *Permit2Filterer) WatchUnorderedNonceInvalidation(opts *bind.WatchOpts, sink chan<- *Permit2UnorderedNonceInvalidation, owner []common.Address) (event.Subscription, error) { + + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + + logs, sub, err := _Permit2.contract.WatchLogs(opts, "UnorderedNonceInvalidation", ownerRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(Permit2UnorderedNonceInvalidation) + if err := _Permit2.contract.UnpackLog(event, "UnorderedNonceInvalidation", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseUnorderedNonceInvalidation is a log parse operation binding the contract event 0x3704902f963766a4e561bbaab6e6cdc1b1dd12f6e9e99648da8843b3f46b918d. +// +// Solidity: event UnorderedNonceInvalidation(address indexed owner, uint256 word, uint256 mask) +func (_Permit2 *Permit2Filterer) ParseUnorderedNonceInvalidation(log types.Log) (*Permit2UnorderedNonceInvalidation, error) { + event := new(Permit2UnorderedNonceInvalidation) + if err := _Permit2.contract.UnpackLog(event, "UnorderedNonceInvalidation", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} diff --git a/utils/provider/dex/uniswap/abi/v2Router02/v2Router02.go b/utils/provider/dex/uniswap/abi/v2Router02/v2Router02.go new file mode 100644 index 0000000..ed96fe9 --- /dev/null +++ b/utils/provider/dex/uniswap/abi/v2Router02/v2Router02.go @@ -0,0 +1,776 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package v2Router02 + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription + _ = abi.ConvertType +) + +// V2Router02MetaData contains all meta data concerning the V2Router02 contract. +var V2Router02MetaData = &bind.MetaData{ + ABI: "[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_factory\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_WETH\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"WETH\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"tokenA\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"tokenB\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amountADesired\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountBDesired\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountAMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountBMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"addLiquidity\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountB\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amountTokenDesired\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountTokenMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETHMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"addLiquidityETH\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountToken\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETH\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"factory\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"reserveIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"reserveOut\",\"type\":\"uint256\"}],\"name\":\"getAmountIn\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"reserveIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"reserveOut\",\"type\":\"uint256\"}],\"name\":\"getAmountOut\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"}],\"name\":\"getAmountsIn\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"}],\"name\":\"getAmountsOut\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"reserveA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"reserveB\",\"type\":\"uint256\"}],\"name\":\"quote\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountB\",\"type\":\"uint256\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"tokenA\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"tokenB\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountAMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountBMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"removeLiquidity\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountB\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountTokenMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETHMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"removeLiquidityETH\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountToken\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETH\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountTokenMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETHMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"removeLiquidityETHSupportingFeeOnTransferTokens\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountETH\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountTokenMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETHMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"approveMax\",\"type\":\"bool\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"removeLiquidityETHWithPermit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountToken\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETH\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountTokenMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountETHMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"approveMax\",\"type\":\"bool\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"removeLiquidityETHWithPermitSupportingFeeOnTransferTokens\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountETH\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"tokenA\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"tokenB\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountAMin\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountBMin\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"bool\",\"name\":\"approveMax\",\"type\":\"bool\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"removeLiquidityWithPermit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountA\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountB\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapETHForExactTokens\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapExactETHForTokens\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapExactETHForTokensSupportingFeeOnTransferTokens\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapExactTokensForETH\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapExactTokensForETHSupportingFeeOnTransferTokens\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapExactTokensForTokens\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapExactTokensForTokensSupportingFeeOnTransferTokens\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountInMax\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapTokensForExactETH\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountInMax\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"swapTokensForExactTokens\",\"outputs\":[{\"internalType\":\"uint256[]\",\"name\":\"amounts\",\"type\":\"uint256[]\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}]", +} + +// V2Router02ABI is the input ABI used to generate the binding from. +// Deprecated: Use V2Router02MetaData.ABI instead. +var V2Router02ABI = V2Router02MetaData.ABI + +// V2Router02 is an auto generated Go binding around an Ethereum contract. +type V2Router02 struct { + V2Router02Caller // Read-only binding to the contract + V2Router02Transactor // Write-only binding to the contract + V2Router02Filterer // Log filterer for contract events +} + +// V2Router02Caller is an auto generated read-only Go binding around an Ethereum contract. +type V2Router02Caller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// V2Router02Transactor is an auto generated write-only Go binding around an Ethereum contract. +type V2Router02Transactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// V2Router02Filterer is an auto generated log filtering Go binding around an Ethereum contract events. +type V2Router02Filterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// V2Router02Session is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type V2Router02Session struct { + Contract *V2Router02 // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// V2Router02CallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type V2Router02CallerSession struct { + Contract *V2Router02Caller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// V2Router02TransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type V2Router02TransactorSession struct { + Contract *V2Router02Transactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// V2Router02Raw is an auto generated low-level Go binding around an Ethereum contract. +type V2Router02Raw struct { + Contract *V2Router02 // Generic contract binding to access the raw methods on +} + +// V2Router02CallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type V2Router02CallerRaw struct { + Contract *V2Router02Caller // Generic read-only contract binding to access the raw methods on +} + +// V2Router02TransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type V2Router02TransactorRaw struct { + Contract *V2Router02Transactor // Generic write-only contract binding to access the raw methods on +} + +// NewV2Router02 creates a new instance of V2Router02, bound to a specific deployed contract. +func NewV2Router02(address common.Address, backend bind.ContractBackend) (*V2Router02, error) { + contract, err := bindV2Router02(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &V2Router02{V2Router02Caller: V2Router02Caller{contract: contract}, V2Router02Transactor: V2Router02Transactor{contract: contract}, V2Router02Filterer: V2Router02Filterer{contract: contract}}, nil +} + +// NewV2Router02Caller creates a new read-only instance of V2Router02, bound to a specific deployed contract. +func NewV2Router02Caller(address common.Address, caller bind.ContractCaller) (*V2Router02Caller, error) { + contract, err := bindV2Router02(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &V2Router02Caller{contract: contract}, nil +} + +// NewV2Router02Transactor creates a new write-only instance of V2Router02, bound to a specific deployed contract. +func NewV2Router02Transactor(address common.Address, transactor bind.ContractTransactor) (*V2Router02Transactor, error) { + contract, err := bindV2Router02(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &V2Router02Transactor{contract: contract}, nil +} + +// NewV2Router02Filterer creates a new log filterer instance of V2Router02, bound to a specific deployed contract. +func NewV2Router02Filterer(address common.Address, filterer bind.ContractFilterer) (*V2Router02Filterer, error) { + contract, err := bindV2Router02(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &V2Router02Filterer{contract: contract}, nil +} + +// bindV2Router02 binds a generic wrapper to an already deployed contract. +func bindV2Router02(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := V2Router02MetaData.GetAbi() + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_V2Router02 *V2Router02Raw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _V2Router02.Contract.V2Router02Caller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_V2Router02 *V2Router02Raw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _V2Router02.Contract.V2Router02Transactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_V2Router02 *V2Router02Raw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _V2Router02.Contract.V2Router02Transactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_V2Router02 *V2Router02CallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _V2Router02.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_V2Router02 *V2Router02TransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _V2Router02.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_V2Router02 *V2Router02TransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _V2Router02.Contract.contract.Transact(opts, method, params...) +} + +// WETH is a free data retrieval call binding the contract method 0xad5c4648. +// +// Solidity: function WETH() view returns(address) +func (_V2Router02 *V2Router02Caller) WETH(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _V2Router02.contract.Call(opts, &out, "WETH") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// WETH is a free data retrieval call binding the contract method 0xad5c4648. +// +// Solidity: function WETH() view returns(address) +func (_V2Router02 *V2Router02Session) WETH() (common.Address, error) { + return _V2Router02.Contract.WETH(&_V2Router02.CallOpts) +} + +// WETH is a free data retrieval call binding the contract method 0xad5c4648. +// +// Solidity: function WETH() view returns(address) +func (_V2Router02 *V2Router02CallerSession) WETH() (common.Address, error) { + return _V2Router02.Contract.WETH(&_V2Router02.CallOpts) +} + +// Factory is a free data retrieval call binding the contract method 0xc45a0155. +// +// Solidity: function factory() view returns(address) +func (_V2Router02 *V2Router02Caller) Factory(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _V2Router02.contract.Call(opts, &out, "factory") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// Factory is a free data retrieval call binding the contract method 0xc45a0155. +// +// Solidity: function factory() view returns(address) +func (_V2Router02 *V2Router02Session) Factory() (common.Address, error) { + return _V2Router02.Contract.Factory(&_V2Router02.CallOpts) +} + +// Factory is a free data retrieval call binding the contract method 0xc45a0155. +// +// Solidity: function factory() view returns(address) +func (_V2Router02 *V2Router02CallerSession) Factory() (common.Address, error) { + return _V2Router02.Contract.Factory(&_V2Router02.CallOpts) +} + +// GetAmountIn is a free data retrieval call binding the contract method 0x85f8c259. +// +// Solidity: function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) pure returns(uint256 amountIn) +func (_V2Router02 *V2Router02Caller) GetAmountIn(opts *bind.CallOpts, amountOut *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) { + var out []interface{} + err := _V2Router02.contract.Call(opts, &out, "getAmountIn", amountOut, reserveIn, reserveOut) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// GetAmountIn is a free data retrieval call binding the contract method 0x85f8c259. +// +// Solidity: function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) pure returns(uint256 amountIn) +func (_V2Router02 *V2Router02Session) GetAmountIn(amountOut *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) { + return _V2Router02.Contract.GetAmountIn(&_V2Router02.CallOpts, amountOut, reserveIn, reserveOut) +} + +// GetAmountIn is a free data retrieval call binding the contract method 0x85f8c259. +// +// Solidity: function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) pure returns(uint256 amountIn) +func (_V2Router02 *V2Router02CallerSession) GetAmountIn(amountOut *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) { + return _V2Router02.Contract.GetAmountIn(&_V2Router02.CallOpts, amountOut, reserveIn, reserveOut) +} + +// GetAmountOut is a free data retrieval call binding the contract method 0x054d50d4. +// +// Solidity: function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) pure returns(uint256 amountOut) +func (_V2Router02 *V2Router02Caller) GetAmountOut(opts *bind.CallOpts, amountIn *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) { + var out []interface{} + err := _V2Router02.contract.Call(opts, &out, "getAmountOut", amountIn, reserveIn, reserveOut) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// GetAmountOut is a free data retrieval call binding the contract method 0x054d50d4. +// +// Solidity: function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) pure returns(uint256 amountOut) +func (_V2Router02 *V2Router02Session) GetAmountOut(amountIn *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) { + return _V2Router02.Contract.GetAmountOut(&_V2Router02.CallOpts, amountIn, reserveIn, reserveOut) +} + +// GetAmountOut is a free data retrieval call binding the contract method 0x054d50d4. +// +// Solidity: function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) pure returns(uint256 amountOut) +func (_V2Router02 *V2Router02CallerSession) GetAmountOut(amountIn *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) { + return _V2Router02.Contract.GetAmountOut(&_V2Router02.CallOpts, amountIn, reserveIn, reserveOut) +} + +// GetAmountsIn is a free data retrieval call binding the contract method 0x1f00ca74. +// +// Solidity: function getAmountsIn(uint256 amountOut, address[] path) view returns(uint256[] amounts) +func (_V2Router02 *V2Router02Caller) GetAmountsIn(opts *bind.CallOpts, amountOut *big.Int, path []common.Address) ([]*big.Int, error) { + var out []interface{} + err := _V2Router02.contract.Call(opts, &out, "getAmountsIn", amountOut, path) + + if err != nil { + return *new([]*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new([]*big.Int)).(*[]*big.Int) + + return out0, err + +} + +// GetAmountsIn is a free data retrieval call binding the contract method 0x1f00ca74. +// +// Solidity: function getAmountsIn(uint256 amountOut, address[] path) view returns(uint256[] amounts) +func (_V2Router02 *V2Router02Session) GetAmountsIn(amountOut *big.Int, path []common.Address) ([]*big.Int, error) { + return _V2Router02.Contract.GetAmountsIn(&_V2Router02.CallOpts, amountOut, path) +} + +// GetAmountsIn is a free data retrieval call binding the contract method 0x1f00ca74. +// +// Solidity: function getAmountsIn(uint256 amountOut, address[] path) view returns(uint256[] amounts) +func (_V2Router02 *V2Router02CallerSession) GetAmountsIn(amountOut *big.Int, path []common.Address) ([]*big.Int, error) { + return _V2Router02.Contract.GetAmountsIn(&_V2Router02.CallOpts, amountOut, path) +} + +// GetAmountsOut is a free data retrieval call binding the contract method 0xd06ca61f. +// +// Solidity: function getAmountsOut(uint256 amountIn, address[] path) view returns(uint256[] amounts) +func (_V2Router02 *V2Router02Caller) GetAmountsOut(opts *bind.CallOpts, amountIn *big.Int, path []common.Address) ([]*big.Int, error) { + var out []interface{} + err := _V2Router02.contract.Call(opts, &out, "getAmountsOut", amountIn, path) + + if err != nil { + return *new([]*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new([]*big.Int)).(*[]*big.Int) + + return out0, err + +} + +// GetAmountsOut is a free data retrieval call binding the contract method 0xd06ca61f. +// +// Solidity: function getAmountsOut(uint256 amountIn, address[] path) view returns(uint256[] amounts) +func (_V2Router02 *V2Router02Session) GetAmountsOut(amountIn *big.Int, path []common.Address) ([]*big.Int, error) { + return _V2Router02.Contract.GetAmountsOut(&_V2Router02.CallOpts, amountIn, path) +} + +// GetAmountsOut is a free data retrieval call binding the contract method 0xd06ca61f. +// +// Solidity: function getAmountsOut(uint256 amountIn, address[] path) view returns(uint256[] amounts) +func (_V2Router02 *V2Router02CallerSession) GetAmountsOut(amountIn *big.Int, path []common.Address) ([]*big.Int, error) { + return _V2Router02.Contract.GetAmountsOut(&_V2Router02.CallOpts, amountIn, path) +} + +// Quote is a free data retrieval call binding the contract method 0xad615dec. +// +// Solidity: function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) pure returns(uint256 amountB) +func (_V2Router02 *V2Router02Caller) Quote(opts *bind.CallOpts, amountA *big.Int, reserveA *big.Int, reserveB *big.Int) (*big.Int, error) { + var out []interface{} + err := _V2Router02.contract.Call(opts, &out, "quote", amountA, reserveA, reserveB) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// Quote is a free data retrieval call binding the contract method 0xad615dec. +// +// Solidity: function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) pure returns(uint256 amountB) +func (_V2Router02 *V2Router02Session) Quote(amountA *big.Int, reserveA *big.Int, reserveB *big.Int) (*big.Int, error) { + return _V2Router02.Contract.Quote(&_V2Router02.CallOpts, amountA, reserveA, reserveB) +} + +// Quote is a free data retrieval call binding the contract method 0xad615dec. +// +// Solidity: function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) pure returns(uint256 amountB) +func (_V2Router02 *V2Router02CallerSession) Quote(amountA *big.Int, reserveA *big.Int, reserveB *big.Int) (*big.Int, error) { + return _V2Router02.Contract.Quote(&_V2Router02.CallOpts, amountA, reserveA, reserveB) +} + +// AddLiquidity is a paid mutator transaction binding the contract method 0xe8e33700. +// +// Solidity: function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns(uint256 amountA, uint256 amountB, uint256 liquidity) +func (_V2Router02 *V2Router02Transactor) AddLiquidity(opts *bind.TransactOpts, tokenA common.Address, tokenB common.Address, amountADesired *big.Int, amountBDesired *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.contract.Transact(opts, "addLiquidity", tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline) +} + +// AddLiquidity is a paid mutator transaction binding the contract method 0xe8e33700. +// +// Solidity: function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns(uint256 amountA, uint256 amountB, uint256 liquidity) +func (_V2Router02 *V2Router02Session) AddLiquidity(tokenA common.Address, tokenB common.Address, amountADesired *big.Int, amountBDesired *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.AddLiquidity(&_V2Router02.TransactOpts, tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline) +} + +// AddLiquidity is a paid mutator transaction binding the contract method 0xe8e33700. +// +// Solidity: function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns(uint256 amountA, uint256 amountB, uint256 liquidity) +func (_V2Router02 *V2Router02TransactorSession) AddLiquidity(tokenA common.Address, tokenB common.Address, amountADesired *big.Int, amountBDesired *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.AddLiquidity(&_V2Router02.TransactOpts, tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline) +} + +// AddLiquidityETH is a paid mutator transaction binding the contract method 0xf305d719. +// +// Solidity: function addLiquidityETH(address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) payable returns(uint256 amountToken, uint256 amountETH, uint256 liquidity) +func (_V2Router02 *V2Router02Transactor) AddLiquidityETH(opts *bind.TransactOpts, token common.Address, amountTokenDesired *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.contract.Transact(opts, "addLiquidityETH", token, amountTokenDesired, amountTokenMin, amountETHMin, to, deadline) +} + +// AddLiquidityETH is a paid mutator transaction binding the contract method 0xf305d719. +// +// Solidity: function addLiquidityETH(address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) payable returns(uint256 amountToken, uint256 amountETH, uint256 liquidity) +func (_V2Router02 *V2Router02Session) AddLiquidityETH(token common.Address, amountTokenDesired *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.AddLiquidityETH(&_V2Router02.TransactOpts, token, amountTokenDesired, amountTokenMin, amountETHMin, to, deadline) +} + +// AddLiquidityETH is a paid mutator transaction binding the contract method 0xf305d719. +// +// Solidity: function addLiquidityETH(address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) payable returns(uint256 amountToken, uint256 amountETH, uint256 liquidity) +func (_V2Router02 *V2Router02TransactorSession) AddLiquidityETH(token common.Address, amountTokenDesired *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.AddLiquidityETH(&_V2Router02.TransactOpts, token, amountTokenDesired, amountTokenMin, amountETHMin, to, deadline) +} + +// RemoveLiquidity is a paid mutator transaction binding the contract method 0xbaa2abde. +// +// Solidity: function removeLiquidity(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns(uint256 amountA, uint256 amountB) +func (_V2Router02 *V2Router02Transactor) RemoveLiquidity(opts *bind.TransactOpts, tokenA common.Address, tokenB common.Address, liquidity *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.contract.Transact(opts, "removeLiquidity", tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline) +} + +// RemoveLiquidity is a paid mutator transaction binding the contract method 0xbaa2abde. +// +// Solidity: function removeLiquidity(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns(uint256 amountA, uint256 amountB) +func (_V2Router02 *V2Router02Session) RemoveLiquidity(tokenA common.Address, tokenB common.Address, liquidity *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.RemoveLiquidity(&_V2Router02.TransactOpts, tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline) +} + +// RemoveLiquidity is a paid mutator transaction binding the contract method 0xbaa2abde. +// +// Solidity: function removeLiquidity(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) returns(uint256 amountA, uint256 amountB) +func (_V2Router02 *V2Router02TransactorSession) RemoveLiquidity(tokenA common.Address, tokenB common.Address, liquidity *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.RemoveLiquidity(&_V2Router02.TransactOpts, tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline) +} + +// RemoveLiquidityETH is a paid mutator transaction binding the contract method 0x02751cec. +// +// Solidity: function removeLiquidityETH(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) returns(uint256 amountToken, uint256 amountETH) +func (_V2Router02 *V2Router02Transactor) RemoveLiquidityETH(opts *bind.TransactOpts, token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.contract.Transact(opts, "removeLiquidityETH", token, liquidity, amountTokenMin, amountETHMin, to, deadline) +} + +// RemoveLiquidityETH is a paid mutator transaction binding the contract method 0x02751cec. +// +// Solidity: function removeLiquidityETH(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) returns(uint256 amountToken, uint256 amountETH) +func (_V2Router02 *V2Router02Session) RemoveLiquidityETH(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.RemoveLiquidityETH(&_V2Router02.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline) +} + +// RemoveLiquidityETH is a paid mutator transaction binding the contract method 0x02751cec. +// +// Solidity: function removeLiquidityETH(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) returns(uint256 amountToken, uint256 amountETH) +func (_V2Router02 *V2Router02TransactorSession) RemoveLiquidityETH(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.RemoveLiquidityETH(&_V2Router02.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline) +} + +// RemoveLiquidityETHSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0xaf2979eb. +// +// Solidity: function removeLiquidityETHSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) returns(uint256 amountETH) +func (_V2Router02 *V2Router02Transactor) RemoveLiquidityETHSupportingFeeOnTransferTokens(opts *bind.TransactOpts, token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.contract.Transact(opts, "removeLiquidityETHSupportingFeeOnTransferTokens", token, liquidity, amountTokenMin, amountETHMin, to, deadline) +} + +// RemoveLiquidityETHSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0xaf2979eb. +// +// Solidity: function removeLiquidityETHSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) returns(uint256 amountETH) +func (_V2Router02 *V2Router02Session) RemoveLiquidityETHSupportingFeeOnTransferTokens(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.RemoveLiquidityETHSupportingFeeOnTransferTokens(&_V2Router02.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline) +} + +// RemoveLiquidityETHSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0xaf2979eb. +// +// Solidity: function removeLiquidityETHSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) returns(uint256 amountETH) +func (_V2Router02 *V2Router02TransactorSession) RemoveLiquidityETHSupportingFeeOnTransferTokens(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.RemoveLiquidityETHSupportingFeeOnTransferTokens(&_V2Router02.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline) +} + +// RemoveLiquidityETHWithPermit is a paid mutator transaction binding the contract method 0xded9382a. +// +// Solidity: function removeLiquidityETHWithPermit(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountToken, uint256 amountETH) +func (_V2Router02 *V2Router02Transactor) RemoveLiquidityETHWithPermit(opts *bind.TransactOpts, token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V2Router02.contract.Transact(opts, "removeLiquidityETHWithPermit", token, liquidity, amountTokenMin, amountETHMin, to, deadline, approveMax, v, r, s) +} + +// RemoveLiquidityETHWithPermit is a paid mutator transaction binding the contract method 0xded9382a. +// +// Solidity: function removeLiquidityETHWithPermit(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountToken, uint256 amountETH) +func (_V2Router02 *V2Router02Session) RemoveLiquidityETHWithPermit(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V2Router02.Contract.RemoveLiquidityETHWithPermit(&_V2Router02.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline, approveMax, v, r, s) +} + +// RemoveLiquidityETHWithPermit is a paid mutator transaction binding the contract method 0xded9382a. +// +// Solidity: function removeLiquidityETHWithPermit(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountToken, uint256 amountETH) +func (_V2Router02 *V2Router02TransactorSession) RemoveLiquidityETHWithPermit(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V2Router02.Contract.RemoveLiquidityETHWithPermit(&_V2Router02.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline, approveMax, v, r, s) +} + +// RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x5b0d5984. +// +// Solidity: function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountETH) +func (_V2Router02 *V2Router02Transactor) RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens(opts *bind.TransactOpts, token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V2Router02.contract.Transact(opts, "removeLiquidityETHWithPermitSupportingFeeOnTransferTokens", token, liquidity, amountTokenMin, amountETHMin, to, deadline, approveMax, v, r, s) +} + +// RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x5b0d5984. +// +// Solidity: function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountETH) +func (_V2Router02 *V2Router02Session) RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V2Router02.Contract.RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens(&_V2Router02.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline, approveMax, v, r, s) +} + +// RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x5b0d5984. +// +// Solidity: function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountETH) +func (_V2Router02 *V2Router02TransactorSession) RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens(token common.Address, liquidity *big.Int, amountTokenMin *big.Int, amountETHMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V2Router02.Contract.RemoveLiquidityETHWithPermitSupportingFeeOnTransferTokens(&_V2Router02.TransactOpts, token, liquidity, amountTokenMin, amountETHMin, to, deadline, approveMax, v, r, s) +} + +// RemoveLiquidityWithPermit is a paid mutator transaction binding the contract method 0x2195995c. +// +// Solidity: function removeLiquidityWithPermit(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountA, uint256 amountB) +func (_V2Router02 *V2Router02Transactor) RemoveLiquidityWithPermit(opts *bind.TransactOpts, tokenA common.Address, tokenB common.Address, liquidity *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V2Router02.contract.Transact(opts, "removeLiquidityWithPermit", tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline, approveMax, v, r, s) +} + +// RemoveLiquidityWithPermit is a paid mutator transaction binding the contract method 0x2195995c. +// +// Solidity: function removeLiquidityWithPermit(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountA, uint256 amountB) +func (_V2Router02 *V2Router02Session) RemoveLiquidityWithPermit(tokenA common.Address, tokenB common.Address, liquidity *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V2Router02.Contract.RemoveLiquidityWithPermit(&_V2Router02.TransactOpts, tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline, approveMax, v, r, s) +} + +// RemoveLiquidityWithPermit is a paid mutator transaction binding the contract method 0x2195995c. +// +// Solidity: function removeLiquidityWithPermit(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) returns(uint256 amountA, uint256 amountB) +func (_V2Router02 *V2Router02TransactorSession) RemoveLiquidityWithPermit(tokenA common.Address, tokenB common.Address, liquidity *big.Int, amountAMin *big.Int, amountBMin *big.Int, to common.Address, deadline *big.Int, approveMax bool, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V2Router02.Contract.RemoveLiquidityWithPermit(&_V2Router02.TransactOpts, tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline, approveMax, v, r, s) +} + +// SwapETHForExactTokens is a paid mutator transaction binding the contract method 0xfb3bdb41. +// +// Solidity: function swapETHForExactTokens(uint256 amountOut, address[] path, address to, uint256 deadline) payable returns(uint256[] amounts) +func (_V2Router02 *V2Router02Transactor) SwapETHForExactTokens(opts *bind.TransactOpts, amountOut *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.contract.Transact(opts, "swapETHForExactTokens", amountOut, path, to, deadline) +} + +// SwapETHForExactTokens is a paid mutator transaction binding the contract method 0xfb3bdb41. +// +// Solidity: function swapETHForExactTokens(uint256 amountOut, address[] path, address to, uint256 deadline) payable returns(uint256[] amounts) +func (_V2Router02 *V2Router02Session) SwapETHForExactTokens(amountOut *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.SwapETHForExactTokens(&_V2Router02.TransactOpts, amountOut, path, to, deadline) +} + +// SwapETHForExactTokens is a paid mutator transaction binding the contract method 0xfb3bdb41. +// +// Solidity: function swapETHForExactTokens(uint256 amountOut, address[] path, address to, uint256 deadline) payable returns(uint256[] amounts) +func (_V2Router02 *V2Router02TransactorSession) SwapETHForExactTokens(amountOut *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.SwapETHForExactTokens(&_V2Router02.TransactOpts, amountOut, path, to, deadline) +} + +// SwapExactETHForTokens is a paid mutator transaction binding the contract method 0x7ff36ab5. +// +// Solidity: function swapExactETHForTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable returns(uint256[] amounts) +func (_V2Router02 *V2Router02Transactor) SwapExactETHForTokens(opts *bind.TransactOpts, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.contract.Transact(opts, "swapExactETHForTokens", amountOutMin, path, to, deadline) +} + +// SwapExactETHForTokens is a paid mutator transaction binding the contract method 0x7ff36ab5. +// +// Solidity: function swapExactETHForTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable returns(uint256[] amounts) +func (_V2Router02 *V2Router02Session) SwapExactETHForTokens(amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.SwapExactETHForTokens(&_V2Router02.TransactOpts, amountOutMin, path, to, deadline) +} + +// SwapExactETHForTokens is a paid mutator transaction binding the contract method 0x7ff36ab5. +// +// Solidity: function swapExactETHForTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable returns(uint256[] amounts) +func (_V2Router02 *V2Router02TransactorSession) SwapExactETHForTokens(amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.SwapExactETHForTokens(&_V2Router02.TransactOpts, amountOutMin, path, to, deadline) +} + +// SwapExactETHForTokensSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0xb6f9de95. +// +// Solidity: function swapExactETHForTokensSupportingFeeOnTransferTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable returns() +func (_V2Router02 *V2Router02Transactor) SwapExactETHForTokensSupportingFeeOnTransferTokens(opts *bind.TransactOpts, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.contract.Transact(opts, "swapExactETHForTokensSupportingFeeOnTransferTokens", amountOutMin, path, to, deadline) +} + +// SwapExactETHForTokensSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0xb6f9de95. +// +// Solidity: function swapExactETHForTokensSupportingFeeOnTransferTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable returns() +func (_V2Router02 *V2Router02Session) SwapExactETHForTokensSupportingFeeOnTransferTokens(amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.SwapExactETHForTokensSupportingFeeOnTransferTokens(&_V2Router02.TransactOpts, amountOutMin, path, to, deadline) +} + +// SwapExactETHForTokensSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0xb6f9de95. +// +// Solidity: function swapExactETHForTokensSupportingFeeOnTransferTokens(uint256 amountOutMin, address[] path, address to, uint256 deadline) payable returns() +func (_V2Router02 *V2Router02TransactorSession) SwapExactETHForTokensSupportingFeeOnTransferTokens(amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.SwapExactETHForTokensSupportingFeeOnTransferTokens(&_V2Router02.TransactOpts, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForETH is a paid mutator transaction binding the contract method 0x18cbafe5. +// +// Solidity: function swapExactTokensForETH(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_V2Router02 *V2Router02Transactor) SwapExactTokensForETH(opts *bind.TransactOpts, amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.contract.Transact(opts, "swapExactTokensForETH", amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForETH is a paid mutator transaction binding the contract method 0x18cbafe5. +// +// Solidity: function swapExactTokensForETH(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_V2Router02 *V2Router02Session) SwapExactTokensForETH(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.SwapExactTokensForETH(&_V2Router02.TransactOpts, amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForETH is a paid mutator transaction binding the contract method 0x18cbafe5. +// +// Solidity: function swapExactTokensForETH(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_V2Router02 *V2Router02TransactorSession) SwapExactTokensForETH(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.SwapExactTokensForETH(&_V2Router02.TransactOpts, amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForETHSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x791ac947. +// +// Solidity: function swapExactTokensForETHSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns() +func (_V2Router02 *V2Router02Transactor) SwapExactTokensForETHSupportingFeeOnTransferTokens(opts *bind.TransactOpts, amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.contract.Transact(opts, "swapExactTokensForETHSupportingFeeOnTransferTokens", amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForETHSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x791ac947. +// +// Solidity: function swapExactTokensForETHSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns() +func (_V2Router02 *V2Router02Session) SwapExactTokensForETHSupportingFeeOnTransferTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.SwapExactTokensForETHSupportingFeeOnTransferTokens(&_V2Router02.TransactOpts, amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForETHSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x791ac947. +// +// Solidity: function swapExactTokensForETHSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns() +func (_V2Router02 *V2Router02TransactorSession) SwapExactTokensForETHSupportingFeeOnTransferTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.SwapExactTokensForETHSupportingFeeOnTransferTokens(&_V2Router02.TransactOpts, amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForTokens is a paid mutator transaction binding the contract method 0x38ed1739. +// +// Solidity: function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_V2Router02 *V2Router02Transactor) SwapExactTokensForTokens(opts *bind.TransactOpts, amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.contract.Transact(opts, "swapExactTokensForTokens", amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForTokens is a paid mutator transaction binding the contract method 0x38ed1739. +// +// Solidity: function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_V2Router02 *V2Router02Session) SwapExactTokensForTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.SwapExactTokensForTokens(&_V2Router02.TransactOpts, amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForTokens is a paid mutator transaction binding the contract method 0x38ed1739. +// +// Solidity: function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_V2Router02 *V2Router02TransactorSession) SwapExactTokensForTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.SwapExactTokensForTokens(&_V2Router02.TransactOpts, amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForTokensSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x5c11d795. +// +// Solidity: function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns() +func (_V2Router02 *V2Router02Transactor) SwapExactTokensForTokensSupportingFeeOnTransferTokens(opts *bind.TransactOpts, amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.contract.Transact(opts, "swapExactTokensForTokensSupportingFeeOnTransferTokens", amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForTokensSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x5c11d795. +// +// Solidity: function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns() +func (_V2Router02 *V2Router02Session) SwapExactTokensForTokensSupportingFeeOnTransferTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.SwapExactTokensForTokensSupportingFeeOnTransferTokens(&_V2Router02.TransactOpts, amountIn, amountOutMin, path, to, deadline) +} + +// SwapExactTokensForTokensSupportingFeeOnTransferTokens is a paid mutator transaction binding the contract method 0x5c11d795. +// +// Solidity: function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline) returns() +func (_V2Router02 *V2Router02TransactorSession) SwapExactTokensForTokensSupportingFeeOnTransferTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.SwapExactTokensForTokensSupportingFeeOnTransferTokens(&_V2Router02.TransactOpts, amountIn, amountOutMin, path, to, deadline) +} + +// SwapTokensForExactETH is a paid mutator transaction binding the contract method 0x4a25d94a. +// +// Solidity: function swapTokensForExactETH(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_V2Router02 *V2Router02Transactor) SwapTokensForExactETH(opts *bind.TransactOpts, amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.contract.Transact(opts, "swapTokensForExactETH", amountOut, amountInMax, path, to, deadline) +} + +// SwapTokensForExactETH is a paid mutator transaction binding the contract method 0x4a25d94a. +// +// Solidity: function swapTokensForExactETH(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_V2Router02 *V2Router02Session) SwapTokensForExactETH(amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.SwapTokensForExactETH(&_V2Router02.TransactOpts, amountOut, amountInMax, path, to, deadline) +} + +// SwapTokensForExactETH is a paid mutator transaction binding the contract method 0x4a25d94a. +// +// Solidity: function swapTokensForExactETH(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_V2Router02 *V2Router02TransactorSession) SwapTokensForExactETH(amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.SwapTokensForExactETH(&_V2Router02.TransactOpts, amountOut, amountInMax, path, to, deadline) +} + +// SwapTokensForExactTokens is a paid mutator transaction binding the contract method 0x8803dbee. +// +// Solidity: function swapTokensForExactTokens(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_V2Router02 *V2Router02Transactor) SwapTokensForExactTokens(opts *bind.TransactOpts, amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.contract.Transact(opts, "swapTokensForExactTokens", amountOut, amountInMax, path, to, deadline) +} + +// SwapTokensForExactTokens is a paid mutator transaction binding the contract method 0x8803dbee. +// +// Solidity: function swapTokensForExactTokens(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_V2Router02 *V2Router02Session) SwapTokensForExactTokens(amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.SwapTokensForExactTokens(&_V2Router02.TransactOpts, amountOut, amountInMax, path, to, deadline) +} + +// SwapTokensForExactTokens is a paid mutator transaction binding the contract method 0x8803dbee. +// +// Solidity: function swapTokensForExactTokens(uint256 amountOut, uint256 amountInMax, address[] path, address to, uint256 deadline) returns(uint256[] amounts) +func (_V2Router02 *V2Router02TransactorSession) SwapTokensForExactTokens(amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address, deadline *big.Int) (*types.Transaction, error) { + return _V2Router02.Contract.SwapTokensForExactTokens(&_V2Router02.TransactOpts, amountOut, amountInMax, path, to, deadline) +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_V2Router02 *V2Router02Transactor) Receive(opts *bind.TransactOpts) (*types.Transaction, error) { + return _V2Router02.contract.RawTransact(opts, nil) // calldata is disallowed for receive function +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_V2Router02 *V2Router02Session) Receive() (*types.Transaction, error) { + return _V2Router02.Contract.Receive(&_V2Router02.TransactOpts) +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_V2Router02 *V2Router02TransactorSession) Receive() (*types.Transaction, error) { + return _V2Router02.Contract.Receive(&_V2Router02.TransactOpts) +} diff --git a/utils/provider/dex/uniswap/abi/v3SwapRouter/v3SwapRouter.go b/utils/provider/dex/uniswap/abi/v3SwapRouter/v3SwapRouter.go new file mode 100644 index 0000000..53008d5 --- /dev/null +++ b/utils/provider/dex/uniswap/abi/v3SwapRouter/v3SwapRouter.go @@ -0,0 +1,621 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package v3SwapRouter + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription + _ = abi.ConvertType +) + +// ISwapRouterExactInputParams is an auto generated low-level Go binding around an user-defined struct. +type ISwapRouterExactInputParams struct { + Path []byte + Recipient common.Address + Deadline *big.Int + AmountIn *big.Int + AmountOutMinimum *big.Int +} + +// ISwapRouterExactInputSingleParams is an auto generated low-level Go binding around an user-defined struct. +type ISwapRouterExactInputSingleParams struct { + TokenIn common.Address + TokenOut common.Address + Fee *big.Int + Recipient common.Address + Deadline *big.Int + AmountIn *big.Int + AmountOutMinimum *big.Int + SqrtPriceLimitX96 *big.Int +} + +// ISwapRouterExactOutputParams is an auto generated low-level Go binding around an user-defined struct. +type ISwapRouterExactOutputParams struct { + Path []byte + Recipient common.Address + Deadline *big.Int + AmountOut *big.Int + AmountInMaximum *big.Int +} + +// ISwapRouterExactOutputSingleParams is an auto generated low-level Go binding around an user-defined struct. +type ISwapRouterExactOutputSingleParams struct { + TokenIn common.Address + TokenOut common.Address + Fee *big.Int + Recipient common.Address + Deadline *big.Int + AmountOut *big.Int + AmountInMaximum *big.Int + SqrtPriceLimitX96 *big.Int +} + +// V3SwapRouterMetaData contains all meta data concerning the V3SwapRouter contract. +var V3SwapRouterMetaData = &bind.MetaData{ + ABI: "[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_factory\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_WETH9\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"WETH9\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"internalType\":\"bytes\",\"name\":\"path\",\"type\":\"bytes\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMinimum\",\"type\":\"uint256\"}],\"internalType\":\"structISwapRouter.ExactInputParams\",\"name\":\"params\",\"type\":\"tuple\"}],\"name\":\"exactInput\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"tokenIn\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"tokenOut\",\"type\":\"address\"},{\"internalType\":\"uint24\",\"name\":\"fee\",\"type\":\"uint24\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMinimum\",\"type\":\"uint256\"},{\"internalType\":\"uint160\",\"name\":\"sqrtPriceLimitX96\",\"type\":\"uint160\"}],\"internalType\":\"structISwapRouter.ExactInputSingleParams\",\"name\":\"params\",\"type\":\"tuple\"}],\"name\":\"exactInputSingle\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"internalType\":\"bytes\",\"name\":\"path\",\"type\":\"bytes\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountInMaximum\",\"type\":\"uint256\"}],\"internalType\":\"structISwapRouter.ExactOutputParams\",\"name\":\"params\",\"type\":\"tuple\"}],\"name\":\"exactOutput\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"tokenIn\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"tokenOut\",\"type\":\"address\"},{\"internalType\":\"uint24\",\"name\":\"fee\",\"type\":\"uint24\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountInMaximum\",\"type\":\"uint256\"},{\"internalType\":\"uint160\",\"name\":\"sqrtPriceLimitX96\",\"type\":\"uint160\"}],\"internalType\":\"structISwapRouter.ExactOutputSingleParams\",\"name\":\"params\",\"type\":\"tuple\"}],\"name\":\"exactOutputSingle\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"factory\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes[]\",\"name\":\"data\",\"type\":\"bytes[]\"}],\"name\":\"multicall\",\"outputs\":[{\"internalType\":\"bytes[]\",\"name\":\"results\",\"type\":\"bytes[]\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"refundETH\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"selfPermit\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"nonce\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"expiry\",\"type\":\"uint256\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"selfPermitAllowed\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"nonce\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"expiry\",\"type\":\"uint256\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"selfPermitAllowedIfNecessary\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"selfPermitIfNecessary\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amountMinimum\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"}],\"name\":\"sweepToken\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amountMinimum\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"feeBips\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"feeRecipient\",\"type\":\"address\"}],\"name\":\"sweepTokenWithFee\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"int256\",\"name\":\"amount0Delta\",\"type\":\"int256\"},{\"internalType\":\"int256\",\"name\":\"amount1Delta\",\"type\":\"int256\"},{\"internalType\":\"bytes\",\"name\":\"_data\",\"type\":\"bytes\"}],\"name\":\"uniswapV3SwapCallback\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountMinimum\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"}],\"name\":\"unwrapWETH9\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountMinimum\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"feeBips\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"feeRecipient\",\"type\":\"address\"}],\"name\":\"unwrapWETH9WithFee\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}]", +} + +// V3SwapRouterABI is the input ABI used to generate the binding from. +// Deprecated: Use V3SwapRouterMetaData.ABI instead. +var V3SwapRouterABI = V3SwapRouterMetaData.ABI + +// V3SwapRouter is an auto generated Go binding around an Ethereum contract. +type V3SwapRouter struct { + V3SwapRouterCaller // Read-only binding to the contract + V3SwapRouterTransactor // Write-only binding to the contract + V3SwapRouterFilterer // Log filterer for contract events +} + +// V3SwapRouterCaller is an auto generated read-only Go binding around an Ethereum contract. +type V3SwapRouterCaller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// V3SwapRouterTransactor is an auto generated write-only Go binding around an Ethereum contract. +type V3SwapRouterTransactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// V3SwapRouterFilterer is an auto generated log filtering Go binding around an Ethereum contract events. +type V3SwapRouterFilterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// V3SwapRouterSession is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type V3SwapRouterSession struct { + Contract *V3SwapRouter // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// V3SwapRouterCallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type V3SwapRouterCallerSession struct { + Contract *V3SwapRouterCaller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// V3SwapRouterTransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type V3SwapRouterTransactorSession struct { + Contract *V3SwapRouterTransactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// V3SwapRouterRaw is an auto generated low-level Go binding around an Ethereum contract. +type V3SwapRouterRaw struct { + Contract *V3SwapRouter // Generic contract binding to access the raw methods on +} + +// V3SwapRouterCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type V3SwapRouterCallerRaw struct { + Contract *V3SwapRouterCaller // Generic read-only contract binding to access the raw methods on +} + +// V3SwapRouterTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type V3SwapRouterTransactorRaw struct { + Contract *V3SwapRouterTransactor // Generic write-only contract binding to access the raw methods on +} + +// NewV3SwapRouter creates a new instance of V3SwapRouter, bound to a specific deployed contract. +func NewV3SwapRouter(address common.Address, backend bind.ContractBackend) (*V3SwapRouter, error) { + contract, err := bindV3SwapRouter(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &V3SwapRouter{V3SwapRouterCaller: V3SwapRouterCaller{contract: contract}, V3SwapRouterTransactor: V3SwapRouterTransactor{contract: contract}, V3SwapRouterFilterer: V3SwapRouterFilterer{contract: contract}}, nil +} + +// NewV3SwapRouterCaller creates a new read-only instance of V3SwapRouter, bound to a specific deployed contract. +func NewV3SwapRouterCaller(address common.Address, caller bind.ContractCaller) (*V3SwapRouterCaller, error) { + contract, err := bindV3SwapRouter(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &V3SwapRouterCaller{contract: contract}, nil +} + +// NewV3SwapRouterTransactor creates a new write-only instance of V3SwapRouter, bound to a specific deployed contract. +func NewV3SwapRouterTransactor(address common.Address, transactor bind.ContractTransactor) (*V3SwapRouterTransactor, error) { + contract, err := bindV3SwapRouter(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &V3SwapRouterTransactor{contract: contract}, nil +} + +// NewV3SwapRouterFilterer creates a new log filterer instance of V3SwapRouter, bound to a specific deployed contract. +func NewV3SwapRouterFilterer(address common.Address, filterer bind.ContractFilterer) (*V3SwapRouterFilterer, error) { + contract, err := bindV3SwapRouter(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &V3SwapRouterFilterer{contract: contract}, nil +} + +// bindV3SwapRouter binds a generic wrapper to an already deployed contract. +func bindV3SwapRouter(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := V3SwapRouterMetaData.GetAbi() + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_V3SwapRouter *V3SwapRouterRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _V3SwapRouter.Contract.V3SwapRouterCaller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_V3SwapRouter *V3SwapRouterRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _V3SwapRouter.Contract.V3SwapRouterTransactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_V3SwapRouter *V3SwapRouterRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _V3SwapRouter.Contract.V3SwapRouterTransactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_V3SwapRouter *V3SwapRouterCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _V3SwapRouter.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_V3SwapRouter *V3SwapRouterTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _V3SwapRouter.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_V3SwapRouter *V3SwapRouterTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _V3SwapRouter.Contract.contract.Transact(opts, method, params...) +} + +// WETH9 is a free data retrieval call binding the contract method 0x4aa4a4fc. +// +// Solidity: function WETH9() view returns(address) +func (_V3SwapRouter *V3SwapRouterCaller) WETH9(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _V3SwapRouter.contract.Call(opts, &out, "WETH9") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// WETH9 is a free data retrieval call binding the contract method 0x4aa4a4fc. +// +// Solidity: function WETH9() view returns(address) +func (_V3SwapRouter *V3SwapRouterSession) WETH9() (common.Address, error) { + return _V3SwapRouter.Contract.WETH9(&_V3SwapRouter.CallOpts) +} + +// WETH9 is a free data retrieval call binding the contract method 0x4aa4a4fc. +// +// Solidity: function WETH9() view returns(address) +func (_V3SwapRouter *V3SwapRouterCallerSession) WETH9() (common.Address, error) { + return _V3SwapRouter.Contract.WETH9(&_V3SwapRouter.CallOpts) +} + +// Factory is a free data retrieval call binding the contract method 0xc45a0155. +// +// Solidity: function factory() view returns(address) +func (_V3SwapRouter *V3SwapRouterCaller) Factory(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _V3SwapRouter.contract.Call(opts, &out, "factory") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// Factory is a free data retrieval call binding the contract method 0xc45a0155. +// +// Solidity: function factory() view returns(address) +func (_V3SwapRouter *V3SwapRouterSession) Factory() (common.Address, error) { + return _V3SwapRouter.Contract.Factory(&_V3SwapRouter.CallOpts) +} + +// Factory is a free data retrieval call binding the contract method 0xc45a0155. +// +// Solidity: function factory() view returns(address) +func (_V3SwapRouter *V3SwapRouterCallerSession) Factory() (common.Address, error) { + return _V3SwapRouter.Contract.Factory(&_V3SwapRouter.CallOpts) +} + +// ExactInput is a paid mutator transaction binding the contract method 0xc04b8d59. +// +// Solidity: function exactInput((bytes,address,uint256,uint256,uint256) params) payable returns(uint256 amountOut) +func (_V3SwapRouter *V3SwapRouterTransactor) ExactInput(opts *bind.TransactOpts, params ISwapRouterExactInputParams) (*types.Transaction, error) { + return _V3SwapRouter.contract.Transact(opts, "exactInput", params) +} + +// ExactInput is a paid mutator transaction binding the contract method 0xc04b8d59. +// +// Solidity: function exactInput((bytes,address,uint256,uint256,uint256) params) payable returns(uint256 amountOut) +func (_V3SwapRouter *V3SwapRouterSession) ExactInput(params ISwapRouterExactInputParams) (*types.Transaction, error) { + return _V3SwapRouter.Contract.ExactInput(&_V3SwapRouter.TransactOpts, params) +} + +// ExactInput is a paid mutator transaction binding the contract method 0xc04b8d59. +// +// Solidity: function exactInput((bytes,address,uint256,uint256,uint256) params) payable returns(uint256 amountOut) +func (_V3SwapRouter *V3SwapRouterTransactorSession) ExactInput(params ISwapRouterExactInputParams) (*types.Transaction, error) { + return _V3SwapRouter.Contract.ExactInput(&_V3SwapRouter.TransactOpts, params) +} + +// ExactInputSingle is a paid mutator transaction binding the contract method 0x414bf389. +// +// Solidity: function exactInputSingle((address,address,uint24,address,uint256,uint256,uint256,uint160) params) payable returns(uint256 amountOut) +func (_V3SwapRouter *V3SwapRouterTransactor) ExactInputSingle(opts *bind.TransactOpts, params ISwapRouterExactInputSingleParams) (*types.Transaction, error) { + return _V3SwapRouter.contract.Transact(opts, "exactInputSingle", params) +} + +// ExactInputSingle is a paid mutator transaction binding the contract method 0x414bf389. +// +// Solidity: function exactInputSingle((address,address,uint24,address,uint256,uint256,uint256,uint160) params) payable returns(uint256 amountOut) +func (_V3SwapRouter *V3SwapRouterSession) ExactInputSingle(params ISwapRouterExactInputSingleParams) (*types.Transaction, error) { + return _V3SwapRouter.Contract.ExactInputSingle(&_V3SwapRouter.TransactOpts, params) +} + +// ExactInputSingle is a paid mutator transaction binding the contract method 0x414bf389. +// +// Solidity: function exactInputSingle((address,address,uint24,address,uint256,uint256,uint256,uint160) params) payable returns(uint256 amountOut) +func (_V3SwapRouter *V3SwapRouterTransactorSession) ExactInputSingle(params ISwapRouterExactInputSingleParams) (*types.Transaction, error) { + return _V3SwapRouter.Contract.ExactInputSingle(&_V3SwapRouter.TransactOpts, params) +} + +// ExactOutput is a paid mutator transaction binding the contract method 0xf28c0498. +// +// Solidity: function exactOutput((bytes,address,uint256,uint256,uint256) params) payable returns(uint256 amountIn) +func (_V3SwapRouter *V3SwapRouterTransactor) ExactOutput(opts *bind.TransactOpts, params ISwapRouterExactOutputParams) (*types.Transaction, error) { + return _V3SwapRouter.contract.Transact(opts, "exactOutput", params) +} + +// ExactOutput is a paid mutator transaction binding the contract method 0xf28c0498. +// +// Solidity: function exactOutput((bytes,address,uint256,uint256,uint256) params) payable returns(uint256 amountIn) +func (_V3SwapRouter *V3SwapRouterSession) ExactOutput(params ISwapRouterExactOutputParams) (*types.Transaction, error) { + return _V3SwapRouter.Contract.ExactOutput(&_V3SwapRouter.TransactOpts, params) +} + +// ExactOutput is a paid mutator transaction binding the contract method 0xf28c0498. +// +// Solidity: function exactOutput((bytes,address,uint256,uint256,uint256) params) payable returns(uint256 amountIn) +func (_V3SwapRouter *V3SwapRouterTransactorSession) ExactOutput(params ISwapRouterExactOutputParams) (*types.Transaction, error) { + return _V3SwapRouter.Contract.ExactOutput(&_V3SwapRouter.TransactOpts, params) +} + +// ExactOutputSingle is a paid mutator transaction binding the contract method 0xdb3e2198. +// +// Solidity: function exactOutputSingle((address,address,uint24,address,uint256,uint256,uint256,uint160) params) payable returns(uint256 amountIn) +func (_V3SwapRouter *V3SwapRouterTransactor) ExactOutputSingle(opts *bind.TransactOpts, params ISwapRouterExactOutputSingleParams) (*types.Transaction, error) { + return _V3SwapRouter.contract.Transact(opts, "exactOutputSingle", params) +} + +// ExactOutputSingle is a paid mutator transaction binding the contract method 0xdb3e2198. +// +// Solidity: function exactOutputSingle((address,address,uint24,address,uint256,uint256,uint256,uint160) params) payable returns(uint256 amountIn) +func (_V3SwapRouter *V3SwapRouterSession) ExactOutputSingle(params ISwapRouterExactOutputSingleParams) (*types.Transaction, error) { + return _V3SwapRouter.Contract.ExactOutputSingle(&_V3SwapRouter.TransactOpts, params) +} + +// ExactOutputSingle is a paid mutator transaction binding the contract method 0xdb3e2198. +// +// Solidity: function exactOutputSingle((address,address,uint24,address,uint256,uint256,uint256,uint160) params) payable returns(uint256 amountIn) +func (_V3SwapRouter *V3SwapRouterTransactorSession) ExactOutputSingle(params ISwapRouterExactOutputSingleParams) (*types.Transaction, error) { + return _V3SwapRouter.Contract.ExactOutputSingle(&_V3SwapRouter.TransactOpts, params) +} + +// Multicall is a paid mutator transaction binding the contract method 0xac9650d8. +// +// Solidity: function multicall(bytes[] data) payable returns(bytes[] results) +func (_V3SwapRouter *V3SwapRouterTransactor) Multicall(opts *bind.TransactOpts, data [][]byte) (*types.Transaction, error) { + return _V3SwapRouter.contract.Transact(opts, "multicall", data) +} + +// Multicall is a paid mutator transaction binding the contract method 0xac9650d8. +// +// Solidity: function multicall(bytes[] data) payable returns(bytes[] results) +func (_V3SwapRouter *V3SwapRouterSession) Multicall(data [][]byte) (*types.Transaction, error) { + return _V3SwapRouter.Contract.Multicall(&_V3SwapRouter.TransactOpts, data) +} + +// Multicall is a paid mutator transaction binding the contract method 0xac9650d8. +// +// Solidity: function multicall(bytes[] data) payable returns(bytes[] results) +func (_V3SwapRouter *V3SwapRouterTransactorSession) Multicall(data [][]byte) (*types.Transaction, error) { + return _V3SwapRouter.Contract.Multicall(&_V3SwapRouter.TransactOpts, data) +} + +// RefundETH is a paid mutator transaction binding the contract method 0x12210e8a. +// +// Solidity: function refundETH() payable returns() +func (_V3SwapRouter *V3SwapRouterTransactor) RefundETH(opts *bind.TransactOpts) (*types.Transaction, error) { + return _V3SwapRouter.contract.Transact(opts, "refundETH") +} + +// RefundETH is a paid mutator transaction binding the contract method 0x12210e8a. +// +// Solidity: function refundETH() payable returns() +func (_V3SwapRouter *V3SwapRouterSession) RefundETH() (*types.Transaction, error) { + return _V3SwapRouter.Contract.RefundETH(&_V3SwapRouter.TransactOpts) +} + +// RefundETH is a paid mutator transaction binding the contract method 0x12210e8a. +// +// Solidity: function refundETH() payable returns() +func (_V3SwapRouter *V3SwapRouterTransactorSession) RefundETH() (*types.Transaction, error) { + return _V3SwapRouter.Contract.RefundETH(&_V3SwapRouter.TransactOpts) +} + +// SelfPermit is a paid mutator transaction binding the contract method 0xf3995c67. +// +// Solidity: function selfPermit(address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter *V3SwapRouterTransactor) SelfPermit(opts *bind.TransactOpts, token common.Address, value *big.Int, deadline *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter.contract.Transact(opts, "selfPermit", token, value, deadline, v, r, s) +} + +// SelfPermit is a paid mutator transaction binding the contract method 0xf3995c67. +// +// Solidity: function selfPermit(address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter *V3SwapRouterSession) SelfPermit(token common.Address, value *big.Int, deadline *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter.Contract.SelfPermit(&_V3SwapRouter.TransactOpts, token, value, deadline, v, r, s) +} + +// SelfPermit is a paid mutator transaction binding the contract method 0xf3995c67. +// +// Solidity: function selfPermit(address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter *V3SwapRouterTransactorSession) SelfPermit(token common.Address, value *big.Int, deadline *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter.Contract.SelfPermit(&_V3SwapRouter.TransactOpts, token, value, deadline, v, r, s) +} + +// SelfPermitAllowed is a paid mutator transaction binding the contract method 0x4659a494. +// +// Solidity: function selfPermitAllowed(address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter *V3SwapRouterTransactor) SelfPermitAllowed(opts *bind.TransactOpts, token common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter.contract.Transact(opts, "selfPermitAllowed", token, nonce, expiry, v, r, s) +} + +// SelfPermitAllowed is a paid mutator transaction binding the contract method 0x4659a494. +// +// Solidity: function selfPermitAllowed(address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter *V3SwapRouterSession) SelfPermitAllowed(token common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter.Contract.SelfPermitAllowed(&_V3SwapRouter.TransactOpts, token, nonce, expiry, v, r, s) +} + +// SelfPermitAllowed is a paid mutator transaction binding the contract method 0x4659a494. +// +// Solidity: function selfPermitAllowed(address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter *V3SwapRouterTransactorSession) SelfPermitAllowed(token common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter.Contract.SelfPermitAllowed(&_V3SwapRouter.TransactOpts, token, nonce, expiry, v, r, s) +} + +// SelfPermitAllowedIfNecessary is a paid mutator transaction binding the contract method 0xa4a78f0c. +// +// Solidity: function selfPermitAllowedIfNecessary(address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter *V3SwapRouterTransactor) SelfPermitAllowedIfNecessary(opts *bind.TransactOpts, token common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter.contract.Transact(opts, "selfPermitAllowedIfNecessary", token, nonce, expiry, v, r, s) +} + +// SelfPermitAllowedIfNecessary is a paid mutator transaction binding the contract method 0xa4a78f0c. +// +// Solidity: function selfPermitAllowedIfNecessary(address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter *V3SwapRouterSession) SelfPermitAllowedIfNecessary(token common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter.Contract.SelfPermitAllowedIfNecessary(&_V3SwapRouter.TransactOpts, token, nonce, expiry, v, r, s) +} + +// SelfPermitAllowedIfNecessary is a paid mutator transaction binding the contract method 0xa4a78f0c. +// +// Solidity: function selfPermitAllowedIfNecessary(address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter *V3SwapRouterTransactorSession) SelfPermitAllowedIfNecessary(token common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter.Contract.SelfPermitAllowedIfNecessary(&_V3SwapRouter.TransactOpts, token, nonce, expiry, v, r, s) +} + +// SelfPermitIfNecessary is a paid mutator transaction binding the contract method 0xc2e3140a. +// +// Solidity: function selfPermitIfNecessary(address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter *V3SwapRouterTransactor) SelfPermitIfNecessary(opts *bind.TransactOpts, token common.Address, value *big.Int, deadline *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter.contract.Transact(opts, "selfPermitIfNecessary", token, value, deadline, v, r, s) +} + +// SelfPermitIfNecessary is a paid mutator transaction binding the contract method 0xc2e3140a. +// +// Solidity: function selfPermitIfNecessary(address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter *V3SwapRouterSession) SelfPermitIfNecessary(token common.Address, value *big.Int, deadline *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter.Contract.SelfPermitIfNecessary(&_V3SwapRouter.TransactOpts, token, value, deadline, v, r, s) +} + +// SelfPermitIfNecessary is a paid mutator transaction binding the contract method 0xc2e3140a. +// +// Solidity: function selfPermitIfNecessary(address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter *V3SwapRouterTransactorSession) SelfPermitIfNecessary(token common.Address, value *big.Int, deadline *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter.Contract.SelfPermitIfNecessary(&_V3SwapRouter.TransactOpts, token, value, deadline, v, r, s) +} + +// SweepToken is a paid mutator transaction binding the contract method 0xdf2ab5bb. +// +// Solidity: function sweepToken(address token, uint256 amountMinimum, address recipient) payable returns() +func (_V3SwapRouter *V3SwapRouterTransactor) SweepToken(opts *bind.TransactOpts, token common.Address, amountMinimum *big.Int, recipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter.contract.Transact(opts, "sweepToken", token, amountMinimum, recipient) +} + +// SweepToken is a paid mutator transaction binding the contract method 0xdf2ab5bb. +// +// Solidity: function sweepToken(address token, uint256 amountMinimum, address recipient) payable returns() +func (_V3SwapRouter *V3SwapRouterSession) SweepToken(token common.Address, amountMinimum *big.Int, recipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter.Contract.SweepToken(&_V3SwapRouter.TransactOpts, token, amountMinimum, recipient) +} + +// SweepToken is a paid mutator transaction binding the contract method 0xdf2ab5bb. +// +// Solidity: function sweepToken(address token, uint256 amountMinimum, address recipient) payable returns() +func (_V3SwapRouter *V3SwapRouterTransactorSession) SweepToken(token common.Address, amountMinimum *big.Int, recipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter.Contract.SweepToken(&_V3SwapRouter.TransactOpts, token, amountMinimum, recipient) +} + +// SweepTokenWithFee is a paid mutator transaction binding the contract method 0xe0e189a0. +// +// Solidity: function sweepTokenWithFee(address token, uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient) payable returns() +func (_V3SwapRouter *V3SwapRouterTransactor) SweepTokenWithFee(opts *bind.TransactOpts, token common.Address, amountMinimum *big.Int, recipient common.Address, feeBips *big.Int, feeRecipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter.contract.Transact(opts, "sweepTokenWithFee", token, amountMinimum, recipient, feeBips, feeRecipient) +} + +// SweepTokenWithFee is a paid mutator transaction binding the contract method 0xe0e189a0. +// +// Solidity: function sweepTokenWithFee(address token, uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient) payable returns() +func (_V3SwapRouter *V3SwapRouterSession) SweepTokenWithFee(token common.Address, amountMinimum *big.Int, recipient common.Address, feeBips *big.Int, feeRecipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter.Contract.SweepTokenWithFee(&_V3SwapRouter.TransactOpts, token, amountMinimum, recipient, feeBips, feeRecipient) +} + +// SweepTokenWithFee is a paid mutator transaction binding the contract method 0xe0e189a0. +// +// Solidity: function sweepTokenWithFee(address token, uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient) payable returns() +func (_V3SwapRouter *V3SwapRouterTransactorSession) SweepTokenWithFee(token common.Address, amountMinimum *big.Int, recipient common.Address, feeBips *big.Int, feeRecipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter.Contract.SweepTokenWithFee(&_V3SwapRouter.TransactOpts, token, amountMinimum, recipient, feeBips, feeRecipient) +} + +// UniswapV3SwapCallback is a paid mutator transaction binding the contract method 0xfa461e33. +// +// Solidity: function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes _data) returns() +func (_V3SwapRouter *V3SwapRouterTransactor) UniswapV3SwapCallback(opts *bind.TransactOpts, amount0Delta *big.Int, amount1Delta *big.Int, _data []byte) (*types.Transaction, error) { + return _V3SwapRouter.contract.Transact(opts, "uniswapV3SwapCallback", amount0Delta, amount1Delta, _data) +} + +// UniswapV3SwapCallback is a paid mutator transaction binding the contract method 0xfa461e33. +// +// Solidity: function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes _data) returns() +func (_V3SwapRouter *V3SwapRouterSession) UniswapV3SwapCallback(amount0Delta *big.Int, amount1Delta *big.Int, _data []byte) (*types.Transaction, error) { + return _V3SwapRouter.Contract.UniswapV3SwapCallback(&_V3SwapRouter.TransactOpts, amount0Delta, amount1Delta, _data) +} + +// UniswapV3SwapCallback is a paid mutator transaction binding the contract method 0xfa461e33. +// +// Solidity: function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes _data) returns() +func (_V3SwapRouter *V3SwapRouterTransactorSession) UniswapV3SwapCallback(amount0Delta *big.Int, amount1Delta *big.Int, _data []byte) (*types.Transaction, error) { + return _V3SwapRouter.Contract.UniswapV3SwapCallback(&_V3SwapRouter.TransactOpts, amount0Delta, amount1Delta, _data) +} + +// UnwrapWETH9 is a paid mutator transaction binding the contract method 0x49404b7c. +// +// Solidity: function unwrapWETH9(uint256 amountMinimum, address recipient) payable returns() +func (_V3SwapRouter *V3SwapRouterTransactor) UnwrapWETH9(opts *bind.TransactOpts, amountMinimum *big.Int, recipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter.contract.Transact(opts, "unwrapWETH9", amountMinimum, recipient) +} + +// UnwrapWETH9 is a paid mutator transaction binding the contract method 0x49404b7c. +// +// Solidity: function unwrapWETH9(uint256 amountMinimum, address recipient) payable returns() +func (_V3SwapRouter *V3SwapRouterSession) UnwrapWETH9(amountMinimum *big.Int, recipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter.Contract.UnwrapWETH9(&_V3SwapRouter.TransactOpts, amountMinimum, recipient) +} + +// UnwrapWETH9 is a paid mutator transaction binding the contract method 0x49404b7c. +// +// Solidity: function unwrapWETH9(uint256 amountMinimum, address recipient) payable returns() +func (_V3SwapRouter *V3SwapRouterTransactorSession) UnwrapWETH9(amountMinimum *big.Int, recipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter.Contract.UnwrapWETH9(&_V3SwapRouter.TransactOpts, amountMinimum, recipient) +} + +// UnwrapWETH9WithFee is a paid mutator transaction binding the contract method 0x9b2c0a37. +// +// Solidity: function unwrapWETH9WithFee(uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient) payable returns() +func (_V3SwapRouter *V3SwapRouterTransactor) UnwrapWETH9WithFee(opts *bind.TransactOpts, amountMinimum *big.Int, recipient common.Address, feeBips *big.Int, feeRecipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter.contract.Transact(opts, "unwrapWETH9WithFee", amountMinimum, recipient, feeBips, feeRecipient) +} + +// UnwrapWETH9WithFee is a paid mutator transaction binding the contract method 0x9b2c0a37. +// +// Solidity: function unwrapWETH9WithFee(uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient) payable returns() +func (_V3SwapRouter *V3SwapRouterSession) UnwrapWETH9WithFee(amountMinimum *big.Int, recipient common.Address, feeBips *big.Int, feeRecipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter.Contract.UnwrapWETH9WithFee(&_V3SwapRouter.TransactOpts, amountMinimum, recipient, feeBips, feeRecipient) +} + +// UnwrapWETH9WithFee is a paid mutator transaction binding the contract method 0x9b2c0a37. +// +// Solidity: function unwrapWETH9WithFee(uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient) payable returns() +func (_V3SwapRouter *V3SwapRouterTransactorSession) UnwrapWETH9WithFee(amountMinimum *big.Int, recipient common.Address, feeBips *big.Int, feeRecipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter.Contract.UnwrapWETH9WithFee(&_V3SwapRouter.TransactOpts, amountMinimum, recipient, feeBips, feeRecipient) +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_V3SwapRouter *V3SwapRouterTransactor) Receive(opts *bind.TransactOpts) (*types.Transaction, error) { + return _V3SwapRouter.contract.RawTransact(opts, nil) // calldata is disallowed for receive function +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_V3SwapRouter *V3SwapRouterSession) Receive() (*types.Transaction, error) { + return _V3SwapRouter.Contract.Receive(&_V3SwapRouter.TransactOpts) +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_V3SwapRouter *V3SwapRouterTransactorSession) Receive() (*types.Transaction, error) { + return _V3SwapRouter.Contract.Receive(&_V3SwapRouter.TransactOpts) +} diff --git a/utils/provider/dex/uniswap/abi/v3SwapRouter02/v3SwapRouter02.go b/utils/provider/dex/uniswap/abi/v3SwapRouter02/v3SwapRouter02.go new file mode 100644 index 0000000..490b946 --- /dev/null +++ b/utils/provider/dex/uniswap/abi/v3SwapRouter02/v3SwapRouter02.go @@ -0,0 +1,1136 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package v3SwapRouter02 + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription + _ = abi.ConvertType +) + +// IApproveAndCallIncreaseLiquidityParams is an auto generated low-level Go binding around an user-defined struct. +type IApproveAndCallIncreaseLiquidityParams struct { + Token0 common.Address + Token1 common.Address + TokenId *big.Int + Amount0Min *big.Int + Amount1Min *big.Int +} + +// IApproveAndCallMintParams is an auto generated low-level Go binding around an user-defined struct. +type IApproveAndCallMintParams struct { + Token0 common.Address + Token1 common.Address + Fee *big.Int + TickLower *big.Int + TickUpper *big.Int + Amount0Min *big.Int + Amount1Min *big.Int + Recipient common.Address +} + +// IV3SwapRouterExactInputParams is an auto generated low-level Go binding around an user-defined struct. +type IV3SwapRouterExactInputParams struct { + Path []byte + Recipient common.Address + AmountIn *big.Int + AmountOutMinimum *big.Int +} + +// IV3SwapRouterExactInputSingleParams is an auto generated low-level Go binding around an user-defined struct. +type IV3SwapRouterExactInputSingleParams struct { + TokenIn common.Address + TokenOut common.Address + Fee *big.Int + Recipient common.Address + AmountIn *big.Int + AmountOutMinimum *big.Int + SqrtPriceLimitX96 *big.Int +} + +// IV3SwapRouterExactOutputParams is an auto generated low-level Go binding around an user-defined struct. +type IV3SwapRouterExactOutputParams struct { + Path []byte + Recipient common.Address + AmountOut *big.Int + AmountInMaximum *big.Int +} + +// IV3SwapRouterExactOutputSingleParams is an auto generated low-level Go binding around an user-defined struct. +type IV3SwapRouterExactOutputSingleParams struct { + TokenIn common.Address + TokenOut common.Address + Fee *big.Int + Recipient common.Address + AmountOut *big.Int + AmountInMaximum *big.Int + SqrtPriceLimitX96 *big.Int +} + +// V3SwapRouter02MetaData contains all meta data concerning the V3SwapRouter02 contract. +var V3SwapRouter02MetaData = &bind.MetaData{ + ABI: "[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_factoryV2\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"factoryV3\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_positionManager\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_WETH9\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"WETH9\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"}],\"name\":\"approveMax\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"}],\"name\":\"approveMaxMinusOne\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"}],\"name\":\"approveZeroThenMax\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"}],\"name\":\"approveZeroThenMaxMinusOne\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"callPositionManager\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"result\",\"type\":\"bytes\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes[]\",\"name\":\"paths\",\"type\":\"bytes[]\"},{\"internalType\":\"uint128[]\",\"name\":\"amounts\",\"type\":\"uint128[]\"},{\"internalType\":\"uint24\",\"name\":\"maximumTickDivergence\",\"type\":\"uint24\"},{\"internalType\":\"uint32\",\"name\":\"secondsAgo\",\"type\":\"uint32\"}],\"name\":\"checkOracleSlippage\",\"outputs\":[],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"path\",\"type\":\"bytes\"},{\"internalType\":\"uint24\",\"name\":\"maximumTickDivergence\",\"type\":\"uint24\"},{\"internalType\":\"uint32\",\"name\":\"secondsAgo\",\"type\":\"uint32\"}],\"name\":\"checkOracleSlippage\",\"outputs\":[],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"internalType\":\"bytes\",\"name\":\"path\",\"type\":\"bytes\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMinimum\",\"type\":\"uint256\"}],\"internalType\":\"structIV3SwapRouter.ExactInputParams\",\"name\":\"params\",\"type\":\"tuple\"}],\"name\":\"exactInput\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"tokenIn\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"tokenOut\",\"type\":\"address\"},{\"internalType\":\"uint24\",\"name\":\"fee\",\"type\":\"uint24\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMinimum\",\"type\":\"uint256\"},{\"internalType\":\"uint160\",\"name\":\"sqrtPriceLimitX96\",\"type\":\"uint160\"}],\"internalType\":\"structIV3SwapRouter.ExactInputSingleParams\",\"name\":\"params\",\"type\":\"tuple\"}],\"name\":\"exactInputSingle\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"internalType\":\"bytes\",\"name\":\"path\",\"type\":\"bytes\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountInMaximum\",\"type\":\"uint256\"}],\"internalType\":\"structIV3SwapRouter.ExactOutputParams\",\"name\":\"params\",\"type\":\"tuple\"}],\"name\":\"exactOutput\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"tokenIn\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"tokenOut\",\"type\":\"address\"},{\"internalType\":\"uint24\",\"name\":\"fee\",\"type\":\"uint24\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountInMaximum\",\"type\":\"uint256\"},{\"internalType\":\"uint160\",\"name\":\"sqrtPriceLimitX96\",\"type\":\"uint160\"}],\"internalType\":\"structIV3SwapRouter.ExactOutputSingleParams\",\"name\":\"params\",\"type\":\"tuple\"}],\"name\":\"exactOutputSingle\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"factory\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"factoryV2\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"getApprovalType\",\"outputs\":[{\"internalType\":\"enumIApproveAndCall.ApprovalType\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"token0\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"token1\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"tokenId\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amount0Min\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amount1Min\",\"type\":\"uint256\"}],\"internalType\":\"structIApproveAndCall.IncreaseLiquidityParams\",\"name\":\"params\",\"type\":\"tuple\"}],\"name\":\"increaseLiquidity\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"result\",\"type\":\"bytes\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"token0\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"token1\",\"type\":\"address\"},{\"internalType\":\"uint24\",\"name\":\"fee\",\"type\":\"uint24\"},{\"internalType\":\"int24\",\"name\":\"tickLower\",\"type\":\"int24\"},{\"internalType\":\"int24\",\"name\":\"tickUpper\",\"type\":\"int24\"},{\"internalType\":\"uint256\",\"name\":\"amount0Min\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amount1Min\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"}],\"internalType\":\"structIApproveAndCall.MintParams\",\"name\":\"params\",\"type\":\"tuple\"}],\"name\":\"mint\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"result\",\"type\":\"bytes\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"previousBlockhash\",\"type\":\"bytes32\"},{\"internalType\":\"bytes[]\",\"name\":\"data\",\"type\":\"bytes[]\"}],\"name\":\"multicall\",\"outputs\":[{\"internalType\":\"bytes[]\",\"name\":\"\",\"type\":\"bytes[]\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"bytes[]\",\"name\":\"data\",\"type\":\"bytes[]\"}],\"name\":\"multicall\",\"outputs\":[{\"internalType\":\"bytes[]\",\"name\":\"\",\"type\":\"bytes[]\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes[]\",\"name\":\"data\",\"type\":\"bytes[]\"}],\"name\":\"multicall\",\"outputs\":[{\"internalType\":\"bytes[]\",\"name\":\"results\",\"type\":\"bytes[]\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"positionManager\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"pull\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"refundETH\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"selfPermit\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"nonce\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"expiry\",\"type\":\"uint256\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"selfPermitAllowed\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"nonce\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"expiry\",\"type\":\"uint256\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"selfPermitAllowedIfNecessary\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"selfPermitIfNecessary\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountOutMin\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"}],\"name\":\"swapExactTokensForTokens\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountOut\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amountInMax\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"path\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"}],\"name\":\"swapTokensForExactTokens\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amountIn\",\"type\":\"uint256\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amountMinimum\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"}],\"name\":\"sweepToken\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amountMinimum\",\"type\":\"uint256\"}],\"name\":\"sweepToken\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amountMinimum\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"feeBips\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"feeRecipient\",\"type\":\"address\"}],\"name\":\"sweepTokenWithFee\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amountMinimum\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"feeBips\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"feeRecipient\",\"type\":\"address\"}],\"name\":\"sweepTokenWithFee\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"int256\",\"name\":\"amount0Delta\",\"type\":\"int256\"},{\"internalType\":\"int256\",\"name\":\"amount1Delta\",\"type\":\"int256\"},{\"internalType\":\"bytes\",\"name\":\"_data\",\"type\":\"bytes\"}],\"name\":\"uniswapV3SwapCallback\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountMinimum\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"}],\"name\":\"unwrapWETH9\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountMinimum\",\"type\":\"uint256\"}],\"name\":\"unwrapWETH9\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountMinimum\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"feeBips\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"feeRecipient\",\"type\":\"address\"}],\"name\":\"unwrapWETH9WithFee\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountMinimum\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"feeBips\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"feeRecipient\",\"type\":\"address\"}],\"name\":\"unwrapWETH9WithFee\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"wrapETH\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}]", +} + +// V3SwapRouter02ABI is the input ABI used to generate the binding from. +// Deprecated: Use V3SwapRouter02MetaData.ABI instead. +var V3SwapRouter02ABI = V3SwapRouter02MetaData.ABI + +// V3SwapRouter02 is an auto generated Go binding around an Ethereum contract. +type V3SwapRouter02 struct { + V3SwapRouter02Caller // Read-only binding to the contract + V3SwapRouter02Transactor // Write-only binding to the contract + V3SwapRouter02Filterer // Log filterer for contract events +} + +// V3SwapRouter02Caller is an auto generated read-only Go binding around an Ethereum contract. +type V3SwapRouter02Caller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// V3SwapRouter02Transactor is an auto generated write-only Go binding around an Ethereum contract. +type V3SwapRouter02Transactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// V3SwapRouter02Filterer is an auto generated log filtering Go binding around an Ethereum contract events. +type V3SwapRouter02Filterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// V3SwapRouter02Session is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type V3SwapRouter02Session struct { + Contract *V3SwapRouter02 // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// V3SwapRouter02CallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type V3SwapRouter02CallerSession struct { + Contract *V3SwapRouter02Caller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// V3SwapRouter02TransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type V3SwapRouter02TransactorSession struct { + Contract *V3SwapRouter02Transactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// V3SwapRouter02Raw is an auto generated low-level Go binding around an Ethereum contract. +type V3SwapRouter02Raw struct { + Contract *V3SwapRouter02 // Generic contract binding to access the raw methods on +} + +// V3SwapRouter02CallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type V3SwapRouter02CallerRaw struct { + Contract *V3SwapRouter02Caller // Generic read-only contract binding to access the raw methods on +} + +// V3SwapRouter02TransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type V3SwapRouter02TransactorRaw struct { + Contract *V3SwapRouter02Transactor // Generic write-only contract binding to access the raw methods on +} + +// NewV3SwapRouter02 creates a new instance of V3SwapRouter02, bound to a specific deployed contract. +func NewV3SwapRouter02(address common.Address, backend bind.ContractBackend) (*V3SwapRouter02, error) { + contract, err := bindV3SwapRouter02(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &V3SwapRouter02{V3SwapRouter02Caller: V3SwapRouter02Caller{contract: contract}, V3SwapRouter02Transactor: V3SwapRouter02Transactor{contract: contract}, V3SwapRouter02Filterer: V3SwapRouter02Filterer{contract: contract}}, nil +} + +// NewV3SwapRouter02Caller creates a new read-only instance of V3SwapRouter02, bound to a specific deployed contract. +func NewV3SwapRouter02Caller(address common.Address, caller bind.ContractCaller) (*V3SwapRouter02Caller, error) { + contract, err := bindV3SwapRouter02(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &V3SwapRouter02Caller{contract: contract}, nil +} + +// NewV3SwapRouter02Transactor creates a new write-only instance of V3SwapRouter02, bound to a specific deployed contract. +func NewV3SwapRouter02Transactor(address common.Address, transactor bind.ContractTransactor) (*V3SwapRouter02Transactor, error) { + contract, err := bindV3SwapRouter02(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &V3SwapRouter02Transactor{contract: contract}, nil +} + +// NewV3SwapRouter02Filterer creates a new log filterer instance of V3SwapRouter02, bound to a specific deployed contract. +func NewV3SwapRouter02Filterer(address common.Address, filterer bind.ContractFilterer) (*V3SwapRouter02Filterer, error) { + contract, err := bindV3SwapRouter02(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &V3SwapRouter02Filterer{contract: contract}, nil +} + +// bindV3SwapRouter02 binds a generic wrapper to an already deployed contract. +func bindV3SwapRouter02(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := V3SwapRouter02MetaData.GetAbi() + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_V3SwapRouter02 *V3SwapRouter02Raw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _V3SwapRouter02.Contract.V3SwapRouter02Caller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_V3SwapRouter02 *V3SwapRouter02Raw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.V3SwapRouter02Transactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_V3SwapRouter02 *V3SwapRouter02Raw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.V3SwapRouter02Transactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_V3SwapRouter02 *V3SwapRouter02CallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _V3SwapRouter02.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_V3SwapRouter02 *V3SwapRouter02TransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_V3SwapRouter02 *V3SwapRouter02TransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.contract.Transact(opts, method, params...) +} + +// WETH9 is a free data retrieval call binding the contract method 0x4aa4a4fc. +// +// Solidity: function WETH9() view returns(address) +func (_V3SwapRouter02 *V3SwapRouter02Caller) WETH9(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _V3SwapRouter02.contract.Call(opts, &out, "WETH9") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// WETH9 is a free data retrieval call binding the contract method 0x4aa4a4fc. +// +// Solidity: function WETH9() view returns(address) +func (_V3SwapRouter02 *V3SwapRouter02Session) WETH9() (common.Address, error) { + return _V3SwapRouter02.Contract.WETH9(&_V3SwapRouter02.CallOpts) +} + +// WETH9 is a free data retrieval call binding the contract method 0x4aa4a4fc. +// +// Solidity: function WETH9() view returns(address) +func (_V3SwapRouter02 *V3SwapRouter02CallerSession) WETH9() (common.Address, error) { + return _V3SwapRouter02.Contract.WETH9(&_V3SwapRouter02.CallOpts) +} + +// CheckOracleSlippage is a free data retrieval call binding the contract method 0xefdeed8e. +// +// Solidity: function checkOracleSlippage(bytes[] paths, uint128[] amounts, uint24 maximumTickDivergence, uint32 secondsAgo) view returns() +func (_V3SwapRouter02 *V3SwapRouter02Caller) CheckOracleSlippage(opts *bind.CallOpts, paths [][]byte, amounts []*big.Int, maximumTickDivergence *big.Int, secondsAgo uint32) error { + var out []interface{} + err := _V3SwapRouter02.contract.Call(opts, &out, "checkOracleSlippage", paths, amounts, maximumTickDivergence, secondsAgo) + + if err != nil { + return err + } + + return err + +} + +// CheckOracleSlippage is a free data retrieval call binding the contract method 0xefdeed8e. +// +// Solidity: function checkOracleSlippage(bytes[] paths, uint128[] amounts, uint24 maximumTickDivergence, uint32 secondsAgo) view returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) CheckOracleSlippage(paths [][]byte, amounts []*big.Int, maximumTickDivergence *big.Int, secondsAgo uint32) error { + return _V3SwapRouter02.Contract.CheckOracleSlippage(&_V3SwapRouter02.CallOpts, paths, amounts, maximumTickDivergence, secondsAgo) +} + +// CheckOracleSlippage is a free data retrieval call binding the contract method 0xefdeed8e. +// +// Solidity: function checkOracleSlippage(bytes[] paths, uint128[] amounts, uint24 maximumTickDivergence, uint32 secondsAgo) view returns() +func (_V3SwapRouter02 *V3SwapRouter02CallerSession) CheckOracleSlippage(paths [][]byte, amounts []*big.Int, maximumTickDivergence *big.Int, secondsAgo uint32) error { + return _V3SwapRouter02.Contract.CheckOracleSlippage(&_V3SwapRouter02.CallOpts, paths, amounts, maximumTickDivergence, secondsAgo) +} + +// CheckOracleSlippage0 is a free data retrieval call binding the contract method 0xf25801a7. +// +// Solidity: function checkOracleSlippage(bytes path, uint24 maximumTickDivergence, uint32 secondsAgo) view returns() +func (_V3SwapRouter02 *V3SwapRouter02Caller) CheckOracleSlippage0(opts *bind.CallOpts, path []byte, maximumTickDivergence *big.Int, secondsAgo uint32) error { + var out []interface{} + err := _V3SwapRouter02.contract.Call(opts, &out, "checkOracleSlippage0", path, maximumTickDivergence, secondsAgo) + + if err != nil { + return err + } + + return err + +} + +// CheckOracleSlippage0 is a free data retrieval call binding the contract method 0xf25801a7. +// +// Solidity: function checkOracleSlippage(bytes path, uint24 maximumTickDivergence, uint32 secondsAgo) view returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) CheckOracleSlippage0(path []byte, maximumTickDivergence *big.Int, secondsAgo uint32) error { + return _V3SwapRouter02.Contract.CheckOracleSlippage0(&_V3SwapRouter02.CallOpts, path, maximumTickDivergence, secondsAgo) +} + +// CheckOracleSlippage0 is a free data retrieval call binding the contract method 0xf25801a7. +// +// Solidity: function checkOracleSlippage(bytes path, uint24 maximumTickDivergence, uint32 secondsAgo) view returns() +func (_V3SwapRouter02 *V3SwapRouter02CallerSession) CheckOracleSlippage0(path []byte, maximumTickDivergence *big.Int, secondsAgo uint32) error { + return _V3SwapRouter02.Contract.CheckOracleSlippage0(&_V3SwapRouter02.CallOpts, path, maximumTickDivergence, secondsAgo) +} + +// Factory is a free data retrieval call binding the contract method 0xc45a0155. +// +// Solidity: function factory() view returns(address) +func (_V3SwapRouter02 *V3SwapRouter02Caller) Factory(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _V3SwapRouter02.contract.Call(opts, &out, "factory") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// Factory is a free data retrieval call binding the contract method 0xc45a0155. +// +// Solidity: function factory() view returns(address) +func (_V3SwapRouter02 *V3SwapRouter02Session) Factory() (common.Address, error) { + return _V3SwapRouter02.Contract.Factory(&_V3SwapRouter02.CallOpts) +} + +// Factory is a free data retrieval call binding the contract method 0xc45a0155. +// +// Solidity: function factory() view returns(address) +func (_V3SwapRouter02 *V3SwapRouter02CallerSession) Factory() (common.Address, error) { + return _V3SwapRouter02.Contract.Factory(&_V3SwapRouter02.CallOpts) +} + +// FactoryV2 is a free data retrieval call binding the contract method 0x68e0d4e1. +// +// Solidity: function factoryV2() view returns(address) +func (_V3SwapRouter02 *V3SwapRouter02Caller) FactoryV2(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _V3SwapRouter02.contract.Call(opts, &out, "factoryV2") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// FactoryV2 is a free data retrieval call binding the contract method 0x68e0d4e1. +// +// Solidity: function factoryV2() view returns(address) +func (_V3SwapRouter02 *V3SwapRouter02Session) FactoryV2() (common.Address, error) { + return _V3SwapRouter02.Contract.FactoryV2(&_V3SwapRouter02.CallOpts) +} + +// FactoryV2 is a free data retrieval call binding the contract method 0x68e0d4e1. +// +// Solidity: function factoryV2() view returns(address) +func (_V3SwapRouter02 *V3SwapRouter02CallerSession) FactoryV2() (common.Address, error) { + return _V3SwapRouter02.Contract.FactoryV2(&_V3SwapRouter02.CallOpts) +} + +// PositionManager is a free data retrieval call binding the contract method 0x791b98bc. +// +// Solidity: function positionManager() view returns(address) +func (_V3SwapRouter02 *V3SwapRouter02Caller) PositionManager(opts *bind.CallOpts) (common.Address, error) { + var out []interface{} + err := _V3SwapRouter02.contract.Call(opts, &out, "positionManager") + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// PositionManager is a free data retrieval call binding the contract method 0x791b98bc. +// +// Solidity: function positionManager() view returns(address) +func (_V3SwapRouter02 *V3SwapRouter02Session) PositionManager() (common.Address, error) { + return _V3SwapRouter02.Contract.PositionManager(&_V3SwapRouter02.CallOpts) +} + +// PositionManager is a free data retrieval call binding the contract method 0x791b98bc. +// +// Solidity: function positionManager() view returns(address) +func (_V3SwapRouter02 *V3SwapRouter02CallerSession) PositionManager() (common.Address, error) { + return _V3SwapRouter02.Contract.PositionManager(&_V3SwapRouter02.CallOpts) +} + +// ApproveMax is a paid mutator transaction binding the contract method 0x571ac8b0. +// +// Solidity: function approveMax(address token) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) ApproveMax(opts *bind.TransactOpts, token common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "approveMax", token) +} + +// ApproveMax is a paid mutator transaction binding the contract method 0x571ac8b0. +// +// Solidity: function approveMax(address token) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) ApproveMax(token common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.ApproveMax(&_V3SwapRouter02.TransactOpts, token) +} + +// ApproveMax is a paid mutator transaction binding the contract method 0x571ac8b0. +// +// Solidity: function approveMax(address token) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) ApproveMax(token common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.ApproveMax(&_V3SwapRouter02.TransactOpts, token) +} + +// ApproveMaxMinusOne is a paid mutator transaction binding the contract method 0xcab372ce. +// +// Solidity: function approveMaxMinusOne(address token) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) ApproveMaxMinusOne(opts *bind.TransactOpts, token common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "approveMaxMinusOne", token) +} + +// ApproveMaxMinusOne is a paid mutator transaction binding the contract method 0xcab372ce. +// +// Solidity: function approveMaxMinusOne(address token) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) ApproveMaxMinusOne(token common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.ApproveMaxMinusOne(&_V3SwapRouter02.TransactOpts, token) +} + +// ApproveMaxMinusOne is a paid mutator transaction binding the contract method 0xcab372ce. +// +// Solidity: function approveMaxMinusOne(address token) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) ApproveMaxMinusOne(token common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.ApproveMaxMinusOne(&_V3SwapRouter02.TransactOpts, token) +} + +// ApproveZeroThenMax is a paid mutator transaction binding the contract method 0x639d71a9. +// +// Solidity: function approveZeroThenMax(address token) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) ApproveZeroThenMax(opts *bind.TransactOpts, token common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "approveZeroThenMax", token) +} + +// ApproveZeroThenMax is a paid mutator transaction binding the contract method 0x639d71a9. +// +// Solidity: function approveZeroThenMax(address token) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) ApproveZeroThenMax(token common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.ApproveZeroThenMax(&_V3SwapRouter02.TransactOpts, token) +} + +// ApproveZeroThenMax is a paid mutator transaction binding the contract method 0x639d71a9. +// +// Solidity: function approveZeroThenMax(address token) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) ApproveZeroThenMax(token common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.ApproveZeroThenMax(&_V3SwapRouter02.TransactOpts, token) +} + +// ApproveZeroThenMaxMinusOne is a paid mutator transaction binding the contract method 0xab3fdd50. +// +// Solidity: function approveZeroThenMaxMinusOne(address token) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) ApproveZeroThenMaxMinusOne(opts *bind.TransactOpts, token common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "approveZeroThenMaxMinusOne", token) +} + +// ApproveZeroThenMaxMinusOne is a paid mutator transaction binding the contract method 0xab3fdd50. +// +// Solidity: function approveZeroThenMaxMinusOne(address token) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) ApproveZeroThenMaxMinusOne(token common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.ApproveZeroThenMaxMinusOne(&_V3SwapRouter02.TransactOpts, token) +} + +// ApproveZeroThenMaxMinusOne is a paid mutator transaction binding the contract method 0xab3fdd50. +// +// Solidity: function approveZeroThenMaxMinusOne(address token) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) ApproveZeroThenMaxMinusOne(token common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.ApproveZeroThenMaxMinusOne(&_V3SwapRouter02.TransactOpts, token) +} + +// CallPositionManager is a paid mutator transaction binding the contract method 0xb3a2af13. +// +// Solidity: function callPositionManager(bytes data) payable returns(bytes result) +func (_V3SwapRouter02 *V3SwapRouter02Transactor) CallPositionManager(opts *bind.TransactOpts, data []byte) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "callPositionManager", data) +} + +// CallPositionManager is a paid mutator transaction binding the contract method 0xb3a2af13. +// +// Solidity: function callPositionManager(bytes data) payable returns(bytes result) +func (_V3SwapRouter02 *V3SwapRouter02Session) CallPositionManager(data []byte) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.CallPositionManager(&_V3SwapRouter02.TransactOpts, data) +} + +// CallPositionManager is a paid mutator transaction binding the contract method 0xb3a2af13. +// +// Solidity: function callPositionManager(bytes data) payable returns(bytes result) +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) CallPositionManager(data []byte) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.CallPositionManager(&_V3SwapRouter02.TransactOpts, data) +} + +// ExactInput is a paid mutator transaction binding the contract method 0xb858183f. +// +// Solidity: function exactInput((bytes,address,uint256,uint256) params) payable returns(uint256 amountOut) +func (_V3SwapRouter02 *V3SwapRouter02Transactor) ExactInput(opts *bind.TransactOpts, params IV3SwapRouterExactInputParams) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "exactInput", params) +} + +// ExactInput is a paid mutator transaction binding the contract method 0xb858183f. +// +// Solidity: function exactInput((bytes,address,uint256,uint256) params) payable returns(uint256 amountOut) +func (_V3SwapRouter02 *V3SwapRouter02Session) ExactInput(params IV3SwapRouterExactInputParams) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.ExactInput(&_V3SwapRouter02.TransactOpts, params) +} + +// ExactInput is a paid mutator transaction binding the contract method 0xb858183f. +// +// Solidity: function exactInput((bytes,address,uint256,uint256) params) payable returns(uint256 amountOut) +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) ExactInput(params IV3SwapRouterExactInputParams) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.ExactInput(&_V3SwapRouter02.TransactOpts, params) +} + +// ExactInputSingle is a paid mutator transaction binding the contract method 0x04e45aaf. +// +// Solidity: function exactInputSingle((address,address,uint24,address,uint256,uint256,uint160) params) payable returns(uint256 amountOut) +func (_V3SwapRouter02 *V3SwapRouter02Transactor) ExactInputSingle(opts *bind.TransactOpts, params IV3SwapRouterExactInputSingleParams) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "exactInputSingle", params) +} + +// ExactInputSingle is a paid mutator transaction binding the contract method 0x04e45aaf. +// +// Solidity: function exactInputSingle((address,address,uint24,address,uint256,uint256,uint160) params) payable returns(uint256 amountOut) +func (_V3SwapRouter02 *V3SwapRouter02Session) ExactInputSingle(params IV3SwapRouterExactInputSingleParams) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.ExactInputSingle(&_V3SwapRouter02.TransactOpts, params) +} + +// ExactInputSingle is a paid mutator transaction binding the contract method 0x04e45aaf. +// +// Solidity: function exactInputSingle((address,address,uint24,address,uint256,uint256,uint160) params) payable returns(uint256 amountOut) +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) ExactInputSingle(params IV3SwapRouterExactInputSingleParams) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.ExactInputSingle(&_V3SwapRouter02.TransactOpts, params) +} + +// ExactOutput is a paid mutator transaction binding the contract method 0x09b81346. +// +// Solidity: function exactOutput((bytes,address,uint256,uint256) params) payable returns(uint256 amountIn) +func (_V3SwapRouter02 *V3SwapRouter02Transactor) ExactOutput(opts *bind.TransactOpts, params IV3SwapRouterExactOutputParams) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "exactOutput", params) +} + +// ExactOutput is a paid mutator transaction binding the contract method 0x09b81346. +// +// Solidity: function exactOutput((bytes,address,uint256,uint256) params) payable returns(uint256 amountIn) +func (_V3SwapRouter02 *V3SwapRouter02Session) ExactOutput(params IV3SwapRouterExactOutputParams) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.ExactOutput(&_V3SwapRouter02.TransactOpts, params) +} + +// ExactOutput is a paid mutator transaction binding the contract method 0x09b81346. +// +// Solidity: function exactOutput((bytes,address,uint256,uint256) params) payable returns(uint256 amountIn) +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) ExactOutput(params IV3SwapRouterExactOutputParams) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.ExactOutput(&_V3SwapRouter02.TransactOpts, params) +} + +// ExactOutputSingle is a paid mutator transaction binding the contract method 0x5023b4df. +// +// Solidity: function exactOutputSingle((address,address,uint24,address,uint256,uint256,uint160) params) payable returns(uint256 amountIn) +func (_V3SwapRouter02 *V3SwapRouter02Transactor) ExactOutputSingle(opts *bind.TransactOpts, params IV3SwapRouterExactOutputSingleParams) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "exactOutputSingle", params) +} + +// ExactOutputSingle is a paid mutator transaction binding the contract method 0x5023b4df. +// +// Solidity: function exactOutputSingle((address,address,uint24,address,uint256,uint256,uint160) params) payable returns(uint256 amountIn) +func (_V3SwapRouter02 *V3SwapRouter02Session) ExactOutputSingle(params IV3SwapRouterExactOutputSingleParams) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.ExactOutputSingle(&_V3SwapRouter02.TransactOpts, params) +} + +// ExactOutputSingle is a paid mutator transaction binding the contract method 0x5023b4df. +// +// Solidity: function exactOutputSingle((address,address,uint24,address,uint256,uint256,uint160) params) payable returns(uint256 amountIn) +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) ExactOutputSingle(params IV3SwapRouterExactOutputSingleParams) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.ExactOutputSingle(&_V3SwapRouter02.TransactOpts, params) +} + +// GetApprovalType is a paid mutator transaction binding the contract method 0xdee00f35. +// +// Solidity: function getApprovalType(address token, uint256 amount) returns(uint8) +func (_V3SwapRouter02 *V3SwapRouter02Transactor) GetApprovalType(opts *bind.TransactOpts, token common.Address, amount *big.Int) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "getApprovalType", token, amount) +} + +// GetApprovalType is a paid mutator transaction binding the contract method 0xdee00f35. +// +// Solidity: function getApprovalType(address token, uint256 amount) returns(uint8) +func (_V3SwapRouter02 *V3SwapRouter02Session) GetApprovalType(token common.Address, amount *big.Int) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.GetApprovalType(&_V3SwapRouter02.TransactOpts, token, amount) +} + +// GetApprovalType is a paid mutator transaction binding the contract method 0xdee00f35. +// +// Solidity: function getApprovalType(address token, uint256 amount) returns(uint8) +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) GetApprovalType(token common.Address, amount *big.Int) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.GetApprovalType(&_V3SwapRouter02.TransactOpts, token, amount) +} + +// IncreaseLiquidity is a paid mutator transaction binding the contract method 0xf100b205. +// +// Solidity: function increaseLiquidity((address,address,uint256,uint256,uint256) params) payable returns(bytes result) +func (_V3SwapRouter02 *V3SwapRouter02Transactor) IncreaseLiquidity(opts *bind.TransactOpts, params IApproveAndCallIncreaseLiquidityParams) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "increaseLiquidity", params) +} + +// IncreaseLiquidity is a paid mutator transaction binding the contract method 0xf100b205. +// +// Solidity: function increaseLiquidity((address,address,uint256,uint256,uint256) params) payable returns(bytes result) +func (_V3SwapRouter02 *V3SwapRouter02Session) IncreaseLiquidity(params IApproveAndCallIncreaseLiquidityParams) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.IncreaseLiquidity(&_V3SwapRouter02.TransactOpts, params) +} + +// IncreaseLiquidity is a paid mutator transaction binding the contract method 0xf100b205. +// +// Solidity: function increaseLiquidity((address,address,uint256,uint256,uint256) params) payable returns(bytes result) +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) IncreaseLiquidity(params IApproveAndCallIncreaseLiquidityParams) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.IncreaseLiquidity(&_V3SwapRouter02.TransactOpts, params) +} + +// Mint is a paid mutator transaction binding the contract method 0x11ed56c9. +// +// Solidity: function mint((address,address,uint24,int24,int24,uint256,uint256,address) params) payable returns(bytes result) +func (_V3SwapRouter02 *V3SwapRouter02Transactor) Mint(opts *bind.TransactOpts, params IApproveAndCallMintParams) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "mint", params) +} + +// Mint is a paid mutator transaction binding the contract method 0x11ed56c9. +// +// Solidity: function mint((address,address,uint24,int24,int24,uint256,uint256,address) params) payable returns(bytes result) +func (_V3SwapRouter02 *V3SwapRouter02Session) Mint(params IApproveAndCallMintParams) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.Mint(&_V3SwapRouter02.TransactOpts, params) +} + +// Mint is a paid mutator transaction binding the contract method 0x11ed56c9. +// +// Solidity: function mint((address,address,uint24,int24,int24,uint256,uint256,address) params) payable returns(bytes result) +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) Mint(params IApproveAndCallMintParams) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.Mint(&_V3SwapRouter02.TransactOpts, params) +} + +// Multicall is a paid mutator transaction binding the contract method 0x1f0464d1. +// +// Solidity: function multicall(bytes32 previousBlockhash, bytes[] data) payable returns(bytes[]) +func (_V3SwapRouter02 *V3SwapRouter02Transactor) Multicall(opts *bind.TransactOpts, previousBlockhash [32]byte, data [][]byte) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "multicall", previousBlockhash, data) +} + +// Multicall is a paid mutator transaction binding the contract method 0x1f0464d1. +// +// Solidity: function multicall(bytes32 previousBlockhash, bytes[] data) payable returns(bytes[]) +func (_V3SwapRouter02 *V3SwapRouter02Session) Multicall(previousBlockhash [32]byte, data [][]byte) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.Multicall(&_V3SwapRouter02.TransactOpts, previousBlockhash, data) +} + +// Multicall is a paid mutator transaction binding the contract method 0x1f0464d1. +// +// Solidity: function multicall(bytes32 previousBlockhash, bytes[] data) payable returns(bytes[]) +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) Multicall(previousBlockhash [32]byte, data [][]byte) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.Multicall(&_V3SwapRouter02.TransactOpts, previousBlockhash, data) +} + +// Multicall0 is a paid mutator transaction binding the contract method 0x5ae401dc. +// +// Solidity: function multicall(uint256 deadline, bytes[] data) payable returns(bytes[]) +func (_V3SwapRouter02 *V3SwapRouter02Transactor) Multicall0(opts *bind.TransactOpts, deadline *big.Int, data [][]byte) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "multicall0", deadline, data) +} + +// Multicall0 is a paid mutator transaction binding the contract method 0x5ae401dc. +// +// Solidity: function multicall(uint256 deadline, bytes[] data) payable returns(bytes[]) +func (_V3SwapRouter02 *V3SwapRouter02Session) Multicall0(deadline *big.Int, data [][]byte) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.Multicall0(&_V3SwapRouter02.TransactOpts, deadline, data) +} + +// Multicall0 is a paid mutator transaction binding the contract method 0x5ae401dc. +// +// Solidity: function multicall(uint256 deadline, bytes[] data) payable returns(bytes[]) +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) Multicall0(deadline *big.Int, data [][]byte) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.Multicall0(&_V3SwapRouter02.TransactOpts, deadline, data) +} + +// Multicall1 is a paid mutator transaction binding the contract method 0xac9650d8. +// +// Solidity: function multicall(bytes[] data) payable returns(bytes[] results) +func (_V3SwapRouter02 *V3SwapRouter02Transactor) Multicall1(opts *bind.TransactOpts, data [][]byte) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "multicall1", data) +} + +// Multicall1 is a paid mutator transaction binding the contract method 0xac9650d8. +// +// Solidity: function multicall(bytes[] data) payable returns(bytes[] results) +func (_V3SwapRouter02 *V3SwapRouter02Session) Multicall1(data [][]byte) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.Multicall1(&_V3SwapRouter02.TransactOpts, data) +} + +// Multicall1 is a paid mutator transaction binding the contract method 0xac9650d8. +// +// Solidity: function multicall(bytes[] data) payable returns(bytes[] results) +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) Multicall1(data [][]byte) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.Multicall1(&_V3SwapRouter02.TransactOpts, data) +} + +// Pull is a paid mutator transaction binding the contract method 0xf2d5d56b. +// +// Solidity: function pull(address token, uint256 value) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) Pull(opts *bind.TransactOpts, token common.Address, value *big.Int) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "pull", token, value) +} + +// Pull is a paid mutator transaction binding the contract method 0xf2d5d56b. +// +// Solidity: function pull(address token, uint256 value) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) Pull(token common.Address, value *big.Int) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.Pull(&_V3SwapRouter02.TransactOpts, token, value) +} + +// Pull is a paid mutator transaction binding the contract method 0xf2d5d56b. +// +// Solidity: function pull(address token, uint256 value) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) Pull(token common.Address, value *big.Int) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.Pull(&_V3SwapRouter02.TransactOpts, token, value) +} + +// RefundETH is a paid mutator transaction binding the contract method 0x12210e8a. +// +// Solidity: function refundETH() payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) RefundETH(opts *bind.TransactOpts) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "refundETH") +} + +// RefundETH is a paid mutator transaction binding the contract method 0x12210e8a. +// +// Solidity: function refundETH() payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) RefundETH() (*types.Transaction, error) { + return _V3SwapRouter02.Contract.RefundETH(&_V3SwapRouter02.TransactOpts) +} + +// RefundETH is a paid mutator transaction binding the contract method 0x12210e8a. +// +// Solidity: function refundETH() payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) RefundETH() (*types.Transaction, error) { + return _V3SwapRouter02.Contract.RefundETH(&_V3SwapRouter02.TransactOpts) +} + +// SelfPermit is a paid mutator transaction binding the contract method 0xf3995c67. +// +// Solidity: function selfPermit(address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) SelfPermit(opts *bind.TransactOpts, token common.Address, value *big.Int, deadline *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "selfPermit", token, value, deadline, v, r, s) +} + +// SelfPermit is a paid mutator transaction binding the contract method 0xf3995c67. +// +// Solidity: function selfPermit(address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) SelfPermit(token common.Address, value *big.Int, deadline *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SelfPermit(&_V3SwapRouter02.TransactOpts, token, value, deadline, v, r, s) +} + +// SelfPermit is a paid mutator transaction binding the contract method 0xf3995c67. +// +// Solidity: function selfPermit(address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) SelfPermit(token common.Address, value *big.Int, deadline *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SelfPermit(&_V3SwapRouter02.TransactOpts, token, value, deadline, v, r, s) +} + +// SelfPermitAllowed is a paid mutator transaction binding the contract method 0x4659a494. +// +// Solidity: function selfPermitAllowed(address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) SelfPermitAllowed(opts *bind.TransactOpts, token common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "selfPermitAllowed", token, nonce, expiry, v, r, s) +} + +// SelfPermitAllowed is a paid mutator transaction binding the contract method 0x4659a494. +// +// Solidity: function selfPermitAllowed(address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) SelfPermitAllowed(token common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SelfPermitAllowed(&_V3SwapRouter02.TransactOpts, token, nonce, expiry, v, r, s) +} + +// SelfPermitAllowed is a paid mutator transaction binding the contract method 0x4659a494. +// +// Solidity: function selfPermitAllowed(address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) SelfPermitAllowed(token common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SelfPermitAllowed(&_V3SwapRouter02.TransactOpts, token, nonce, expiry, v, r, s) +} + +// SelfPermitAllowedIfNecessary is a paid mutator transaction binding the contract method 0xa4a78f0c. +// +// Solidity: function selfPermitAllowedIfNecessary(address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) SelfPermitAllowedIfNecessary(opts *bind.TransactOpts, token common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "selfPermitAllowedIfNecessary", token, nonce, expiry, v, r, s) +} + +// SelfPermitAllowedIfNecessary is a paid mutator transaction binding the contract method 0xa4a78f0c. +// +// Solidity: function selfPermitAllowedIfNecessary(address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) SelfPermitAllowedIfNecessary(token common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SelfPermitAllowedIfNecessary(&_V3SwapRouter02.TransactOpts, token, nonce, expiry, v, r, s) +} + +// SelfPermitAllowedIfNecessary is a paid mutator transaction binding the contract method 0xa4a78f0c. +// +// Solidity: function selfPermitAllowedIfNecessary(address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) SelfPermitAllowedIfNecessary(token common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SelfPermitAllowedIfNecessary(&_V3SwapRouter02.TransactOpts, token, nonce, expiry, v, r, s) +} + +// SelfPermitIfNecessary is a paid mutator transaction binding the contract method 0xc2e3140a. +// +// Solidity: function selfPermitIfNecessary(address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) SelfPermitIfNecessary(opts *bind.TransactOpts, token common.Address, value *big.Int, deadline *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "selfPermitIfNecessary", token, value, deadline, v, r, s) +} + +// SelfPermitIfNecessary is a paid mutator transaction binding the contract method 0xc2e3140a. +// +// Solidity: function selfPermitIfNecessary(address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) SelfPermitIfNecessary(token common.Address, value *big.Int, deadline *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SelfPermitIfNecessary(&_V3SwapRouter02.TransactOpts, token, value, deadline, v, r, s) +} + +// SelfPermitIfNecessary is a paid mutator transaction binding the contract method 0xc2e3140a. +// +// Solidity: function selfPermitIfNecessary(address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) SelfPermitIfNecessary(token common.Address, value *big.Int, deadline *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SelfPermitIfNecessary(&_V3SwapRouter02.TransactOpts, token, value, deadline, v, r, s) +} + +// SwapExactTokensForTokens is a paid mutator transaction binding the contract method 0x472b43f3. +// +// Solidity: function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to) payable returns(uint256 amountOut) +func (_V3SwapRouter02 *V3SwapRouter02Transactor) SwapExactTokensForTokens(opts *bind.TransactOpts, amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "swapExactTokensForTokens", amountIn, amountOutMin, path, to) +} + +// SwapExactTokensForTokens is a paid mutator transaction binding the contract method 0x472b43f3. +// +// Solidity: function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to) payable returns(uint256 amountOut) +func (_V3SwapRouter02 *V3SwapRouter02Session) SwapExactTokensForTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SwapExactTokensForTokens(&_V3SwapRouter02.TransactOpts, amountIn, amountOutMin, path, to) +} + +// SwapExactTokensForTokens is a paid mutator transaction binding the contract method 0x472b43f3. +// +// Solidity: function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] path, address to) payable returns(uint256 amountOut) +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) SwapExactTokensForTokens(amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SwapExactTokensForTokens(&_V3SwapRouter02.TransactOpts, amountIn, amountOutMin, path, to) +} + +// SwapTokensForExactTokens is a paid mutator transaction binding the contract method 0x42712a67. +// +// Solidity: function swapTokensForExactTokens(uint256 amountOut, uint256 amountInMax, address[] path, address to) payable returns(uint256 amountIn) +func (_V3SwapRouter02 *V3SwapRouter02Transactor) SwapTokensForExactTokens(opts *bind.TransactOpts, amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "swapTokensForExactTokens", amountOut, amountInMax, path, to) +} + +// SwapTokensForExactTokens is a paid mutator transaction binding the contract method 0x42712a67. +// +// Solidity: function swapTokensForExactTokens(uint256 amountOut, uint256 amountInMax, address[] path, address to) payable returns(uint256 amountIn) +func (_V3SwapRouter02 *V3SwapRouter02Session) SwapTokensForExactTokens(amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SwapTokensForExactTokens(&_V3SwapRouter02.TransactOpts, amountOut, amountInMax, path, to) +} + +// SwapTokensForExactTokens is a paid mutator transaction binding the contract method 0x42712a67. +// +// Solidity: function swapTokensForExactTokens(uint256 amountOut, uint256 amountInMax, address[] path, address to) payable returns(uint256 amountIn) +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) SwapTokensForExactTokens(amountOut *big.Int, amountInMax *big.Int, path []common.Address, to common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SwapTokensForExactTokens(&_V3SwapRouter02.TransactOpts, amountOut, amountInMax, path, to) +} + +// SweepToken is a paid mutator transaction binding the contract method 0xdf2ab5bb. +// +// Solidity: function sweepToken(address token, uint256 amountMinimum, address recipient) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) SweepToken(opts *bind.TransactOpts, token common.Address, amountMinimum *big.Int, recipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "sweepToken", token, amountMinimum, recipient) +} + +// SweepToken is a paid mutator transaction binding the contract method 0xdf2ab5bb. +// +// Solidity: function sweepToken(address token, uint256 amountMinimum, address recipient) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) SweepToken(token common.Address, amountMinimum *big.Int, recipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SweepToken(&_V3SwapRouter02.TransactOpts, token, amountMinimum, recipient) +} + +// SweepToken is a paid mutator transaction binding the contract method 0xdf2ab5bb. +// +// Solidity: function sweepToken(address token, uint256 amountMinimum, address recipient) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) SweepToken(token common.Address, amountMinimum *big.Int, recipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SweepToken(&_V3SwapRouter02.TransactOpts, token, amountMinimum, recipient) +} + +// SweepToken0 is a paid mutator transaction binding the contract method 0xe90a182f. +// +// Solidity: function sweepToken(address token, uint256 amountMinimum) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) SweepToken0(opts *bind.TransactOpts, token common.Address, amountMinimum *big.Int) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "sweepToken0", token, amountMinimum) +} + +// SweepToken0 is a paid mutator transaction binding the contract method 0xe90a182f. +// +// Solidity: function sweepToken(address token, uint256 amountMinimum) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) SweepToken0(token common.Address, amountMinimum *big.Int) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SweepToken0(&_V3SwapRouter02.TransactOpts, token, amountMinimum) +} + +// SweepToken0 is a paid mutator transaction binding the contract method 0xe90a182f. +// +// Solidity: function sweepToken(address token, uint256 amountMinimum) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) SweepToken0(token common.Address, amountMinimum *big.Int) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SweepToken0(&_V3SwapRouter02.TransactOpts, token, amountMinimum) +} + +// SweepTokenWithFee is a paid mutator transaction binding the contract method 0x3068c554. +// +// Solidity: function sweepTokenWithFee(address token, uint256 amountMinimum, uint256 feeBips, address feeRecipient) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) SweepTokenWithFee(opts *bind.TransactOpts, token common.Address, amountMinimum *big.Int, feeBips *big.Int, feeRecipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "sweepTokenWithFee", token, amountMinimum, feeBips, feeRecipient) +} + +// SweepTokenWithFee is a paid mutator transaction binding the contract method 0x3068c554. +// +// Solidity: function sweepTokenWithFee(address token, uint256 amountMinimum, uint256 feeBips, address feeRecipient) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) SweepTokenWithFee(token common.Address, amountMinimum *big.Int, feeBips *big.Int, feeRecipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SweepTokenWithFee(&_V3SwapRouter02.TransactOpts, token, amountMinimum, feeBips, feeRecipient) +} + +// SweepTokenWithFee is a paid mutator transaction binding the contract method 0x3068c554. +// +// Solidity: function sweepTokenWithFee(address token, uint256 amountMinimum, uint256 feeBips, address feeRecipient) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) SweepTokenWithFee(token common.Address, amountMinimum *big.Int, feeBips *big.Int, feeRecipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SweepTokenWithFee(&_V3SwapRouter02.TransactOpts, token, amountMinimum, feeBips, feeRecipient) +} + +// SweepTokenWithFee0 is a paid mutator transaction binding the contract method 0xe0e189a0. +// +// Solidity: function sweepTokenWithFee(address token, uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) SweepTokenWithFee0(opts *bind.TransactOpts, token common.Address, amountMinimum *big.Int, recipient common.Address, feeBips *big.Int, feeRecipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "sweepTokenWithFee0", token, amountMinimum, recipient, feeBips, feeRecipient) +} + +// SweepTokenWithFee0 is a paid mutator transaction binding the contract method 0xe0e189a0. +// +// Solidity: function sweepTokenWithFee(address token, uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) SweepTokenWithFee0(token common.Address, amountMinimum *big.Int, recipient common.Address, feeBips *big.Int, feeRecipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SweepTokenWithFee0(&_V3SwapRouter02.TransactOpts, token, amountMinimum, recipient, feeBips, feeRecipient) +} + +// SweepTokenWithFee0 is a paid mutator transaction binding the contract method 0xe0e189a0. +// +// Solidity: function sweepTokenWithFee(address token, uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) SweepTokenWithFee0(token common.Address, amountMinimum *big.Int, recipient common.Address, feeBips *big.Int, feeRecipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.SweepTokenWithFee0(&_V3SwapRouter02.TransactOpts, token, amountMinimum, recipient, feeBips, feeRecipient) +} + +// UniswapV3SwapCallback is a paid mutator transaction binding the contract method 0xfa461e33. +// +// Solidity: function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes _data) returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) UniswapV3SwapCallback(opts *bind.TransactOpts, amount0Delta *big.Int, amount1Delta *big.Int, _data []byte) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "uniswapV3SwapCallback", amount0Delta, amount1Delta, _data) +} + +// UniswapV3SwapCallback is a paid mutator transaction binding the contract method 0xfa461e33. +// +// Solidity: function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes _data) returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) UniswapV3SwapCallback(amount0Delta *big.Int, amount1Delta *big.Int, _data []byte) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.UniswapV3SwapCallback(&_V3SwapRouter02.TransactOpts, amount0Delta, amount1Delta, _data) +} + +// UniswapV3SwapCallback is a paid mutator transaction binding the contract method 0xfa461e33. +// +// Solidity: function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes _data) returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) UniswapV3SwapCallback(amount0Delta *big.Int, amount1Delta *big.Int, _data []byte) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.UniswapV3SwapCallback(&_V3SwapRouter02.TransactOpts, amount0Delta, amount1Delta, _data) +} + +// UnwrapWETH9 is a paid mutator transaction binding the contract method 0x49404b7c. +// +// Solidity: function unwrapWETH9(uint256 amountMinimum, address recipient) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) UnwrapWETH9(opts *bind.TransactOpts, amountMinimum *big.Int, recipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "unwrapWETH9", amountMinimum, recipient) +} + +// UnwrapWETH9 is a paid mutator transaction binding the contract method 0x49404b7c. +// +// Solidity: function unwrapWETH9(uint256 amountMinimum, address recipient) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) UnwrapWETH9(amountMinimum *big.Int, recipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.UnwrapWETH9(&_V3SwapRouter02.TransactOpts, amountMinimum, recipient) +} + +// UnwrapWETH9 is a paid mutator transaction binding the contract method 0x49404b7c. +// +// Solidity: function unwrapWETH9(uint256 amountMinimum, address recipient) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) UnwrapWETH9(amountMinimum *big.Int, recipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.UnwrapWETH9(&_V3SwapRouter02.TransactOpts, amountMinimum, recipient) +} + +// UnwrapWETH90 is a paid mutator transaction binding the contract method 0x49616997. +// +// Solidity: function unwrapWETH9(uint256 amountMinimum) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) UnwrapWETH90(opts *bind.TransactOpts, amountMinimum *big.Int) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "unwrapWETH90", amountMinimum) +} + +// UnwrapWETH90 is a paid mutator transaction binding the contract method 0x49616997. +// +// Solidity: function unwrapWETH9(uint256 amountMinimum) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) UnwrapWETH90(amountMinimum *big.Int) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.UnwrapWETH90(&_V3SwapRouter02.TransactOpts, amountMinimum) +} + +// UnwrapWETH90 is a paid mutator transaction binding the contract method 0x49616997. +// +// Solidity: function unwrapWETH9(uint256 amountMinimum) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) UnwrapWETH90(amountMinimum *big.Int) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.UnwrapWETH90(&_V3SwapRouter02.TransactOpts, amountMinimum) +} + +// UnwrapWETH9WithFee is a paid mutator transaction binding the contract method 0x9b2c0a37. +// +// Solidity: function unwrapWETH9WithFee(uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) UnwrapWETH9WithFee(opts *bind.TransactOpts, amountMinimum *big.Int, recipient common.Address, feeBips *big.Int, feeRecipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "unwrapWETH9WithFee", amountMinimum, recipient, feeBips, feeRecipient) +} + +// UnwrapWETH9WithFee is a paid mutator transaction binding the contract method 0x9b2c0a37. +// +// Solidity: function unwrapWETH9WithFee(uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) UnwrapWETH9WithFee(amountMinimum *big.Int, recipient common.Address, feeBips *big.Int, feeRecipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.UnwrapWETH9WithFee(&_V3SwapRouter02.TransactOpts, amountMinimum, recipient, feeBips, feeRecipient) +} + +// UnwrapWETH9WithFee is a paid mutator transaction binding the contract method 0x9b2c0a37. +// +// Solidity: function unwrapWETH9WithFee(uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) UnwrapWETH9WithFee(amountMinimum *big.Int, recipient common.Address, feeBips *big.Int, feeRecipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.UnwrapWETH9WithFee(&_V3SwapRouter02.TransactOpts, amountMinimum, recipient, feeBips, feeRecipient) +} + +// UnwrapWETH9WithFee0 is a paid mutator transaction binding the contract method 0xd4ef38de. +// +// Solidity: function unwrapWETH9WithFee(uint256 amountMinimum, uint256 feeBips, address feeRecipient) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) UnwrapWETH9WithFee0(opts *bind.TransactOpts, amountMinimum *big.Int, feeBips *big.Int, feeRecipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "unwrapWETH9WithFee0", amountMinimum, feeBips, feeRecipient) +} + +// UnwrapWETH9WithFee0 is a paid mutator transaction binding the contract method 0xd4ef38de. +// +// Solidity: function unwrapWETH9WithFee(uint256 amountMinimum, uint256 feeBips, address feeRecipient) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) UnwrapWETH9WithFee0(amountMinimum *big.Int, feeBips *big.Int, feeRecipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.UnwrapWETH9WithFee0(&_V3SwapRouter02.TransactOpts, amountMinimum, feeBips, feeRecipient) +} + +// UnwrapWETH9WithFee0 is a paid mutator transaction binding the contract method 0xd4ef38de. +// +// Solidity: function unwrapWETH9WithFee(uint256 amountMinimum, uint256 feeBips, address feeRecipient) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) UnwrapWETH9WithFee0(amountMinimum *big.Int, feeBips *big.Int, feeRecipient common.Address) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.UnwrapWETH9WithFee0(&_V3SwapRouter02.TransactOpts, amountMinimum, feeBips, feeRecipient) +} + +// WrapETH is a paid mutator transaction binding the contract method 0x1c58db4f. +// +// Solidity: function wrapETH(uint256 value) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) WrapETH(opts *bind.TransactOpts, value *big.Int) (*types.Transaction, error) { + return _V3SwapRouter02.contract.Transact(opts, "wrapETH", value) +} + +// WrapETH is a paid mutator transaction binding the contract method 0x1c58db4f. +// +// Solidity: function wrapETH(uint256 value) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) WrapETH(value *big.Int) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.WrapETH(&_V3SwapRouter02.TransactOpts, value) +} + +// WrapETH is a paid mutator transaction binding the contract method 0x1c58db4f. +// +// Solidity: function wrapETH(uint256 value) payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) WrapETH(value *big.Int) (*types.Transaction, error) { + return _V3SwapRouter02.Contract.WrapETH(&_V3SwapRouter02.TransactOpts, value) +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Transactor) Receive(opts *bind.TransactOpts) (*types.Transaction, error) { + return _V3SwapRouter02.contract.RawTransact(opts, nil) // calldata is disallowed for receive function +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_V3SwapRouter02 *V3SwapRouter02Session) Receive() (*types.Transaction, error) { + return _V3SwapRouter02.Contract.Receive(&_V3SwapRouter02.TransactOpts) +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_V3SwapRouter02 *V3SwapRouter02TransactorSession) Receive() (*types.Transaction, error) { + return _V3SwapRouter02.Contract.Receive(&_V3SwapRouter02.TransactOpts) +} diff --git a/utils/provider/dex/uniswap/abi/v3UniversalRouter/v3UniversalRouter.go b/utils/provider/dex/uniswap/abi/v3UniversalRouter/v3UniversalRouter.go new file mode 100644 index 0000000..685dcd3 --- /dev/null +++ b/utils/provider/dex/uniswap/abi/v3UniversalRouter/v3UniversalRouter.go @@ -0,0 +1,568 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package v3UniversalRouter + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription + _ = abi.ConvertType +) + +// RouterParameters is an auto generated low-level Go binding around an user-defined struct. +type RouterParameters struct { + Permit2 common.Address + Weth9 common.Address + SeaportV15 common.Address + SeaportV14 common.Address + OpenseaConduit common.Address + NftxZap common.Address + X2y2 common.Address + Foundation common.Address + Sudoswap common.Address + ElementMarket common.Address + Nft20Zap common.Address + Cryptopunks common.Address + LooksRareV2 common.Address + RouterRewardsDistributor common.Address + LooksRareRewardsDistributor common.Address + LooksRareToken common.Address + V2Factory common.Address + V3Factory common.Address + PairInitCodeHash [32]byte + PoolInitCodeHash [32]byte +} + +// V3UniversalRouterMetaData contains all meta data concerning the V3UniversalRouter contract. +var V3UniversalRouterMetaData = &bind.MetaData{ + ABI: "[{\"inputs\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"permit2\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"weth9\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"seaportV1_5\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"seaportV1_4\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"openseaConduit\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"nftxZap\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"x2y2\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"foundation\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"sudoswap\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"elementMarket\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"nft20Zap\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"cryptopunks\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"looksRareV2\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"routerRewardsDistributor\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"looksRareRewardsDistributor\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"looksRareToken\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"v2Factory\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"v3Factory\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"pairInitCodeHash\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"poolInitCodeHash\",\"type\":\"bytes32\"}],\"internalType\":\"structRouterParameters\",\"name\":\"params\",\"type\":\"tuple\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[],\"name\":\"BalanceTooLow\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"BuyPunkFailed\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"ContractLocked\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"ETHNotAccepted\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"commandIndex\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"message\",\"type\":\"bytes\"}],\"name\":\"ExecutionFailed\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"FromAddressIsNotOwner\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InsufficientETH\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InsufficientToken\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidBips\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"commandType\",\"type\":\"uint256\"}],\"name\":\"InvalidCommandType\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidOwnerERC1155\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidOwnerERC721\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidPath\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidReserves\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"InvalidSpender\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"LengthMismatch\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"SliceOutOfBounds\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"TransactionDeadlinePassed\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"UnableToClaim\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"UnsafeCast\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"V2InvalidPath\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"V2TooLittleReceived\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"V2TooMuchRequested\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"V3InvalidAmountOut\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"V3InvalidCaller\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"V3InvalidSwap\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"V3TooLittleReceived\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"V3TooMuchRequested\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"RewardsSent\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"looksRareClaim\",\"type\":\"bytes\"}],\"name\":\"collectRewards\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"commands\",\"type\":\"bytes\"},{\"internalType\":\"bytes[]\",\"name\":\"inputs\",\"type\":\"bytes[]\"}],\"name\":\"execute\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"commands\",\"type\":\"bytes\"},{\"internalType\":\"bytes[]\",\"name\":\"inputs\",\"type\":\"bytes[]\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"}],\"name\":\"execute\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"uint256[]\",\"name\":\"\",\"type\":\"uint256[]\"},{\"internalType\":\"uint256[]\",\"name\":\"\",\"type\":\"uint256[]\"},{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"onERC1155BatchReceived\",\"outputs\":[{\"internalType\":\"bytes4\",\"name\":\"\",\"type\":\"bytes4\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"onERC1155Received\",\"outputs\":[{\"internalType\":\"bytes4\",\"name\":\"\",\"type\":\"bytes4\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"onERC721Received\",\"outputs\":[{\"internalType\":\"bytes4\",\"name\":\"\",\"type\":\"bytes4\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes4\",\"name\":\"interfaceId\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"int256\",\"name\":\"amount0Delta\",\"type\":\"int256\"},{\"internalType\":\"int256\",\"name\":\"amount1Delta\",\"type\":\"int256\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"uniswapV3SwapCallback\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}]", +} + +// V3UniversalRouterABI is the input ABI used to generate the binding from. +// Deprecated: Use V3UniversalRouterMetaData.ABI instead. +var V3UniversalRouterABI = V3UniversalRouterMetaData.ABI + +// V3UniversalRouter is an auto generated Go binding around an Ethereum contract. +type V3UniversalRouter struct { + V3UniversalRouterCaller // Read-only binding to the contract + V3UniversalRouterTransactor // Write-only binding to the contract + V3UniversalRouterFilterer // Log filterer for contract events +} + +// V3UniversalRouterCaller is an auto generated read-only Go binding around an Ethereum contract. +type V3UniversalRouterCaller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// V3UniversalRouterTransactor is an auto generated write-only Go binding around an Ethereum contract. +type V3UniversalRouterTransactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// V3UniversalRouterFilterer is an auto generated log filtering Go binding around an Ethereum contract events. +type V3UniversalRouterFilterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// V3UniversalRouterSession is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type V3UniversalRouterSession struct { + Contract *V3UniversalRouter // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// V3UniversalRouterCallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type V3UniversalRouterCallerSession struct { + Contract *V3UniversalRouterCaller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// V3UniversalRouterTransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type V3UniversalRouterTransactorSession struct { + Contract *V3UniversalRouterTransactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// V3UniversalRouterRaw is an auto generated low-level Go binding around an Ethereum contract. +type V3UniversalRouterRaw struct { + Contract *V3UniversalRouter // Generic contract binding to access the raw methods on +} + +// V3UniversalRouterCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type V3UniversalRouterCallerRaw struct { + Contract *V3UniversalRouterCaller // Generic read-only contract binding to access the raw methods on +} + +// V3UniversalRouterTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type V3UniversalRouterTransactorRaw struct { + Contract *V3UniversalRouterTransactor // Generic write-only contract binding to access the raw methods on +} + +// NewV3UniversalRouter creates a new instance of V3UniversalRouter, bound to a specific deployed contract. +func NewV3UniversalRouter(address common.Address, backend bind.ContractBackend) (*V3UniversalRouter, error) { + contract, err := bindV3UniversalRouter(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &V3UniversalRouter{V3UniversalRouterCaller: V3UniversalRouterCaller{contract: contract}, V3UniversalRouterTransactor: V3UniversalRouterTransactor{contract: contract}, V3UniversalRouterFilterer: V3UniversalRouterFilterer{contract: contract}}, nil +} + +// NewV3UniversalRouterCaller creates a new read-only instance of V3UniversalRouter, bound to a specific deployed contract. +func NewV3UniversalRouterCaller(address common.Address, caller bind.ContractCaller) (*V3UniversalRouterCaller, error) { + contract, err := bindV3UniversalRouter(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &V3UniversalRouterCaller{contract: contract}, nil +} + +// NewV3UniversalRouterTransactor creates a new write-only instance of V3UniversalRouter, bound to a specific deployed contract. +func NewV3UniversalRouterTransactor(address common.Address, transactor bind.ContractTransactor) (*V3UniversalRouterTransactor, error) { + contract, err := bindV3UniversalRouter(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &V3UniversalRouterTransactor{contract: contract}, nil +} + +// NewV3UniversalRouterFilterer creates a new log filterer instance of V3UniversalRouter, bound to a specific deployed contract. +func NewV3UniversalRouterFilterer(address common.Address, filterer bind.ContractFilterer) (*V3UniversalRouterFilterer, error) { + contract, err := bindV3UniversalRouter(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &V3UniversalRouterFilterer{contract: contract}, nil +} + +// bindV3UniversalRouter binds a generic wrapper to an already deployed contract. +func bindV3UniversalRouter(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := V3UniversalRouterMetaData.GetAbi() + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_V3UniversalRouter *V3UniversalRouterRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _V3UniversalRouter.Contract.V3UniversalRouterCaller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_V3UniversalRouter *V3UniversalRouterRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _V3UniversalRouter.Contract.V3UniversalRouterTransactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_V3UniversalRouter *V3UniversalRouterRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _V3UniversalRouter.Contract.V3UniversalRouterTransactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_V3UniversalRouter *V3UniversalRouterCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _V3UniversalRouter.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_V3UniversalRouter *V3UniversalRouterTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _V3UniversalRouter.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_V3UniversalRouter *V3UniversalRouterTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _V3UniversalRouter.Contract.contract.Transact(opts, method, params...) +} + +// OnERC1155BatchReceived is a free data retrieval call binding the contract method 0xbc197c81. +// +// Solidity: function onERC1155BatchReceived(address , address , uint256[] , uint256[] , bytes ) pure returns(bytes4) +func (_V3UniversalRouter *V3UniversalRouterCaller) OnERC1155BatchReceived(opts *bind.CallOpts, arg0 common.Address, arg1 common.Address, arg2 []*big.Int, arg3 []*big.Int, arg4 []byte) ([4]byte, error) { + var out []interface{} + err := _V3UniversalRouter.contract.Call(opts, &out, "onERC1155BatchReceived", arg0, arg1, arg2, arg3, arg4) + + if err != nil { + return *new([4]byte), err + } + + out0 := *abi.ConvertType(out[0], new([4]byte)).(*[4]byte) + + return out0, err + +} + +// OnERC1155BatchReceived is a free data retrieval call binding the contract method 0xbc197c81. +// +// Solidity: function onERC1155BatchReceived(address , address , uint256[] , uint256[] , bytes ) pure returns(bytes4) +func (_V3UniversalRouter *V3UniversalRouterSession) OnERC1155BatchReceived(arg0 common.Address, arg1 common.Address, arg2 []*big.Int, arg3 []*big.Int, arg4 []byte) ([4]byte, error) { + return _V3UniversalRouter.Contract.OnERC1155BatchReceived(&_V3UniversalRouter.CallOpts, arg0, arg1, arg2, arg3, arg4) +} + +// OnERC1155BatchReceived is a free data retrieval call binding the contract method 0xbc197c81. +// +// Solidity: function onERC1155BatchReceived(address , address , uint256[] , uint256[] , bytes ) pure returns(bytes4) +func (_V3UniversalRouter *V3UniversalRouterCallerSession) OnERC1155BatchReceived(arg0 common.Address, arg1 common.Address, arg2 []*big.Int, arg3 []*big.Int, arg4 []byte) ([4]byte, error) { + return _V3UniversalRouter.Contract.OnERC1155BatchReceived(&_V3UniversalRouter.CallOpts, arg0, arg1, arg2, arg3, arg4) +} + +// OnERC1155Received is a free data retrieval call binding the contract method 0xf23a6e61. +// +// Solidity: function onERC1155Received(address , address , uint256 , uint256 , bytes ) pure returns(bytes4) +func (_V3UniversalRouter *V3UniversalRouterCaller) OnERC1155Received(opts *bind.CallOpts, arg0 common.Address, arg1 common.Address, arg2 *big.Int, arg3 *big.Int, arg4 []byte) ([4]byte, error) { + var out []interface{} + err := _V3UniversalRouter.contract.Call(opts, &out, "onERC1155Received", arg0, arg1, arg2, arg3, arg4) + + if err != nil { + return *new([4]byte), err + } + + out0 := *abi.ConvertType(out[0], new([4]byte)).(*[4]byte) + + return out0, err + +} + +// OnERC1155Received is a free data retrieval call binding the contract method 0xf23a6e61. +// +// Solidity: function onERC1155Received(address , address , uint256 , uint256 , bytes ) pure returns(bytes4) +func (_V3UniversalRouter *V3UniversalRouterSession) OnERC1155Received(arg0 common.Address, arg1 common.Address, arg2 *big.Int, arg3 *big.Int, arg4 []byte) ([4]byte, error) { + return _V3UniversalRouter.Contract.OnERC1155Received(&_V3UniversalRouter.CallOpts, arg0, arg1, arg2, arg3, arg4) +} + +// OnERC1155Received is a free data retrieval call binding the contract method 0xf23a6e61. +// +// Solidity: function onERC1155Received(address , address , uint256 , uint256 , bytes ) pure returns(bytes4) +func (_V3UniversalRouter *V3UniversalRouterCallerSession) OnERC1155Received(arg0 common.Address, arg1 common.Address, arg2 *big.Int, arg3 *big.Int, arg4 []byte) ([4]byte, error) { + return _V3UniversalRouter.Contract.OnERC1155Received(&_V3UniversalRouter.CallOpts, arg0, arg1, arg2, arg3, arg4) +} + +// OnERC721Received is a free data retrieval call binding the contract method 0x150b7a02. +// +// Solidity: function onERC721Received(address , address , uint256 , bytes ) pure returns(bytes4) +func (_V3UniversalRouter *V3UniversalRouterCaller) OnERC721Received(opts *bind.CallOpts, arg0 common.Address, arg1 common.Address, arg2 *big.Int, arg3 []byte) ([4]byte, error) { + var out []interface{} + err := _V3UniversalRouter.contract.Call(opts, &out, "onERC721Received", arg0, arg1, arg2, arg3) + + if err != nil { + return *new([4]byte), err + } + + out0 := *abi.ConvertType(out[0], new([4]byte)).(*[4]byte) + + return out0, err + +} + +// OnERC721Received is a free data retrieval call binding the contract method 0x150b7a02. +// +// Solidity: function onERC721Received(address , address , uint256 , bytes ) pure returns(bytes4) +func (_V3UniversalRouter *V3UniversalRouterSession) OnERC721Received(arg0 common.Address, arg1 common.Address, arg2 *big.Int, arg3 []byte) ([4]byte, error) { + return _V3UniversalRouter.Contract.OnERC721Received(&_V3UniversalRouter.CallOpts, arg0, arg1, arg2, arg3) +} + +// OnERC721Received is a free data retrieval call binding the contract method 0x150b7a02. +// +// Solidity: function onERC721Received(address , address , uint256 , bytes ) pure returns(bytes4) +func (_V3UniversalRouter *V3UniversalRouterCallerSession) OnERC721Received(arg0 common.Address, arg1 common.Address, arg2 *big.Int, arg3 []byte) ([4]byte, error) { + return _V3UniversalRouter.Contract.OnERC721Received(&_V3UniversalRouter.CallOpts, arg0, arg1, arg2, arg3) +} + +// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. +// +// Solidity: function supportsInterface(bytes4 interfaceId) pure returns(bool) +func (_V3UniversalRouter *V3UniversalRouterCaller) SupportsInterface(opts *bind.CallOpts, interfaceId [4]byte) (bool, error) { + var out []interface{} + err := _V3UniversalRouter.contract.Call(opts, &out, "supportsInterface", interfaceId) + + if err != nil { + return *new(bool), err + } + + out0 := *abi.ConvertType(out[0], new(bool)).(*bool) + + return out0, err + +} + +// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. +// +// Solidity: function supportsInterface(bytes4 interfaceId) pure returns(bool) +func (_V3UniversalRouter *V3UniversalRouterSession) SupportsInterface(interfaceId [4]byte) (bool, error) { + return _V3UniversalRouter.Contract.SupportsInterface(&_V3UniversalRouter.CallOpts, interfaceId) +} + +// SupportsInterface is a free data retrieval call binding the contract method 0x01ffc9a7. +// +// Solidity: function supportsInterface(bytes4 interfaceId) pure returns(bool) +func (_V3UniversalRouter *V3UniversalRouterCallerSession) SupportsInterface(interfaceId [4]byte) (bool, error) { + return _V3UniversalRouter.Contract.SupportsInterface(&_V3UniversalRouter.CallOpts, interfaceId) +} + +// CollectRewards is a paid mutator transaction binding the contract method 0x709a1cc2. +// +// Solidity: function collectRewards(bytes looksRareClaim) returns() +func (_V3UniversalRouter *V3UniversalRouterTransactor) CollectRewards(opts *bind.TransactOpts, looksRareClaim []byte) (*types.Transaction, error) { + return _V3UniversalRouter.contract.Transact(opts, "collectRewards", looksRareClaim) +} + +// CollectRewards is a paid mutator transaction binding the contract method 0x709a1cc2. +// +// Solidity: function collectRewards(bytes looksRareClaim) returns() +func (_V3UniversalRouter *V3UniversalRouterSession) CollectRewards(looksRareClaim []byte) (*types.Transaction, error) { + return _V3UniversalRouter.Contract.CollectRewards(&_V3UniversalRouter.TransactOpts, looksRareClaim) +} + +// CollectRewards is a paid mutator transaction binding the contract method 0x709a1cc2. +// +// Solidity: function collectRewards(bytes looksRareClaim) returns() +func (_V3UniversalRouter *V3UniversalRouterTransactorSession) CollectRewards(looksRareClaim []byte) (*types.Transaction, error) { + return _V3UniversalRouter.Contract.CollectRewards(&_V3UniversalRouter.TransactOpts, looksRareClaim) +} + +// Execute is a paid mutator transaction binding the contract method 0x24856bc3. +// +// Solidity: function execute(bytes commands, bytes[] inputs) payable returns() +func (_V3UniversalRouter *V3UniversalRouterTransactor) Execute(opts *bind.TransactOpts, commands []byte, inputs [][]byte) (*types.Transaction, error) { + return _V3UniversalRouter.contract.Transact(opts, "execute", commands, inputs) +} + +// Execute is a paid mutator transaction binding the contract method 0x24856bc3. +// +// Solidity: function execute(bytes commands, bytes[] inputs) payable returns() +func (_V3UniversalRouter *V3UniversalRouterSession) Execute(commands []byte, inputs [][]byte) (*types.Transaction, error) { + return _V3UniversalRouter.Contract.Execute(&_V3UniversalRouter.TransactOpts, commands, inputs) +} + +// Execute is a paid mutator transaction binding the contract method 0x24856bc3. +// +// Solidity: function execute(bytes commands, bytes[] inputs) payable returns() +func (_V3UniversalRouter *V3UniversalRouterTransactorSession) Execute(commands []byte, inputs [][]byte) (*types.Transaction, error) { + return _V3UniversalRouter.Contract.Execute(&_V3UniversalRouter.TransactOpts, commands, inputs) +} + +// Execute0 is a paid mutator transaction binding the contract method 0x3593564c. +// +// Solidity: function execute(bytes commands, bytes[] inputs, uint256 deadline) payable returns() +func (_V3UniversalRouter *V3UniversalRouterTransactor) Execute0(opts *bind.TransactOpts, commands []byte, inputs [][]byte, deadline *big.Int) (*types.Transaction, error) { + return _V3UniversalRouter.contract.Transact(opts, "execute0", commands, inputs, deadline) +} + +// Execute0 is a paid mutator transaction binding the contract method 0x3593564c. +// +// Solidity: function execute(bytes commands, bytes[] inputs, uint256 deadline) payable returns() +func (_V3UniversalRouter *V3UniversalRouterSession) Execute0(commands []byte, inputs [][]byte, deadline *big.Int) (*types.Transaction, error) { + return _V3UniversalRouter.Contract.Execute0(&_V3UniversalRouter.TransactOpts, commands, inputs, deadline) +} + +// Execute0 is a paid mutator transaction binding the contract method 0x3593564c. +// +// Solidity: function execute(bytes commands, bytes[] inputs, uint256 deadline) payable returns() +func (_V3UniversalRouter *V3UniversalRouterTransactorSession) Execute0(commands []byte, inputs [][]byte, deadline *big.Int) (*types.Transaction, error) { + return _V3UniversalRouter.Contract.Execute0(&_V3UniversalRouter.TransactOpts, commands, inputs, deadline) +} + +// UniswapV3SwapCallback is a paid mutator transaction binding the contract method 0xfa461e33. +// +// Solidity: function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes data) returns() +func (_V3UniversalRouter *V3UniversalRouterTransactor) UniswapV3SwapCallback(opts *bind.TransactOpts, amount0Delta *big.Int, amount1Delta *big.Int, data []byte) (*types.Transaction, error) { + return _V3UniversalRouter.contract.Transact(opts, "uniswapV3SwapCallback", amount0Delta, amount1Delta, data) +} + +// UniswapV3SwapCallback is a paid mutator transaction binding the contract method 0xfa461e33. +// +// Solidity: function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes data) returns() +func (_V3UniversalRouter *V3UniversalRouterSession) UniswapV3SwapCallback(amount0Delta *big.Int, amount1Delta *big.Int, data []byte) (*types.Transaction, error) { + return _V3UniversalRouter.Contract.UniswapV3SwapCallback(&_V3UniversalRouter.TransactOpts, amount0Delta, amount1Delta, data) +} + +// UniswapV3SwapCallback is a paid mutator transaction binding the contract method 0xfa461e33. +// +// Solidity: function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes data) returns() +func (_V3UniversalRouter *V3UniversalRouterTransactorSession) UniswapV3SwapCallback(amount0Delta *big.Int, amount1Delta *big.Int, data []byte) (*types.Transaction, error) { + return _V3UniversalRouter.Contract.UniswapV3SwapCallback(&_V3UniversalRouter.TransactOpts, amount0Delta, amount1Delta, data) +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_V3UniversalRouter *V3UniversalRouterTransactor) Receive(opts *bind.TransactOpts) (*types.Transaction, error) { + return _V3UniversalRouter.contract.RawTransact(opts, nil) // calldata is disallowed for receive function +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_V3UniversalRouter *V3UniversalRouterSession) Receive() (*types.Transaction, error) { + return _V3UniversalRouter.Contract.Receive(&_V3UniversalRouter.TransactOpts) +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_V3UniversalRouter *V3UniversalRouterTransactorSession) Receive() (*types.Transaction, error) { + return _V3UniversalRouter.Contract.Receive(&_V3UniversalRouter.TransactOpts) +} + +// V3UniversalRouterRewardsSentIterator is returned from FilterRewardsSent and is used to iterate over the raw logs and unpacked data for RewardsSent events raised by the V3UniversalRouter contract. +type V3UniversalRouterRewardsSentIterator struct { + Event *V3UniversalRouterRewardsSent // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *V3UniversalRouterRewardsSentIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(V3UniversalRouterRewardsSent) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(V3UniversalRouterRewardsSent) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *V3UniversalRouterRewardsSentIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *V3UniversalRouterRewardsSentIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// V3UniversalRouterRewardsSent represents a RewardsSent event raised by the V3UniversalRouter contract. +type V3UniversalRouterRewardsSent struct { + Amount *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterRewardsSent is a free log retrieval operation binding the contract event 0x1e8f03f716bc104bf7d728131967a0c771e85ab54d09c1e2d6ed9e0bc4e2a16c. +// +// Solidity: event RewardsSent(uint256 amount) +func (_V3UniversalRouter *V3UniversalRouterFilterer) FilterRewardsSent(opts *bind.FilterOpts) (*V3UniversalRouterRewardsSentIterator, error) { + + logs, sub, err := _V3UniversalRouter.contract.FilterLogs(opts, "RewardsSent") + if err != nil { + return nil, err + } + return &V3UniversalRouterRewardsSentIterator{contract: _V3UniversalRouter.contract, event: "RewardsSent", logs: logs, sub: sub}, nil +} + +// WatchRewardsSent is a free log subscription operation binding the contract event 0x1e8f03f716bc104bf7d728131967a0c771e85ab54d09c1e2d6ed9e0bc4e2a16c. +// +// Solidity: event RewardsSent(uint256 amount) +func (_V3UniversalRouter *V3UniversalRouterFilterer) WatchRewardsSent(opts *bind.WatchOpts, sink chan<- *V3UniversalRouterRewardsSent) (event.Subscription, error) { + + logs, sub, err := _V3UniversalRouter.contract.WatchLogs(opts, "RewardsSent") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(V3UniversalRouterRewardsSent) + if err := _V3UniversalRouter.contract.UnpackLog(event, "RewardsSent", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseRewardsSent is a log parse operation binding the contract event 0x1e8f03f716bc104bf7d728131967a0c771e85ab54d09c1e2d6ed9e0bc4e2a16c. +// +// Solidity: event RewardsSent(uint256 amount) +func (_V3UniversalRouter *V3UniversalRouterFilterer) ParseRewardsSent(log types.Log) (*V3UniversalRouterRewardsSent, error) { + event := new(V3UniversalRouterRewardsSent) + if err := _V3UniversalRouter.contract.UnpackLog(event, "RewardsSent", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} diff --git a/utils/provider/dex/uniswap/configs/configs.go b/utils/provider/dex/uniswap/configs/configs.go new file mode 100644 index 0000000..e5bd8ba --- /dev/null +++ b/utils/provider/dex/uniswap/configs/configs.go @@ -0,0 +1,247 @@ +package configs + +import ( + "github.com/ethereum/go-ethereum/common" + "github.com/jinzhu/copier" + constant "omni-balance/utils/constant" +) + +var ( + // see https://docs.uniswap.org/contracts/v3/reference/deployments/ + WETH_RECIPIENT_ADDRESS = common.HexToAddress("0x0000000000000000000000000000000000000002") + UNWRAP_WETH_RECIPIENT_ADDRESS = common.HexToAddress("0x0000000000000000000000000000000000000001") + ethereumContractAddress = ContractAddress{ + ChainId: 1, + Factory: common.HexToAddress("0x1F98431c8aD98523631AE4a59f267346ea31F984"), + Multicall: common.HexToAddress("0x1F98415757620B543A52E61c46B32eB19261F984"), + Multicall2: common.HexToAddress("0x5BA1e12693Dc8F9c48aAD8770482f4739bEeD696"), + ProxyAdmin: common.HexToAddress("0xB753548F6E010e7e680BA186F9Ca1BdAB2E90cf2"), + TickLens: common.HexToAddress("0xbfd8137f7d1516D3ea5cA83523914859ec47F573"), + Quoter: common.HexToAddress("0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6"), + SwapRouter: common.HexToAddress("0xE592427A0AEce92De3Edee1F18E0157C05861564"), + NFTDescriptor: common.HexToAddress("0x42B24A95702b9986e82d421cC3568932790A48Ec"), + NonfungibleTokenPositionDescriptor: common.HexToAddress("0x91ae842A5Ffd8d12023116943e72A606179294f3"), + TransparentUpgradeableProxy: common.HexToAddress("0xEe6A57eC80ea46401049E92587E52f5Ec1c24785"), + NonfungiblePositionManager: common.HexToAddress("0xC36442b4a4522E871399CD717aBDD847Ab11FE88"), + V3Migrator: common.HexToAddress("0xA5644E29708357803b5A882D272c41cC0dF92B34"), + QuoterV2: common.HexToAddress("0x61fFE014bA17989E743c5F6cB21bF9697530B21e"), + SwapRouter02: common.HexToAddress("0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"), + Permit2: common.HexToAddress("0x000000000022D473030F116dDEE9F6B43aC78BA3"), + UniversalRouter: common.HexToAddress("0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD"), + v3StakerAddress: common.HexToAddress("0xe34139463bA50bD61336E0c446Bd8C0867c6fE65"), + } + + WNativeTokenAddress = map[string]common.Address{ + constant.Ethereum: common.HexToAddress("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"), + constant.Polygon: common.HexToAddress("0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270"), + constant.Bnb: common.HexToAddress("0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"), + constant.Avalanche: common.HexToAddress("0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7"), + constant.Arbitrum: common.HexToAddress("0x82af49447d8a07e3bd95bd0d56f35241523fbab1"), + constant.Optimism: common.HexToAddress("0x4200000000000000000000000000000000000006"), + constant.Base: common.HexToAddress("0x4200000000000000000000000000000000000006"), + constant.Celo: common.HexToAddress("0x471EcE3750Da237f93B8E339c536989b8978a438"), + constant.Blast: common.HexToAddress("0x4300000000000000000000000000000000000004"), + } + stableTokens = map[string]StableToken{ + constant.Ethereum: { + USDT: common.HexToAddress("0xdAC17F958D2ee523a2206206994597C13D831ec7"), + USDC: common.HexToAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"), + }, + constant.Polygon: { + USDT: common.HexToAddress("0xc2132D05D31c914a87C6611C10748AEb04B58e8F"), + USDC: common.HexToAddress("0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"), + }, + constant.Bnb: { + USDT: common.HexToAddress("0x524bC91Dc82d6b90EF29F76A3ECAaBAffFD490Bc"), + USDC: common.HexToAddress("0xc1f47175d96fe7c4cd5370552e5954f384e3c791"), + }, + constant.Avalanche: { + USDT: common.HexToAddress("0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7"), + USDC: common.HexToAddress("0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"), + }, + constant.Arbitrum: { + USDT: common.HexToAddress("0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"), + USDC: common.HexToAddress("0xaf88d065e77c8cc2239327c5edb3a432268e5831"), + }, + constant.Optimism: { + USDT: common.HexToAddress("0x94b008aa00579c1307b0ef2c499ad98a8ce58e58"), + USDC: common.HexToAddress("0x0b2c639c533813f4aa9d7837caf62653d097ff85"), + }, + constant.Base: { + USDC: common.HexToAddress("0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"), + }, + constant.Celo: { + USDC: common.HexToAddress("0xcebA9300f2b948710d2653dD7B07f33A8B32118C"), + }, + } +) + +var ( + V2Pool = "v2-pool" + V3Pool = "v3-pool" +) + +type StableToken struct { + USDT common.Address + USDC common.Address +} + +type ContractAddress struct { + ChainId int `json:"chain_id"` + Factory common.Address + Multicall common.Address + Multicall2 common.Address + ProxyAdmin common.Address + TickLens common.Address + Quoter common.Address + SwapRouter common.Address + NFTDescriptor common.Address + NonfungibleTokenPositionDescriptor common.Address + TransparentUpgradeableProxy common.Address + NonfungiblePositionManager common.Address + V3Migrator common.Address + QuoterV2 common.Address + SwapRouter02 common.Address + Permit2 common.Address + UniversalRouter common.Address + v3StakerAddress common.Address +} + +func (c ContractAddress) Clone() *ContractAddress { + var newContractAddress = new(ContractAddress) + _ = copier.Copy(newContractAddress, &c) + return newContractAddress +} + +func GetContractAddress(chainName string) ContractAddress { + var result = ethereumContractAddress.Clone() + result.ChainId = constant.GetChainId(chainName) + switch chainName { + case constant.Ethereum: + return ethereumContractAddress + case constant.Arbitrum: + result.Multicall = common.HexToAddress("0xadF885960B47eA2CD9B55E6DAc6B42b7Cb2806dB") + result.UniversalRouter = common.HexToAddress("0x5E325eDA8064b456f4781070C0738d849c824258") + result.Multicall2 = common.HexToAddress("") + return *result + case constant.Optimism: + result.Multicall2 = common.HexToAddress("") + result.V3Migrator = common.HexToAddress("") + result.UniversalRouter = common.HexToAddress("0xCb1355ff08Ab38bBCE60111F1bb2B784bE25D7e8") + return *result + case constant.Polygon: + result.Multicall2 = common.HexToAddress("") + result.UniversalRouter = common.HexToAddress("0xec7BE89e9d109e7e3Fec59c222CF297125FEFda2") + return *result + case constant.Base: + return ContractAddress{ + ChainId: constant.GetChainId(chainName), + Factory: common.HexToAddress("0x33128a8fC17869897dcE68Ed026d694621f6FDfD"), + Multicall: common.HexToAddress("0x091e99cb1C49331a94dD62755D168E941AbD0693"), + ProxyAdmin: common.HexToAddress("0x3334d83e224aF5ef9C2E7DDA7c7C98Efd9621fA9"), + TickLens: common.HexToAddress("0x0CdeE061c75D43c82520eD998C23ac2991c9ac6d"), + NFTDescriptor: common.HexToAddress("0xF9d1077fd35670d4ACbD27af82652a8d84577d9F"), + NonfungibleTokenPositionDescriptor: common.HexToAddress("0x4f225937EDc33EFD6109c4ceF7b560B2D6401009"), + TransparentUpgradeableProxy: common.HexToAddress("0x4615C383F85D0a2BbED973d83ccecf5CB7121463"), + NonfungiblePositionManager: common.HexToAddress("0x03a520b32C04BF3bEEf7BEb72E919cf822Ed34f1"), + V3Migrator: common.HexToAddress("0x23cF10b1ee3AdfCA73B0eF17C07F7577e7ACd2d7"), + QuoterV2: common.HexToAddress("0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a"), + SwapRouter02: common.HexToAddress("0x2626664c2603336E57B271c5C0b26F421741e481"), + Permit2: common.HexToAddress("0x000000000022D473030F116dDEE9F6B43aC78BA3"), + UniversalRouter: common.HexToAddress("0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD"), + v3StakerAddress: common.HexToAddress("0x42bE4D6527829FeFA1493e1fb9F3676d2425C3C1"), + } + case constant.Bnb: + return ContractAddress{ + ChainId: constant.GetChainId(chainName), + Factory: common.HexToAddress("0xdB1d10011AD0Ff90774D0C6Bb92e5C5c8b4461F7"), + Multicall: common.HexToAddress("0x963Df249eD09c358A4819E39d9Cd5736c3087184"), + ProxyAdmin: common.HexToAddress("0xC9A7f5b73E853664044ab31936D0E6583d8b1c79"), + TickLens: common.HexToAddress("0xD9270014D396281579760619CCf4c3af0501A47C"), + NFTDescriptor: common.HexToAddress("0x831d93E55AF23A2977E4DA892d5005f4F2995071"), + NonfungibleTokenPositionDescriptor: common.HexToAddress("0x0281E98322e4e8E53491D576Ee6A2BFCE644C55C"), + TransparentUpgradeableProxy: common.HexToAddress("0xAec98e489AE35F243eB63452f6ad233A6c97eE97"), + NonfungiblePositionManager: common.HexToAddress("0x7b8A01B39D58278b5DE7e48c8449c9f4F5170613"), + V3Migrator: common.HexToAddress("0x32681814957e0C13117ddc0c2aba232b5c9e760f"), + QuoterV2: common.HexToAddress("0x78D78E420Da98ad378D7799bE8f4AF69033EB077"), + SwapRouter02: common.HexToAddress("0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2"), + Permit2: common.HexToAddress("0x000000000022D473030F116dDEE9F6B43aC78BA3"), + UniversalRouter: common.HexToAddress("0x4Dae2f939ACf50408e13d58534Ff8c2776d45265"), + v3StakerAddress: common.HexToAddress("0x49B53C35AF9072fC71767577BF6380a88EE32C71"), + } + case constant.Avalanche: + return ContractAddress{ + ChainId: constant.GetChainId(chainName), + Factory: common.HexToAddress("0x740b1c1de25031C31FF4fC9A62f554A55cdC1baD"), + Multicall: common.HexToAddress("0x0139141Cd4Ee88dF3Cdb65881D411bAE271Ef0C2"), + ProxyAdmin: common.HexToAddress("0x9AdA7D7879214073F40183F3410F2b3f088c6381"), + TickLens: common.HexToAddress("0xEB9fFC8bf81b4fFd11fb6A63a6B0f098c6e21950"), + NFTDescriptor: common.HexToAddress("0x27Dd7eE7fE723e83Bf3612a75a034951fe299E99"), + NonfungibleTokenPositionDescriptor: common.HexToAddress("0xe89B7C295d73FCCe88eF263F86e7310925DaEBAF"), + TransparentUpgradeableProxy: common.HexToAddress("0xE1f93a7cB6fFa2dB4F9d5A2FD43158A428993C09"), + NonfungiblePositionManager: common.HexToAddress("0x655C406EBFa14EE2006250925e54ec43AD184f8B"), + V3Migrator: common.HexToAddress("0x44f5f1f5E452ea8d29C890E8F6e893fC0f1f0f97"), + QuoterV2: common.HexToAddress("0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F"), + SwapRouter02: common.HexToAddress("0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE"), + Permit2: common.HexToAddress("0x000000000022D473030F116dDEE9F6B43aC78BA3"), + UniversalRouter: common.HexToAddress("0x4Dae2f939ACf50408e13d58534Ff8c2776d45265"), + v3StakerAddress: common.HexToAddress("0xCA9D0668C600c4dd07ca54Be1615FE5CDFd76Ac3"), + } + case constant.Celo: + return ContractAddress{ + ChainId: constant.GetChainId(chainName), + Factory: common.HexToAddress("0xAfE208a311B21f13EF87E33A90049fC17A7acDEc"), + Multicall2: common.HexToAddress("0x633987602DE5C4F337e3DbF265303A1080324204"), + ProxyAdmin: common.HexToAddress("0xc1b262Dd7643D4B7cA9e51631bBd900a564BF49A"), + TickLens: common.HexToAddress("0x5f115D9113F88e0a0Db1b5033D90D4a9690AcD3D"), + NFTDescriptor: common.HexToAddress("0xa9Fd765d85938D278cb0b108DbE4BF7186831186"), + NonfungibleTokenPositionDescriptor: common.HexToAddress("0x644023b316bB65175C347DE903B60a756F6dd554"), + TransparentUpgradeableProxy: common.HexToAddress("0x505B43c452AA4443e0a6B84bb37771494633Fde9"), + NonfungiblePositionManager: common.HexToAddress("0x3d79EdAaBC0EaB6F08ED885C05Fc0B014290D95A"), + V3Migrator: common.HexToAddress("0x3cFd4d48EDfDCC53D3f173F596f621064614C582"), + QuoterV2: common.HexToAddress("0x82825d0554fA07f7FC52Ab63c961F330fdEFa8E8"), + SwapRouter02: common.HexToAddress("0x5615CDAb10dc425a742d643d949a7F474C01abc4"), + Permit2: common.HexToAddress("0x000000000022D473030F116dDEE9F6B43aC78BA3"), + UniversalRouter: common.HexToAddress("0x643770E279d5D0733F21d6DC03A8efbABf3255B4"), + v3StakerAddress: common.HexToAddress("0x6586FB35393abF7Ff454977a9b3c912d218791C6"), + } + case constant.Blast: + return ContractAddress{ + ChainId: constant.GetChainId(chainName), + Factory: common.HexToAddress("0x792edAdE80af5fC680d96a2eD80A44247D2Cf6Fd"), + Multicall: common.HexToAddress("0xdC7f370de7631cE9e2c2e1DCDA6B3B5744Cf4705"), + ProxyAdmin: common.HexToAddress("0x7C9cAa4ac84C8FAD8Bd504DBF90e791F91f41705"), + TickLens: common.HexToAddress("0x2E95185bCdD928a3e984B7e2D6560Ab1b17d7274"), + NFTDescriptor: common.HexToAddress("0xAa32bD3926097fd04d22b4433e9867417EE79333"), + NonfungibleTokenPositionDescriptor: common.HexToAddress("0x497089D9450BB58f536c38c1C0d0A37472303508"), + TransparentUpgradeableProxy: common.HexToAddress("0xB22Ef02E13B1900EBF10391e57162402c11BfF05"), + NonfungiblePositionManager: common.HexToAddress("0xB218e4f7cF0533d4696fDfC419A0023D33345F28"), + V3Migrator: common.HexToAddress("0x15CA7043CD84C5D21Ae76Ba0A1A967d42c40ecE0"), + QuoterV2: common.HexToAddress("0x6Cdcd65e03c1CEc3730AeeCd45bc140D57A25C77"), + SwapRouter02: common.HexToAddress("0x549FEB8c9bd4c12Ad2AB27022dA12492aC452B66"), + Permit2: common.HexToAddress("0x000000000022d473030f116ddee9f6b43ac78ba3"), + UniversalRouter: common.HexToAddress("0x643770E279d5D0733F21d6DC03A8efbABf3255B4"), + v3StakerAddress: common.HexToAddress("0xEcAF7c276f746170642e97De961f2f0361e1aCc8"), + } + + } + return ContractAddress{} +} + +func GetRouterAddress(chainName string, poolType string) common.Address { + contracts := map[string]map[string]common.Address{ + constant.Ethereum: { + V2Pool: common.HexToAddress("0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"), + V3Pool: common.HexToAddress("0xE592427A0AEce92De3Edee1F18E0157C05861564"), + }, + } + return contracts[chainName][poolType] +} + +func GetNativeTokenWrapperAddress(chainName string) common.Address { + return WNativeTokenAddress[chainName] +} + +func GetStableTokensAddress(chainName string) StableToken { + return stableTokens[chainName] +} diff --git a/utils/provider/dex/uniswap/init.go b/utils/provider/dex/uniswap/init.go new file mode 100644 index 0000000..4d4a304 --- /dev/null +++ b/utils/provider/dex/uniswap/init.go @@ -0,0 +1,10 @@ +package uniswap + +import ( + "omni-balance/utils/configs" + "omni-balance/utils/provider" +) + +func init() { + provider.Register(configs.DEX, NewUniswap) +} diff --git a/utils/provider/dex/uniswap/uniswap.go b/utils/provider/dex/uniswap/uniswap.go new file mode 100644 index 0000000..62d1c19 --- /dev/null +++ b/utils/provider/dex/uniswap/uniswap.go @@ -0,0 +1,235 @@ +package uniswap + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "math/big" + "omni-balance/utils" + "omni-balance/utils/chains" + "omni-balance/utils/configs" + "omni-balance/utils/constant" + "omni-balance/utils/error_types" + "omni-balance/utils/provider" + uniswapConfigs "omni-balance/utils/provider/dex/uniswap/configs" + "strings" + "time" +) + +var ( + SwapApproveSendingAction = "SwapApproveSending" + SwapTXSendingAction = "sourceChainSending" + SwapTXReceivedAction = "targetChainReceived" +) + +func action2Int(action string) int { + switch action { + case SwapApproveSendingAction: + return 0 + case SwapTXSendingAction: + return 1 + case SwapTXReceivedAction: + return 2 + default: + return -1 + } +} + +type Uniswap struct { + conf configs.Config +} + +func NewUniswap(conf configs.Config, noInit ...bool) (provider.Provider, error) { + return &Uniswap{conf: conf}, nil +} + +func (u *Uniswap) GetCost(ctx context.Context, args provider.SwapParams) (provider.TokenInCosts, error) { + if !args.Sender.IsSupportEip712() { + return nil, error_types.ErrUnsupportedWalletType + } + if strings.EqualFold(uniswapConfigs.GetContractAddress(args.TargetChain).UniversalRouter.Hex(), constant.ZeroAddress.Hex()) { + return nil, error_types.ErrUnsupportedTokenAndChain + } + return u.GetTokenIns(ctx, args.TargetChain, args.TargetToken, args.Sender.GetAddress(true), args.Amount) +} + +func (u *Uniswap) Swap(ctx context.Context, args provider.SwapParams) (result provider.SwapResult, err error) { + var ( + log = utils.GetLogFromCtx(ctx).WithField("provide_name", u.Name()) + wallet = args.Sender + contract = uniswapConfigs.GetContractAddress(args.TargetChain) + chain = u.conf.GetChainConfig(args.TargetChain) + tokenOut = u.conf.GetTokenInfoOnChain(args.TargetToken, args.TargetChain) + amountOut = args.Amount + amountOutWei = decimal.NewFromBigInt(chains.EthToWei(amountOut, tokenOut.Decimals), 0) + actionNumber = action2Int(args.LastHistory.Actions) + recordFn = func(s provider.SwapHistory, errs ...error) { + s.ProviderType = string(u.Type()) + s.ProviderName = u.Name() + s.Amount = args.Amount + if args.RecordFn == nil { + return + } + args.RecordFn(s, errs...) + } + ) + ctx = context.WithValue(ctx, constant.ChainNameKeyInCtx, args.TargetChain) + if !utils.InArray(args.LastHistory.Actions, + []string{SwapApproveSendingAction, SwapTXReceivedAction, SwapTXReceivedAction, ""}) { + return provider.SwapResult{}, error_types.ErrUnsupportedActions + } + + tokenIns, err := u.GetTokenIns(ctx, chain.Name, tokenOut.Name, wallet.GetAddress(true), amountOut) + if err != nil { + return provider.SwapResult{}, errors.Wrap(err, "get token ins") + } + if len(tokenIns) == 0 { + return provider.SwapResult{}, error_types.ErrUnsupportedTokenAndChain + } + tokenInPrice, err := tokenIns.GetBest() + if err != nil { + return provider.SwapResult{}, errors.Wrap(err, "get best token in") + } + var ( + tokenIn = u.conf.GetTokenInfoOnChain(tokenInPrice.TokenName, chain.Name) + isTokenInNative = u.conf.IsNativeToken(chain.Name, tokenIn.Name) + ) + log = log.WithFields(logrus.Fields{ + "tokenIn": utils.ToMap(tokenIn), + "tokenOut": utils.ToMap(tokenOut), + "amountOut": amountOut, + "isTokenInNative": isTokenInNative, + }) + log.Debugf("start get exact output quote") + quote, err := u.GetTokenExactOutputQuote( + ctx, + chain.Name, + tokenIn, + tokenOut, + wallet.GetAddress(true), + amountOutWei) + if err != nil { + return provider.SwapResult{}, errors.Wrap(err, "get quote") + } + if len(quote.Quote.Route) == 0 { + return provider.SwapResult{}, errors.Errorf("no route found") + } + + log.WithField("quote", utils.ToMap(quote.Quote)).Debug("get quote success") + + ethClient, err := chains.NewTryClient(ctx, chain.RpcEndpoints) + if err != nil { + return provider.SwapResult{}, errors.New("dial rpc") + } + defer ethClient.Close() + + if !isTokenInNative && actionNumber <= 0 && args.LastHistory.Status != provider.TxStatusSuccess.String() { + // uint256 MAX see https://docs.uniswap.org/contracts/permit2/overview + amount := decimal.RequireFromString("115792089237316195423570985008687907853269984665640564039457584007913129639935") + log.Debugf("approve tokenIn amount: %s", amount) + if err := chains.TokenApprove(ctx, chains.TokenApproveParams{ + ChainId: int64(chain.Id), + TokenAddress: common.HexToAddress(tokenIn.ContractAddress), + Owner: wallet.GetAddress(true), + SendTransaction: wallet.SendTransaction, + WaitTransaction: wallet.WaitTransaction, + Spender: contract.Permit2, + AmountWei: amount, + Client: ethClient, + }); err != nil { + return provider.SwapResult{}, err + } + } + + log.Debug("build tx") + txRawData, err := u.BuildTx(ctx, BuildTxParams{ + TokenIn: tokenIn, + TokenOut: tokenOut, + Chain: chain, + Sender: args.Sender, + Quote: quote, + Deadline: big.NewInt(time.Now().Add(time.Hour * 10).Unix()), + Client: ethClient, + Amount: args.Amount, + }) + if err != nil { + return provider.SwapResult{}, err + } + + var value = decimal.Zero + if isTokenInNative { + value = decimal.RequireFromString(quote.Quote.Route[0][0].AmountIn).Add(decimal.RequireFromString(quote.Quote.GasUseEstimate)) + } + + txData := &types.LegacyTx{ + GasPrice: decimal.RequireFromString(quote.Quote.GasPriceWei).Mul(decimal.NewFromInt(2)).BigInt(), + Gas: uint64(decimal.RequireFromString(quote.Quote.GasUseEstimate).Mul(decimal.NewFromInt(2)).IntPart()), + To: &contract.UniversalRouter, + Data: txRawData, + Value: value.BigInt(), + } + swapResult := &provider.SwapResult{ + ProviderType: u.Type(), + ProviderName: u.Name(), + Order: quote.Quote, + CurrentChain: chain.Name, + TokenInName: tokenIn.Name, + } + log.WithField("txData", utils.ToMap(txData)).Debug("build tx success") + var tx = args.LastHistory.Tx + if actionNumber <= 1 && args.LastHistory.Status != provider.TxStatusSuccess.String() { + recordFn(provider.SwapHistory{Actions: SwapTXSendingAction, Status: string(provider.TxStatusPending), CurrentChain: chain.Name}) + log.Debug("sending tx") + txHash, err := wallet.SendTransaction(ctx, txData, ethClient) + if err != nil { + swapResult.Status = provider.TxStatusFailed + swapResult.Error = err.Error() + args.RecordFn(provider.SwapHistory{Actions: SwapTXSendingAction, Status: string(provider.TxStatusFailed), CurrentChain: chain.Name, Amount: args.Amount}) + return *swapResult, errors.Wrap(err, "send tx") + } + tx = txHash.Hex() + log.WithField("txHash", tx).Debug("send tx success") + recordFn(provider.SwapHistory{Actions: SwapTXSendingAction, Status: string(provider.TxStatusPending), CurrentChain: chain.Name, Tx: tx}) + } + if tx == "" { + return provider.SwapResult{}, errors.New("tx is empty") + } + swapResult.Tx = tx + swapResult.OrderId = tx + if actionNumber <= 2 && args.LastHistory.Status != provider.TxStatusSuccess.String() { + log.Debug("waiting tx") + if err := wallet.WaitTransaction(ctx, common.HexToHash(tx), ethClient); err != nil { + recordFn(provider.SwapHistory{Actions: SwapTXReceivedAction, Status: string(provider.TxStatusFailed), CurrentChain: args.SourceChain, Tx: tx}) + swapResult.Status = provider.TxStatusFailed + swapResult.Error = err.Error() + return *swapResult, err + } + swapResult.Status = provider.TxStatusSuccess + recordFn(provider.SwapHistory{Actions: SwapTXReceivedAction, Status: string(provider.TxStatusSuccess), CurrentChain: chain.Name, Tx: tx}) + } + log.Debug("tx success") + return *swapResult, nil +} + +func (u *Uniswap) Help() []string { + return []string{"See https://app.uniswap.org/swap"} +} + +func (u *Uniswap) Name() string { + return "uniswap" +} + +func (u *Uniswap) Type() configs.LiquidityProviderType { + return configs.DEX +} + +func (u *Uniswap) CheckToken(ctx context.Context, tokenName, tokenInChainName, tokenOutChainName string, amount decimal.Decimal) (bool, error) { + if tokenInChainName != tokenOutChainName { + return false, nil + } + tokenInCosts, err := u.GetTokenIns(ctx, tokenInChainName, tokenName, constant.ZeroAddress, amount) + return len(tokenInCosts) != 0, err +} diff --git a/utils/provider/dex/uniswap/uniswap_test.go b/utils/provider/dex/uniswap/uniswap_test.go new file mode 100644 index 0000000..93adfe8 --- /dev/null +++ b/utils/provider/dex/uniswap/uniswap_test.go @@ -0,0 +1,218 @@ +package uniswap + +import ( + "context" + "encoding/json" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethclient" + "github.com/shopspring/decimal" + "github.com/stretchr/testify/assert" + "math/big" + "omni-balance/utils/configs" + "omni-balance/utils/constant" + "omni-balance/utils/provider/dex/uniswap/utils" + "omni-balance/utils/wallets" + "testing" +) + +var conf = &configs.Config{ + Wallets: []configs.Wallet{ + { + Address: constant.TestWalletAddress, + PrivateKey: constant.TestPrivateKey, + }, + }, + Chains: []configs.Chain{ + { + Name: "arbitrum", + RpcEndpoints: []string{ + "https://arb1.arbitrum.io/rpc", + }, + Tokens: []configs.Token{ + { + Name: "CBETH", + ContractAddress: "0x1debd73e752beaf79865fd6446b0c970eae7732f", + Decimals: 18, + }, + { + Name: "ETH", + ContractAddress: constant.ZeroAddress.Hex(), + Decimals: 18, + }, + { + Name: "RING", + ContractAddress: "0x9e523234D36973f9e38642886197D023C88e307e", // gitleaks:allow + Decimals: 18, + }, + }, + Id: 42161, + }, + }, +} + +func TestUniswap_BuildTx(t *testing.T) { + conf.Init() + client, err := ethclient.Dial("https://arb1.arbitrum.io/rpc") + assert.NoError(t, err) + quoteData := `{"routing":"CLASSIC","quote":{"methodParameters":{"calldata":"0x24856bc30000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000050b0105040c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000500000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000022000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000320000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000147f6101f37d00000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000001163fe8c5429500000000000000000000000000000000000000000000000000000000147f6101f37d00000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002b9e523234d36973f9e38642886197d023c88e307e000bb882af49447d8a07e3bd95bd0d56f35241523fbab100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000009e523234d36973f9e38642886197d023c88e307e00000000000000000000000089f30783108e2f9191db4a44ae2a516327c9957500000000000000000000000000000000000000000000000000b1a2bc2ec5000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000009e523234d36973f9e38642886197d023c88e307e0000000000000000000000005a91fe74ab3788ff58187acaf3fb0a039534428e000000000000000000000000000000000000000000000001158e460913d0000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000005a91fe74ab3788ff58187acaf3fb0a039534428e0000000000000000000000000000000000000000000000000000000000000000","value":"0x147f6101f37d","to":"0x5E325eDA8064b456f4781070C0738d849c824258"},"blockNumber":"213741025","amount":"20000000000000000000","amountDecimals":"20","quote":"22369271765793","quoteDecimals":"0.000022369271765793","quoteGasAdjusted":"24373216442145","quoteGasAdjustedDecimals":"0.000024373216442145","quoteGasAndPortionAdjusted":"24429139621559","quoteGasAndPortionAdjustedDecimals":"0.000024429139621559","gasUseEstimateQuote":"2003944676352","gasUseEstimateQuoteDecimals":"0.000002003944676352","gasUseEstimate":"200394","gasUseEstimateUSD":"0.007619574833510388","simulationStatus":"UNATTEMPTED","simulationError":false,"gasPriceWei":"10000000","route":[[{"type":"v3-pool","address":"0x39FE2595FC6dF650877FC24E47e15A2F9da7daa4","tokenIn":{"chainId":42161,"decimals":"18","address":"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","symbol":"WETH"},"tokenOut":{"chainId":42161,"decimals":"18","address":"0x9e523234D36973f9e38642886197D023C88e307e","symbol":"RING"},"fee":"3000","liquidity":"83079614297215821019731","sqrtRatioX96":"75027613904587995298968008794024","tickCurrent":"137072","amountIn":"22698953047059","amountOut":"20050000000000000000"}]],"routeString":"[V3] 100.00% = WETH -- 0.3% [0x39FE2595FC6dF650877FC24E47e15A2F9da7daa4] --> RING","quoteId":"9e9ffbfc-e8c0-476b-a39a-6c87d4e3b199","hitsCachedRoutes":true,"portionBips":25,"portionRecipient":"0x89F30783108E2F9191Db4A44aE2A516327C99575","portionAmount":"50000000000000000","portionAmountDecimals":"0.05","requestId":"8541333c-2b0f-41a0-8cf9-6b1182b9a824","permitData":{"domain":{"name":"Permit2","chainId":42161,"verifyingContract":"0x000000000022D473030F116dDEE9F6B43aC78BA3"},"types":{"PermitSingle":[{"name":"details","type":"PermitDetails"},{"name":"spender","type":"address"},{"name":"sigDeadline","type":"uint256"}],"PermitDetails":[{"name":"token","type":"address"},{"name":"amount","type":"uint160"},{"name":"expiration","type":"uint48"},{"name":"nonce","type":"uint48"}]},"values":{"details":{"token":"0x0000000000000000000000000000000000000000","amount":"1461501637330902918203684832716283019655932542975","expiration":"1718940656","nonce":"0"},"spender":"0x5E325eDA8064b456f4781070C0738d849c824258","sigDeadline":"1716350456"}},"tradeType":"EXACT_OUTPUT","slippage":0.5},"requestId":"8541333c-2b0f-41a0-8cf9-6b1182b9a824","allQuotes":[{"routing":"CLASSIC","quote":{"methodParameters":{"calldata":"0x24856bc30000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000050b0105040c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000500000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000022000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000320000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000147f6101f37d00000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000001163fe8c5429500000000000000000000000000000000000000000000000000000000147f6101f37d00000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002b9e523234d36973f9e38642886197d023c88e307e000bb882af49447d8a07e3bd95bd0d56f35241523fbab100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000009e523234d36973f9e38642886197d023c88e307e00000000000000000000000089f30783108e2f9191db4a44ae2a516327c9957500000000000000000000000000000000000000000000000000b1a2bc2ec5000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000009e523234d36973f9e38642886197d023c88e307e0000000000000000000000005a91fe74ab3788ff58187acaf3fb0a039534428e000000000000000000000000000000000000000000000001158e460913d0000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000005a91fe74ab3788ff58187acaf3fb0a039534428e0000000000000000000000000000000000000000000000000000000000000000","value":"0x147f6101f37d","to":"0x5E325eDA8064b456f4781070C0738d849c824258"},"blockNumber":"213741025","amount":"20000000000000000000","amountDecimals":"20","quote":"22369271765793","quoteDecimals":"0.000022369271765793","quoteGasAdjusted":"24373216442145","quoteGasAdjustedDecimals":"0.000024373216442145","quoteGasAndPortionAdjusted":"24429139621559","quoteGasAndPortionAdjustedDecimals":"0.000024429139621559","gasUseEstimateQuote":"2003944676352","gasUseEstimateQuoteDecimals":"0.000002003944676352","gasUseEstimate":"200394","gasUseEstimateUSD":"0.007619574833510388","simulationStatus":"UNATTEMPTED","simulationError":false,"gasPriceWei":"10000000","route":[[{"type":"v3-pool","address":"0x39FE2595FC6dF650877FC24E47e15A2F9da7daa4","tokenIn":{"chainId":42161,"decimals":"18","address":"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","symbol":"WETH"},"tokenOut":{"chainId":42161,"decimals":"18","address":"0x9e523234D36973f9e38642886197D023C88e307e","symbol":"RING"},"fee":"3000","liquidity":"83079614297215821019731","sqrtRatioX96":"75027613904587995298968008794024","tickCurrent":"137072","amountIn":"22698953047059","amountOut":"20050000000000000000"}]],"routeString":"[V3] 100.00% = WETH -- 0.3% [0x39FE2595FC6dF650877FC24E47e15A2F9da7daa4] --> RING","quoteId":"9e9ffbfc-e8c0-476b-a39a-6c87d4e3b199","hitsCachedRoutes":true,"portionBips":25,"portionRecipient":"0x89F30783108E2F9191Db4A44aE2A516327C99575","portionAmount":"50000000000000000","portionAmountDecimals":"0.05","requestId":"8541333c-2b0f-41a0-8cf9-6b1182b9a824","permitData":{"domain":{"name":"Permit2","chainId":42161,"verifyingContract":"0x000000000022D473030F116dDEE9F6B43aC78BA3"},"types":{"PermitSingle":[{"name":"details","type":"PermitDetails"},{"name":"spender","type":"address"},{"name":"sigDeadline","type":"uint256"}],"PermitDetails":[{"name":"token","type":"address"},{"name":"amount","type":"uint160"},{"name":"expiration","type":"uint48"},{"name":"nonce","type":"uint48"}]},"values":{"details":{"token":"0x0000000000000000000000000000000000000000","amount":"1461501637330902918203684832716283019655932542975","expiration":"1718940656","nonce":"0"},"spender":"0x5E325eDA8064b456f4781070C0738d849c824258","sigDeadline":"1716350456"}},"tradeType":"EXACT_OUTPUT","slippage":0.5}}]}` // gitleaks:allow + cbETHquoteData := `{"routing":"CLASSIC","quote":{"methodParameters":{"calldata":"0x24856bc300000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000301050400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000220000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000123c4120b4000000000000000000000000000000000000000000000000010eb8b5647007d4b600000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000421debd73e752beaf79865fd6446b0c970eae7732f000bb882af49447d8a07e3bd95bd0d56f35241523fbab1000bb89e523234d36973f9e38642886197d023c88e307e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000001debd73e752beaf79865fd6446b0c970eae7732f00000000000000000000000089f30783108e2f9191db4a44ae2a516327c995750000000000000000000000000000000000000000000000000000000ba43b740000000000000000000000000000000000000000000000000000000000000000600000000000000000000000001debd73e752beaf79865fd6446b0c970eae7732f0000000000000000000000005a91fe74ab3788ff58187acaf3fb0a039534428e000000000000000000000000000000000000000000000000000012309ce54000","value":"0x00","to":"0x5E325eDA8064b456f4781070C0738d849c824258"},"blockNumber":"213813900","amount":"20000000000000","amountDecimals":"0.00002","quote":"19362083576070988577","quoteDecimals":"19.362083576070988577","quoteGasAdjusted":"21852250560150417637","quoteGasAdjustedDecimals":"21.852250560150417637","quoteGasAndPortionAdjusted":"21900655769090595108","quoteGasAndPortionAdjustedDecimals":"21.900655769090595108","gasUseEstimateQuote":"2490166984079429060","gasUseEstimateQuoteDecimals":"2.49016698407942906","gasUseEstimate":"276278","gasUseEstimateUSD":"0.010405816029298318","simulationStatus":"UNATTEMPTED","simulationError":false,"gasPriceWei":"10000000","route":[[{"type":"v3-pool","address":"0x39FE2595FC6dF650877FC24E47e15A2F9da7daa4","tokenIn":{"chainId":42161,"decimals":"18","address":"0x9e523234D36973f9e38642886197D023C88e307e","symbol":"RING"},"tokenOut":{"chainId":42161,"decimals":"18","address":"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","symbol":"WETH"},"fee":"3000","liquidity":"83079614297215821019731","sqrtRatioX96":"75217739790961806731360142688900","tickCurrent":"137123","amountIn":"19507541228936221878"},{"type":"v3-pool","address":"0xEd3fE08bd12F24dad0f1a1E58610644dEbe374fb","tokenIn":{"chainId":42161,"decimals":"18","address":"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","symbol":"WETH"},"tokenOut":{"chainId":42161,"decimals":"18","address":"0x1DEBd73E752bEaF79865Fd6446b0c970EaE7732f","symbol":"cbETH"},"fee":"3000","liquidity":"3544355497631728858561","sqrtRatioX96":"81864391755545008004895065536","tickCurrent":"654","amountOut":"20050000000000"}]],"routeString":"[V3] 100.00% = RING -- 0.3% [0x39FE2595FC6dF650877FC24E47e15A2F9da7daa4] --> WETH -- 0.3% [0xEd3fE08bd12F24dad0f1a1E58610644dEbe374fb] --> cbETH","quoteId":"bd03db72-4b74-4cae-a39d-23aaa911c28f","hitsCachedRoutes":true,"portionBips":25,"portionRecipient":"0x89F30783108E2F9191Db4A44aE2A516327C99575","portionAmount":"50000000000","portionAmountDecimals":"0.00000005","requestId":"0fc33eb1-f91f-49dd-8968-9db0225639c0","tradeType":"EXACT_OUTPUT","slippage":0.5},"requestId":"0fc33eb1-f91f-49dd-8968-9db0225639c0","allQuotes":[{"routing":"CLASSIC","quote":{"methodParameters":{"calldata":"0x24856bc300000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000301050400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000220000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000123c4120b4000000000000000000000000000000000000000000000000010eb8b5647007d4b600000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000421debd73e752beaf79865fd6446b0c970eae7732f000bb882af49447d8a07e3bd95bd0d56f35241523fbab1000bb89e523234d36973f9e38642886197d023c88e307e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000001debd73e752beaf79865fd6446b0c970eae7732f00000000000000000000000089f30783108e2f9191db4a44ae2a516327c995750000000000000000000000000000000000000000000000000000000ba43b740000000000000000000000000000000000000000000000000000000000000000600000000000000000000000001debd73e752beaf79865fd6446b0c970eae7732f0000000000000000000000005a91fe74ab3788ff58187acaf3fb0a039534428e000000000000000000000000000000000000000000000000000012309ce54000","value":"0x00","to":"0x5E325eDA8064b456f4781070C0738d849c824258"},"blockNumber":"213813900","amount":"20000000000000","amountDecimals":"0.00002","quote":"19362083576070988577","quoteDecimals":"19.362083576070988577","quoteGasAdjusted":"21852250560150417637","quoteGasAdjustedDecimals":"21.852250560150417637","quoteGasAndPortionAdjusted":"21900655769090595108","quoteGasAndPortionAdjustedDecimals":"21.900655769090595108","gasUseEstimateQuote":"2490166984079429060","gasUseEstimateQuoteDecimals":"2.49016698407942906","gasUseEstimate":"276278","gasUseEstimateUSD":"0.010405816029298318","simulationStatus":"UNATTEMPTED","simulationError":false,"gasPriceWei":"10000000","route":[[{"type":"v3-pool","address":"0x39FE2595FC6dF650877FC24E47e15A2F9da7daa4","tokenIn":{"chainId":42161,"decimals":"18","address":"0x9e523234D36973f9e38642886197D023C88e307e","symbol":"RING"},"tokenOut":{"chainId":42161,"decimals":"18","address":"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","symbol":"WETH"},"fee":"3000","liquidity":"83079614297215821019731","sqrtRatioX96":"75217739790961806731360142688900","tickCurrent":"137123","amountIn":"19410488785011166048"},{"type":"v3-pool","address":"0xEd3fE08bd12F24dad0f1a1E58610644dEbe374fb","tokenIn":{"chainId":42161,"decimals":"18","address":"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","symbol":"WETH"},"tokenOut":{"chainId":42161,"decimals":"18","address":"0x1DEBd73E752bEaF79865Fd6446b0c970EaE7732f","symbol":"cbETH"},"fee":"3000","liquidity":"3544355497631728858561","sqrtRatioX96":"81864391755545008004895065536","tickCurrent":"654","amountOut":"20050000000000"}]],"routeString":"[V3] 100.00% = RING -- 0.3% [0x39FE2595FC6dF650877FC24E47e15A2F9da7daa4] --> WETH -- 0.3% [0xEd3fE08bd12F24dad0f1a1E58610644dEbe374fb] --> cbETH","quoteId":"bd03db72-4b74-4cae-a39d-23aaa911c28f","hitsCachedRoutes":true,"portionBips":25,"portionRecipient":"0x89F30783108E2F9191Db4A44aE2A516327C99575","portionAmount":"50000000000","portionAmountDecimals":"0.00000005","requestId":"0fc33eb1-f91f-49dd-8968-9db0225639c0","tradeType":"EXACT_OUTPUT","slippage":0.5}}]}` // gitleaks:allow + RING2ETHquoteData := `{"routing":"CLASSIC","quote":{"methodParameters":{"calldata":"0x24856bc300000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000301050c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001800000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000123c4120b400000000000000000000000000000000000000000000000000fcce4826bed4f5a700000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002b82af49447d8a07e3bd95bd0d56f35241523fbab1000bb89e523234d36973f9e38642886197d023c88e307e000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006000000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab100000000000000000000000089f30783108e2f9191db4a44ae2a516327c995750000000000000000000000000000000000000000000000000000000ba43b740000000000000000000000000000000000000000000000000000000000000000400000000000000000000000005a91fe74ab3788ff58187acaf3fb0a039534428e000000000000000000000000000000000000000000000000000012309ce54000","value":"0x00","to":"0x5E325eDA8064b456f4781070C0738d849c824258"},"blockNumber":"213817191","amount":"20000000000000","amountDecimals":"0.00002","quote":"18080745275128417452","quoteDecimals":"18.080745275128417452","quoteGasAdjusted":"19899248096074758680","quoteGasAdjustedDecimals":"19.89924809607475868","quoteGasAndPortionAdjusted":"19944449959262579723","quoteGasAndPortionAdjustedDecimals":"19.944449959262579723","gasUseEstimateQuote":"1818502820946341228","gasUseEstimateQuoteDecimals":"1.818502820946341228","gasUseEstimate":"201758","gasUseEstimateUSD":"0.007599069507237653","simulationStatus":"UNATTEMPTED","simulationError":false,"gasPriceWei":"10000000","route":[[{"type":"v3-pool","address":"0x39FE2595FC6dF650877FC24E47e15A2F9da7daa4","tokenIn":{"chainId":42161,"decimals":"18","address":"0x9e523234D36973f9e38642886197D023C88e307e","symbol":"RING"},"tokenOut":{"chainId":42161,"decimals":"18","address":"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","symbol":"WETH"},"fee":"3000","liquidity":"83079614297215821019731","sqrtRatioX96":"75217739790961806731360142688900","tickCurrent":"137123","amountIn":"18216576874007819687","amountOut":"20050000000000"}]],"routeString":"[V3] 100.00% = RING -- 0.3% [0x39FE2595FC6dF650877FC24E47e15A2F9da7daa4] --> WETH","quoteId":"235fc981-0c21-4b72-b6cf-503e5a5f9f75","hitsCachedRoutes":true,"portionBips":25,"portionRecipient":"0x89F30783108E2F9191Db4A44aE2A516327C99575","portionAmount":"50000000000","portionAmountDecimals":"0.00000005","requestId":"2db07bc8-ad9b-48b4-83d9-d516cc37beab","tradeType":"EXACT_OUTPUT","slippage":0.5},"requestId":"2db07bc8-ad9b-48b4-83d9-d516cc37beab","allQuotes":[{"routing":"CLASSIC","quote":{"methodParameters":{"calldata":"0x24856bc300000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000301050c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001800000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000123c4120b400000000000000000000000000000000000000000000000000fcce4826bed4f5a700000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002b82af49447d8a07e3bd95bd0d56f35241523fbab1000bb89e523234d36973f9e38642886197d023c88e307e000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006000000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab100000000000000000000000089f30783108e2f9191db4a44ae2a516327c995750000000000000000000000000000000000000000000000000000000ba43b740000000000000000000000000000000000000000000000000000000000000000400000000000000000000000005a91fe74ab3788ff58187acaf3fb0a039534428e000000000000000000000000000000000000000000000000000012309ce54000","value":"0x00","to":"0x5E325eDA8064b456f4781070C0738d849c824258"},"blockNumber":"213817191","amount":"20000000000000","amountDecimals":"0.00002","quote":"18080745275128417452","quoteDecimals":"18.080745275128417452","quoteGasAdjusted":"19899248096074758680","quoteGasAdjustedDecimals":"19.89924809607475868","quoteGasAndPortionAdjusted":"19944449959262579723","quoteGasAndPortionAdjustedDecimals":"19.944449959262579723","gasUseEstimateQuote":"1818502820946341228","gasUseEstimateQuoteDecimals":"1.818502820946341228","gasUseEstimate":"201758","gasUseEstimateUSD":"0.007599069507237653","simulationStatus":"UNATTEMPTED","simulationError":false,"gasPriceWei":"10000000","route":[[{"type":"v3-pool","address":"0x39FE2595FC6dF650877FC24E47e15A2F9da7daa4","tokenIn":{"chainId":42161,"decimals":"18","address":"0x9e523234D36973f9e38642886197D023C88e307e","symbol":"RING"},"tokenOut":{"chainId":42161,"decimals":"18","address":"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","symbol":"WETH"},"fee":"3000","liquidity":"83079614297215821019731","sqrtRatioX96":"75217739790961806731360142688900","tickCurrent":"137123","amountIn":"18125947138316238495","amountOut":"20050000000000"}]],"routeString":"[V3] 100.00% = RING -- 0.3% [0x39FE2595FC6dF650877FC24E47e15A2F9da7daa4] --> WETH","quoteId":"235fc981-0c21-4b72-b6cf-503e5a5f9f75","hitsCachedRoutes":true,"portionBips":25,"portionRecipient":"0x89F30783108E2F9191Db4A44aE2A516327C99575","portionAmount":"50000000000","portionAmountDecimals":"0.00000005","requestId":"2db07bc8-ad9b-48b4-83d9-d516cc37beab","tradeType":"EXACT_OUTPUT","slippage":0.5}}]}` // gitleaks:allow + ETH2CBETHV2quoteData := `{"routing":"CLASSIC","quote":{"methodParameters":{"calldata":"0x24856bc30000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000050b0905040c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000500000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000022000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000032000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000001d9a345f20b00000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000001d2d3501200000000000000000000000000000000000000000000000000000001d9a345f20b00000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab10000000000000000000000001debd73e752beaf79865fd6446b0c970eae7732f00000000000000000000000000000000000000000000000000000000000000600000000000000000000000001debd73e752beaf79865fd6446b0c970eae7732f00000000000000000000000089f30783108e2f9191db4a44ae2a516327c99575000000000000000000000000000000000000000000000000000000012a05f20000000000000000000000000000000000000000000000000000000000000000600000000000000000000000001debd73e752beaf79865fd6446b0c970eae7732f0000000000000000000000005a91fe74ab3788ff58187acaf3fb0a039534428e000000000000000000000000000000000000000000000000000001d1a94a200000000000000000000000000000000000000000000000000000000000000000400000000000000000000000005a91fe74ab3788ff58187acaf3fb0a039534428e0000000000000000000000000000000000000000000000000000000000000000","value":"0x01d9a345f20b","to":"0x5E325eDA8064b456f4781070C0738d849c824258"},"blockNumber":"213830031","amount":"2000000000000","amountDecimals":"0.000002","quote":"2019090384649","quoteDecimals":"0.000002019090384649","quoteGasAdjusted":"3715163744489","quoteGasAdjustedDecimals":"0.000003715163744489","quoteGasAndPortionAdjusted":"3720211470450","quoteGasAndPortionAdjustedDecimals":"0.00000372021147045","gasUseEstimateQuote":"1696073359840","gasUseEstimateQuoteDecimals":"0.00000169607335984","gasUseEstimate":"169607","gasUseEstimateUSD":"0.006349","simulationStatus":"UNATTEMPTED","simulationError":false,"gasPriceWei":"10000000","route":[[{"type":"v2-pool","address":"0x1504CA3De8F90149520fCb08e27eb57F7D6a7DE6","tokenIn":{"chainId":42161,"decimals":"18","address":"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","symbol":"WETH"},"tokenOut":{"chainId":42161,"decimals":"18","address":"0x1DEBd73E752bEaF79865Fd6446b0c970EaE7732f","symbol":"cbETH"},"reserve0":{"token":{"chainId":42161,"decimals":"18","address":"0x1DEBd73E752bEaF79865Fd6446b0c970EaE7732f","symbol":"cbETH"},"quotient":"482571368782833"},"reserve1":{"token":{"chainId":42161,"decimals":"18","address":"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","symbol":"WETH"},"quotient":"483698006795751"},"amountIn":"2034258801163","amountOut":"2005000000000"}]],"routeString":"[V2] 100.00% = WETH -- [0x1504CA3De8F90149520fCb08e27eb57F7D6a7DE6] --> cbETH","quoteId":"f3349f21-db00-4d67-8c97-0dedc472630f","hitsCachedRoutes":true,"portionBips":25,"portionRecipient":"0x89F30783108E2F9191Db4A44aE2A516327C99575","portionAmount":"5000000000","portionAmountDecimals":"0.000000005","requestId":"7fd363de-73e5-4f3c-9bcd-71b2bea73563","permitData":{"domain":{"name":"Permit2","chainId":42161,"verifyingContract":"0x000000000022D473030F116dDEE9F6B43aC78BA3"},"types":{"PermitSingle":[{"name":"details","type":"PermitDetails"},{"name":"spender","type":"address"},{"name":"sigDeadline","type":"uint256"}],"PermitDetails":[{"name":"token","type":"address"},{"name":"amount","type":"uint160"},{"name":"expiration","type":"uint48"},{"name":"nonce","type":"uint48"}]},"values":{"details":{"token":"0x0000000000000000000000000000000000000000","amount":"1461501637330902918203684832716283019655932542975","expiration":"1718963315","nonce":"0"},"spender":"0x5E325eDA8064b456f4781070C0738d849c824258","sigDeadline":"1716373115"}},"tradeType":"EXACT_OUTPUT","slippage":0.5},"requestId":"7fd363de-73e5-4f3c-9bcd-71b2bea73563","allQuotes":[{"routing":"CLASSIC","quote":{"methodParameters":{"calldata":"0x24856bc30000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000050b0905040c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000500000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000022000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000032000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000001d9a345f20b00000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000001d2d3501200000000000000000000000000000000000000000000000000000001d9a345f20b00000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab10000000000000000000000001debd73e752beaf79865fd6446b0c970eae7732f00000000000000000000000000000000000000000000000000000000000000600000000000000000000000001debd73e752beaf79865fd6446b0c970eae7732f00000000000000000000000089f30783108e2f9191db4a44ae2a516327c99575000000000000000000000000000000000000000000000000000000012a05f20000000000000000000000000000000000000000000000000000000000000000600000000000000000000000001debd73e752beaf79865fd6446b0c970eae7732f0000000000000000000000005a91fe74ab3788ff58187acaf3fb0a039534428e000000000000000000000000000000000000000000000000000001d1a94a200000000000000000000000000000000000000000000000000000000000000000400000000000000000000000005a91fe74ab3788ff58187acaf3fb0a039534428e0000000000000000000000000000000000000000000000000000000000000000","value":"0x01d9a345f20b","to":"0x5E325eDA8064b456f4781070C0738d849c824258"},"blockNumber":"213830031","amount":"2000000000000","amountDecimals":"0.000002","quote":"2019090384649","quoteDecimals":"0.000002019090384649","quoteGasAdjusted":"3715163744489","quoteGasAdjustedDecimals":"0.000003715163744489","quoteGasAndPortionAdjusted":"3720211470450","quoteGasAndPortionAdjustedDecimals":"0.00000372021147045","gasUseEstimateQuote":"1696073359840","gasUseEstimateQuoteDecimals":"0.00000169607335984","gasUseEstimate":"169607","gasUseEstimateUSD":"0.006349","simulationStatus":"UNATTEMPTED","simulationError":false,"gasPriceWei":"10000000","route":[[{"type":"v2-pool","address":"0x1504CA3De8F90149520fCb08e27eb57F7D6a7DE6","tokenIn":{"chainId":42161,"decimals":"18","address":"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","symbol":"WETH"},"tokenOut":{"chainId":42161,"decimals":"18","address":"0x1DEBd73E752bEaF79865Fd6446b0c970EaE7732f","symbol":"cbETH"},"reserve0":{"token":{"chainId":42161,"decimals":"18","address":"0x1DEBd73E752bEaF79865Fd6446b0c970EaE7732f","symbol":"cbETH"},"quotient":"482571368782833"},"reserve1":{"token":{"chainId":42161,"decimals":"18","address":"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","symbol":"WETH"},"quotient":"483698006795751"},"amountIn":"2034258801163","amountOut":"2005000000000"}]],"routeString":"[V2] 100.00% = WETH -- [0x1504CA3De8F90149520fCb08e27eb57F7D6a7DE6] --> cbETH","quoteId":"f3349f21-db00-4d67-8c97-0dedc472630f","hitsCachedRoutes":true,"portionBips":25,"portionRecipient":"0x89F30783108E2F9191Db4A44aE2A516327C99575","portionAmount":"5000000000","portionAmountDecimals":"0.000000005","requestId":"7fd363de-73e5-4f3c-9bcd-71b2bea73563","permitData":{"domain":{"name":"Permit2","chainId":42161,"verifyingContract":"0x000000000022D473030F116dDEE9F6B43aC78BA3"},"types":{"PermitSingle":[{"name":"details","type":"PermitDetails"},{"name":"spender","type":"address"},{"name":"sigDeadline","type":"uint256"}],"PermitDetails":[{"name":"token","type":"address"},{"name":"amount","type":"uint160"},{"name":"expiration","type":"uint48"},{"name":"nonce","type":"uint48"}]},"values":{"details":{"token":"0x0000000000000000000000000000000000000000","amount":"1461501637330902918203684832716283019655932542975","expiration":"1718963315","nonce":"0"},"spender":"0x5E325eDA8064b456f4781070C0738d849c824258","sigDeadline":"1716373115"}},"tradeType":"EXACT_OUTPUT","slippage":0.5}}]}` // gitleaks:allow + CBETH2ETHV2quoteData := `{"routing":"CLASSIC","quote":{"methodParameters":{"calldata":"0x24856bc300000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000309050c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001800000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000140f2c578c40000000000000000000000000000000000000000000000000000014f50bb466ca00000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000020000000000000000000000001debd73e752beaf79865fd6446b0c970eae7732f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab1000000000000000000000000000000000000000000000000000000000000006000000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab100000000000000000000000089f30783108e2f9191db4a44ae2a516327c995750000000000000000000000000000000000000000000000000000000cce50a84000000000000000000000000000000000000000000000000000000000000000400000000000000000000000005a91fe74ab3788ff58187acaf3fb0a039534428e000000000000000000000000000000000000000000000000000014025e06e400","value":"0x00","to":"0x5E325eDA8064b456f4781070C0738d849c824258"},"blockNumber":"213832225","amount":"22000400000000","amountDecimals":"0.0000220004","quote":"22870878440923","quoteDecimals":"0.000022870878440923","quoteGasAdjusted":"24758565294438","quoteGasAdjustedDecimals":"0.000024758565294438","quoteGasAndPortionAdjusted":"24815742490540","quoteGasAndPortionAdjustedDecimals":"0.00002481574249054","gasUseEstimateQuote":"1887686853515","gasUseEstimateQuoteDecimals":"0.000001887686853515","gasUseEstimate":"190793","gasUseEstimateUSD":"0.007142","simulationStatus":"UNATTEMPTED","simulationError":false,"gasPriceWei":"10000000","route":[[{"type":"v2-pool","address":"0x1504CA3De8F90149520fCb08e27eb57F7D6a7DE6","tokenIn":{"chainId":42161,"decimals":"18","address":"0x1DEBd73E752bEaF79865Fd6446b0c970EaE7732f","symbol":"cbETH"},"tokenOut":{"chainId":42161,"decimals":"18","address":"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","symbol":"WETH"},"reserve0":{"token":{"chainId":42161,"decimals":"18","address":"0x1DEBd73E752bEaF79865Fd6446b0c970EaE7732f","symbol":"cbETH"},"quotient":"480566368782833"},"reserve1":{"token":{"chainId":42161,"decimals":"18","address":"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","symbol":"WETH"},"quotient":"485722144906361"},"amountIn":"2008326802927","amountOut":"2005401000000"}]],"routeString":"[V2] 100.00% = cbETH -- [0x1504CA3De8F90149520fCb08e27eb57F7D6a7DE6] --> WETH","quoteId":"b3852cd8-30cd-4b96-bfbf-74961420bac3","hitsCachedRoutes":true,"portionBips":25,"portionRecipient":"0x89F30783108E2F9191Db4A44aE2A516327C99575","portionAmount":"55001000000","portionAmountDecimals":"0.000000055001","requestId":"22218871-339b-4ca8-860a-8593e90d3b4b","permitData":{"domain":{"name":"Permit2","chainId":42161,"verifyingContract":"0x000000000022D473030F116dDEE9F6B43aC78BA3"},"types":{"PermitSingle":[{"name":"details","type":"PermitDetails"},{"name":"spender","type":"address"},{"name":"sigDeadline","type":"uint256"}],"PermitDetails":[{"name":"token","type":"address"},{"name":"amount","type":"uint160"},{"name":"expiration","type":"uint48"},{"name":"nonce","type":"uint48"}]},"values":{"details":{"token":"0x1DEBd73E752bEaF79865Fd6446b0c970EaE7732f","amount":"1461501637330902918203684832716283019655932542975","expiration":"1718963869","nonce":"1"},"spender":"0x5E325eDA8064b456f4781070C0738d849c824258","sigDeadline":"1716373669"}},"tradeType":"EXACT_OUTPUT","slippage":0.5},"requestId":"22218871-339b-4ca8-860a-8593e90d3b4b","allQuotes":[{"routing":"CLASSIC","quote":{"methodParameters":{"calldata":"0x24856bc300000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000309050c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001800000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000140f2c578c40000000000000000000000000000000000000000000000000000014f50bb466ca00000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000020000000000000000000000001debd73e752beaf79865fd6446b0c970eae7732f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab1000000000000000000000000000000000000000000000000000000000000006000000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab100000000000000000000000089f30783108e2f9191db4a44ae2a516327c995750000000000000000000000000000000000000000000000000000000cce50a84000000000000000000000000000000000000000000000000000000000000000400000000000000000000000005a91fe74ab3788ff58187acaf3fb0a039534428e000000000000000000000000000000000000000000000000000014025e06e400","value":"0x00","to":"0x5E325eDA8064b456f4781070C0738d849c824258"},"blockNumber":"213832225","amount":"22000400000000","amountDecimals":"0.0000220004","quote":"22870878440923","quoteDecimals":"0.000022870878440923","quoteGasAdjusted":"24758565294438","quoteGasAdjustedDecimals":"0.000024758565294438","quoteGasAndPortionAdjusted":"24815742490540","quoteGasAndPortionAdjustedDecimals":"0.00002481574249054","gasUseEstimateQuote":"1887686853515","gasUseEstimateQuoteDecimals":"0.000001887686853515","gasUseEstimate":"190793","gasUseEstimateUSD":"0.007142","simulationStatus":"UNATTEMPTED","simulationError":false,"gasPriceWei":"10000000","route":[[{"type":"v2-pool","address":"0x1504CA3De8F90149520fCb08e27eb57F7D6a7DE6","tokenIn":{"chainId":42161,"decimals":"18","address":"0x1DEBd73E752bEaF79865Fd6446b0c970EaE7732f","symbol":"cbETH"},"tokenOut":{"chainId":42161,"decimals":"18","address":"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","symbol":"WETH"},"reserve0":{"token":{"chainId":42161,"decimals":"18","address":"0x1DEBd73E752bEaF79865Fd6446b0c970EaE7732f","symbol":"cbETH"},"quotient":"480566368782833"},"reserve1":{"token":{"chainId":42161,"decimals":"18","address":"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","symbol":"WETH"},"quotient":"485722144906361"},"amountIn":"2008326802927","amountOut":"22055401000000"}]],"routeString":"[V2] 100.00% = cbETH -- [0x1504CA3De8F90149520fCb08e27eb57F7D6a7DE6] --> WETH","quoteId":"b3852cd8-30cd-4b96-bfbf-74961420bac3","hitsCachedRoutes":true,"portionBips":25,"portionRecipient":"0x89F30783108E2F9191Db4A44aE2A516327C99575","portionAmount":"55001000000","portionAmountDecimals":"0.000000055001","requestId":"22218871-339b-4ca8-860a-8593e90d3b4b","permitData":{"domain":{"name":"Permit2","chainId":42161,"verifyingContract":"0x000000000022D473030F116dDEE9F6B43aC78BA3"},"types":{"PermitSingle":[{"name":"details","type":"PermitDetails"},{"name":"spender","type":"address"},{"name":"sigDeadline","type":"uint256"}],"PermitDetails":[{"name":"token","type":"address"},{"name":"amount","type":"uint160"},{"name":"expiration","type":"uint48"},{"name":"nonce","type":"uint48"}]},"values":{"details":{"token":"0x1DEBd73E752bEaF79865Fd6446b0c970EaE7732f","amount":"1461501637330902918203684832716283019655932542975","expiration":"1718963869","nonce":"1"},"spender":"0x5E325eDA8064b456f4781070C0738d849c824258","sigDeadline":"1716373669"}},"tradeType":"EXACT_OUTPUT","slippage":0.5}}]}` // gitleaks:allow + var ( + quote utils.Quote + cbETHquote utils.Quote + RING2ETHquote utils.Quote + ETH2CBETHV2quote utils.Quote + CBETH2ETHV2quote utils.Quote + ) + assert.NoError(t, json.Unmarshal([]byte(quoteData), "e)) + assert.NoError(t, json.Unmarshal([]byte(cbETHquoteData), &cbETHquote)) + assert.NoError(t, json.Unmarshal([]byte(RING2ETHquoteData), &RING2ETHquote)) + assert.NoError(t, json.Unmarshal([]byte(ETH2CBETHV2quoteData), Ð2CBETHV2quote)) + assert.NoError(t, json.Unmarshal([]byte(CBETH2ETHV2quoteData), &CBETH2ETHV2quote)) + type fields struct { + conf configs.Config + } + type args struct { + ctx context.Context + args BuildTxParams + } + tests := []struct { + name string + fields fields + args args + want []byte + wantErr bool + }{ + { + name: "ETH->RING", + fields: fields{ + conf: *conf, + }, + args: args{ + args: BuildTxParams{ + TokenIn: conf.GetTokenInfoOnChain("ETH", "arbitrum"), + TokenOut: conf.GetTokenInfoOnChain("RING", "arbitrum"), + Chain: conf.GetChainConfig("arbitrum"), + Sender: wallets.NewWallets(wallets.WalletConfig{ + PrivateKey: constant.TestPrivateKey, + Address: common.HexToAddress(constant.TestWalletAddress), + }), + Quote: quote, + Deadline: big.NewInt(1716301989), + Client: client, + Amount: decimal.RequireFromString("20"), + }, + }, + wantErr: false, + // see https://arbiscan.io/tx/0x0f9792ac6ed673eefedee6d773024ac002215295c11ed4a47268e233f1b8889a + want: common.Hex2Bytes("3593564c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000664cb0a500000000000000000000000000000000000000000000000000000000000000048b01848c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000028000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000014a503087c1300000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000001163fe8c542950000000000000000000000000000000000000000000000000000000014a503087c1300000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002b9e523234d36973f9e38642886197d023c88e307e000bb882af49447d8a07e3bd95bd0d56f35241523fbab100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000009e523234d36973f9e38642886197d023c88e307e0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000001158e460913d00000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000"), + }, + { + name: "RING->CBETH", + fields: fields{ + conf: *conf, + }, + args: args{ + args: BuildTxParams{ + TokenIn: conf.GetTokenInfoOnChain("RING", "arbitrum"), + TokenOut: conf.GetTokenInfoOnChain("CBETH", "arbitrum"), + Chain: conf.GetChainConfig("arbitrum"), + Sender: wallets.NewWallets(wallets.WalletConfig{ + PrivateKey: constant.TestPrivateKey, + Address: common.HexToAddress(constant.TestWalletAddress), + }), + Quote: cbETHquote, + Deadline: big.NewInt(1716367519), + Client: client, + Amount: decimal.RequireFromString("0.00002"), + }, + }, + wantErr: false, + want: common.Hex2Bytes("3593564c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000664db09f00000000000000000000000000000000000000000000000000000000000000020184000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000180000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000123c4120b4000000000000000000000000000000000000000000000000010eb8b5647007d4b600000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000421debd73e752beaf79865fd6446b0c970eae7732f000bb882af49447d8a07e3bd95bd0d56f35241523fbab1000bb89e523234d36973f9e38642886197d023c88e307e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000001debd73e752beaf79865fd6446b0c970eae7732f0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000012309ce54000"), + }, + { + name: "RING->ETH", + fields: fields{ + conf: *conf, + }, + args: args{ + args: BuildTxParams{ + TokenIn: conf.GetTokenInfoOnChain("RING", "arbitrum"), + TokenOut: conf.GetTokenInfoOnChain("ETH", "arbitrum"), + Chain: conf.GetChainConfig("arbitrum"), + Sender: wallets.NewWallets(wallets.WalletConfig{ + PrivateKey: constant.TestPrivateKey, + Address: common.HexToAddress(constant.TestWalletAddress), + }), + Quote: RING2ETHquote, + Deadline: big.NewInt(1716368349), + Client: client, + Amount: decimal.RequireFromString("0.00002"), + }, + }, + wantErr: false, + want: common.Hex2Bytes("3593564c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000664db3dd0000000000000000000000000000000000000000000000000000000000000002018c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000160000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000123c4120b400000000000000000000000000000000000000000000000000fcce4826bed4f5a700000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002b82af49447d8a07e3bd95bd0d56f35241523fbab1000bb89e523234d36973f9e38642886197d023c88e307e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000012309ce54000"), + }, + { + name: "ETH-v2>CBETH", + fields: fields{ + conf: *conf, + }, + args: args{ + args: BuildTxParams{ + TokenIn: conf.GetTokenInfoOnChain("ETH", "arbitrum"), + TokenOut: conf.GetTokenInfoOnChain("CBETH", "arbitrum"), + Chain: conf.GetChainConfig("arbitrum"), + Sender: wallets.NewWallets(wallets.WalletConfig{ + PrivateKey: constant.TestPrivateKey, + Address: common.HexToAddress(constant.TestWalletAddress), + }), + Quote: ETH2CBETHV2quote, + Deadline: big.NewInt(1716371601), + Client: client, + Amount: decimal.RequireFromString("0.000002"), + }, + }, + wantErr: false, + want: common.Hex2Bytes("3593564c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000664dc09100000000000000000000000000000000000000000000000000000000000000048b09848c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000028000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000001d9a345f20b00000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000001d2d3501200000000000000000000000000000000000000000000000000000001d9a345f20b00000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab10000000000000000000000001debd73e752beaf79865fd6446b0c970eae7732f00000000000000000000000000000000000000000000000000000000000000600000000000000000000000001debd73e752beaf79865fd6446b0c970eae7732f0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000001d1a94a2000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000"), + }, + { + name: "CBETH-v2>ETH", + fields: fields{ + conf: *conf, + }, + args: args{ + args: BuildTxParams{ + TokenIn: conf.GetTokenInfoOnChain("CBETH", "arbitrum"), + TokenOut: conf.GetTokenInfoOnChain("ETH", "arbitrum"), + Chain: conf.GetChainConfig("arbitrum"), + Sender: wallets.NewWallets(wallets.WalletConfig{ + PrivateKey: constant.TestPrivateKey, + Address: common.HexToAddress(constant.TestWalletAddress), + }), + Quote: CBETH2ETHV2quote, + Deadline: big.NewInt(1716372184), + Client: client, + Amount: decimal.RequireFromString("0.0000020004"), + }, + }, + wantErr: false, + want: common.Hex2Bytes("3593564c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000664dc2d800000000000000000000000000000000000000000000000000000000000000030a098c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001e0000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000001600000000000000000000000001debd73e752beaf79865fd6446b0c970eae7732f0000000000000000000000000000000000000000000000000000299a152b9bb600000000000000000000000000000000000000000000000000000000664f145800000000000000000000000000000000000000000000000000000000000000000000000000000000000000005e325eda8064b456f4781070c0738d849c82425800000000000000000000000000000000000000000000000000000000664f145800000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000004106973fac8dc06d7f7459a4d9c16099e786739b13dcf3506fa3de0330c1582a01400c7fc548e451eecea5aa40229dfc08188073e3e5f5ef32c0871c658cfc0ef31b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000001d2eb36d840000000000000000000000000000000000000000000000000000001d3999b0def00000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000020000000000000000000000001debd73e752beaf79865fd6446b0c970eae7732f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab100000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000001d1c121a400"), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + u := &Uniswap{ + conf: tt.fields.conf, + } + got, err := u.BuildTx(tt.args.ctx, tt.args.args) + if (err != nil) != tt.wantErr { + t.Errorf("BuildTx() error = %v, wantErr %v", err, tt.wantErr) + return + } + assert.Equal(t, common.Bytes2Hex(tt.want), common.Bytes2Hex(got)) + }) + } +} diff --git a/utils/provider/dex/uniswap/utils.go b/utils/provider/dex/uniswap/utils.go new file mode 100644 index 0000000..25f8129 --- /dev/null +++ b/utils/provider/dex/uniswap/utils.go @@ -0,0 +1,197 @@ +package uniswap + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/math" + "github.com/ethereum/go-ethereum/ethclient/simulated" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "math/big" + "omni-balance/utils/chains" + "omni-balance/utils/configs" + "omni-balance/utils/error_types" + "omni-balance/utils/provider" + "omni-balance/utils/provider/dex/uniswap/abi/permit2" + uniswapConfigs "omni-balance/utils/provider/dex/uniswap/configs" + uniswapUtils "omni-balance/utils/provider/dex/uniswap/utils" + "omni-balance/utils/wallets" +) + +type BuildTxParams struct { + TokenIn, TokenOut configs.Token + Chain configs.Chain + Sender wallets.Wallets + Quote uniswapUtils.Quote + Deadline *big.Int + Client simulated.Client + Amount decimal.Decimal +} + +func (u *Uniswap) GetTokenExactOutputQuote(ctx context.Context, chainName string, tokenIn, tokenOut configs.Token, + sender common.Address, amount decimal.Decimal) (uniswapUtils.Quote, error) { + var tokenInAddress, tokenOutAddress = tokenIn.ContractAddress, tokenOut.ContractAddress + if u.conf.IsNativeToken(chainName, tokenIn.Name) { + tokenInAddress = tokenIn.Name + } + if u.conf.IsNativeToken(chainName, tokenOut.Name) { + tokenOutAddress = tokenOut.Name + } + + return uniswapUtils.GetTokenExactOutputQuote(ctx, uniswapUtils.GetTokenQuoteParams{ + ChainName: chainName, + TokenIn: tokenInAddress, + TokenOut: tokenOutAddress, + Amount: amount, + Sender: sender, + }) +} + +func (u *Uniswap) BuildTx(ctx context.Context, args BuildTxParams) ([]byte, error) { + var ( + isTokenInNative = u.conf.IsNativeToken(args.Chain.Name, args.TokenIn.Name) + isTokenOutNative = u.conf.IsNativeToken(args.Chain.Name, args.TokenOut.Name) + chainId = int64(args.Chain.Id) + wallet = args.Sender + contract = uniswapConfigs.GetContractAddress(args.Chain.Name) + ) + universalRouterExecute := new(uniswapUtils.Execute) + if isTokenInNative { + universalRouterExecute = universalRouterExecute.WrapEth(uniswapConfigs.WETH_RECIPIENT_ADDRESS, + decimal.RequireFromString(args.Quote.Quote.Route[0][0].AmountIn).BigInt(), true) + } + + if args.Quote.Quote.PermitData.Domain.ChainId != 0 && !isTokenInNative { + p, err := permit2.NewPermit2(contract.Permit2, args.Client) + if err != nil { + return nil, errors.Wrap(err, "permit2") + } + allowance, err := p.Allowance( + nil, wallet.GetAddress(true), common.HexToAddress(args.TokenIn.ContractAddress), + contract.UniversalRouter) + if err != nil { + return nil, errors.Wrap(err, "permit2 allowance") + } + if allowance.Amount.Cmp(decimal.RequireFromString(args.Quote.Quote.Quote).BigInt()) == -1 { + universalRouterExecute = universalRouterExecute.Permit2Permit(uniswapUtils.PermitSingle{ + Details: uniswapUtils.PermitDetails{ + Token: common.HexToAddress(args.TokenIn.ContractAddress), + Amount: decimal.RequireFromString(args.Quote.Quote.Quote).Mul(decimal.NewFromInt(2)).BigInt(), + Expiration: big.NewInt(args.Deadline.Int64() + 1*24*60*60), + Nonce: allowance.Nonce, + }, + Spender: contract.UniversalRouter, + SigDeadline: big.NewInt(args.Deadline.Int64() + 1*24*60*60), + VerifyingContract: contract.Permit2, + ChainId: math.NewHexOrDecimal256(chainId), + }, wallet.SignRawMessage) + } + } + + var routerPool = make(map[string][]uniswapUtils.Route) + for index, routers := range args.Quote.Quote.Route { + for routerIndex, v := range routers { + routerPool[v.Type] = append(routerPool[v.Type], args.Quote.Quote.Route[index][routerIndex]) + } + } + for poolType, routers := range routerPool { + var paths uniswapUtils.Paths + for _, router := range routers { + p := &uniswapUtils.Path{ + TokenIn: common.HexToAddress(router.TokenIn.Address), + TokenOut: common.HexToAddress(router.TokenOut.Address), + } + if poolType == uniswapConfigs.V3Pool { + p.Fee = decimal.RequireFromString(router.Fee).IntPart() + } + paths = append(paths, *p) + } + switch poolType { + case uniswapConfigs.V3Pool: + universalRouterExecute = universalRouterExecute.V3SwapExactOut( + uniswapConfigs.WETH_RECIPIENT_ADDRESS, + decimal.RequireFromString(routers[len(routers)-1].AmountOut).BigInt(), + decimal.RequireFromString(routers[0].AmountIn).BigInt(), + paths, + !isTokenInNative, false, + ) + case uniswapConfigs.V2Pool: + universalRouterExecute = universalRouterExecute.V2SwapExactOut( + uniswapConfigs.WETH_RECIPIENT_ADDRESS, + decimal.RequireFromString(routers[len(routers)-1].AmountOut).BigInt(), + decimal.RequireFromString(routers[0].AmountIn).BigInt(), + paths, + !isTokenInNative, false, + ) + } + } + if !isTokenOutNative { + universalRouterExecute = universalRouterExecute.Sweep( + common.HexToAddress(args.TokenOut.ContractAddress), + uniswapConfigs.UNWRAP_WETH_RECIPIENT_ADDRESS, + decimal.RequireFromString(args.Quote.Quote.Amount).BigInt(), + true, + ) + } + + if isTokenInNative { + universalRouterExecute = universalRouterExecute.UnwrapWEth( + uniswapConfigs.UNWRAP_WETH_RECIPIENT_ADDRESS, + big.NewInt(0), + true, + ) + } + if isTokenOutNative { + universalRouterExecute = universalRouterExecute.UnwrapWEth( + uniswapConfigs.UNWRAP_WETH_RECIPIENT_ADDRESS, + chains.EthToWei(args.Amount, args.TokenIn.Decimals), + true, + ) + } + return universalRouterExecute.Build(args.Deadline) +} + +func (u *Uniswap) GetTokenIns(ctx context.Context, chainName, tokenOutName string, wallet common.Address, + tokenOutAmount decimal.Decimal) (tokenInCosts provider.TokenInCosts, err error) { + + tokenOut := u.conf.GetTokenInfoOnChain(tokenOutName, chainName) + chain := u.conf.GetChainConfig(chainName) + client, err := chains.NewTryClient(ctx, chain.RpcEndpoints) + if err != nil { + logrus.Warnf("get %s chain client error: %s", chainName, err) + return + } + defer client.Close() + for _, v := range u.conf.GetSourceTokenNamesByChain(chainName) { + tokenIn := u.conf.GetTokenInfoOnChain(v, chainName) + result, err := u.GetTokenExactOutputQuote( + ctx, + chainName, + tokenIn, + tokenOut, + wallet, + decimal.NewFromBigInt(chains.EthToWei(tokenOutAmount, tokenOut.Decimals), 0)) + if errors.Is(err, error_types.ErrInsufficientLiquidity) { + continue + } + if err != nil { + logrus.Warnf("get quote error: %s", err) + continue + } + + tokenInBalance, err := chains.GetTokenBalance(ctx, client, tokenIn.ContractAddress, wallet.Hex(), tokenIn.Decimals) + if err != nil { + logrus.Warnf("get balance error: %s", err) + continue + } + if tokenInBalance.Cmp(decimal.RequireFromString(result.Quote.QuoteDecimals)) < 0 { + continue + } + tokenInCosts = append(tokenInCosts, provider.TokenInCost{ + TokenName: v, + CostAmount: decimal.RequireFromString(result.Quote.QuoteDecimals), + }) + } + return tokenInCosts, nil +} diff --git a/utils/provider/dex/uniswap/utils/execute.go b/utils/provider/dex/uniswap/utils/execute.go new file mode 100644 index 0000000..49916a9 --- /dev/null +++ b/utils/provider/dex/uniswap/utils/execute.go @@ -0,0 +1,289 @@ +package utils + +import ( + "bytes" + "fmt" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/signer/core/apitypes" + "github.com/pkg/errors" + "github.com/uniswapv3-go/uniswapv3-universal-router-decoder-go/command" + "math/big" + "omni-balance/utils" + "omni-balance/utils/chains" + "omni-balance/utils/provider/dex/uniswap/abi/v3UniversalRouter" + "strings" +) + +type Paths []Path + +type Path struct { + TokenIn common.Address + Fee int64 + TokenOut common.Address +} + +func (p Paths) ToV2() []common.Address { + var result []common.Address + for index, path := range p { + result = append(result, path.TokenIn) + if index == len(p)-1 { // last need to append tokenOut + result = append(result, path.TokenOut) + continue + } + } + return result +} + +func (p Paths) ToBytes(fnName byte) []byte { + var result = bytes.NewBuffer(nil) + switch fnName { + case command.V3_SWAP_EXACT_OUT, command.V3_SWAP_EXACT_IN: + for index, item := range p { + tokenIn := item.TokenIn.Hex() + tokenOut := item.TokenOut.Hex() + fee := fmt.Sprintf("%06x", item.Fee) + if fnName == command.V3_SWAP_EXACT_OUT { + tokenIn = p[len(p)-index-1].TokenOut.Hex() + tokenOut = p[len(p)-index-1].TokenIn.Hex() + fee = fmt.Sprintf("%06x", p[len(p)-index-1].Fee) + } + result.Write(common.Hex2Bytes(tokenIn[2:])) + result.Write(common.Hex2Bytes(fee)) + if index == len(p)-1 { + result.Write(common.Hex2Bytes(tokenOut[2:])) + continue + } + } + + default: + return nil + } + return result.Bytes() +} + +type Execute struct { + commands []command.Command + errs []error +} + +func (e *Execute) appendCommand(cmd byte, types []string, values ...interface{}) *Execute { + input, err := AbiPack( + types, + values..., + ) + if err != nil { + e.errs = append(e.errs, errors.WithStack(err)) + return e + } + e.commands = append(e.commands, command.Command{ + Command: cmd, + Input: input, + }) + return e +} + +func (e *Execute) lastRevert(isCanRevert ...bool) *Execute { + if len(e.commands) == 0 { + return e + } + if len(isCanRevert) > 0 && isCanRevert[0] { + e.commands[len(e.commands)-1] = command.Command{ + Command: utils.SetBit(e.commands[len(e.commands)-1].Command, 7, true), + Input: e.commands[len(e.commands)-1].Input, + } + } + return e +} + +// UnwrapWEth see https://docs.uniswap.org/contracts/universal-router/technical-reference#unwrap_weth +func (e *Execute) UnwrapWEth(ETHRecipient common.Address, minETHAmount *big.Int, isCanRevert ...bool) *Execute { + return e.appendCommand(command.UNWRAP_WETH, []string{"address", "uint256"}, ETHRecipient, minETHAmount). + lastRevert(isCanRevert...) +} + +// WrapEth see https://docs.uniswap.org/contracts/universal-router/technical-reference#wrap_eth +func (e *Execute) WrapEth(WETHRecipient common.Address, wrapEthAmount *big.Int, isCanRevert ...bool) *Execute { + return e.appendCommand(command.WRAP_ETH, []string{"address", "uint256"}, WETHRecipient, wrapEthAmount). + lastRevert(isCanRevert...) +} + +// Permit2Permit see https://docs.uniswap.org/contracts/universal-router/technical-reference#permit2_permit +func (e *Execute) Permit2Permit(permitSingle PermitSingle, signFn func(msg []byte) (sig []byte, err error), + isCanRevert ...bool) *Execute { + + typedData := apitypes.TypedData{ + Types: apitypes.Types{ + "EIP712Domain": []apitypes.Type{ + {Name: "name", Type: "string"}, + {Name: "chainId", Type: "uint256"}, + {Name: "verifyingContract", Type: "address"}, + }, + "PermitDetails": []apitypes.Type{ + {Name: "token", Type: "address"}, + {Name: "amount", Type: "uint160"}, + {Name: "expiration", Type: "uint48"}, + {Name: "nonce", Type: "uint48"}, + }, + "PermitSingle": []apitypes.Type{ + {Name: "details", Type: "PermitDetails"}, + {Name: "spender", Type: "address"}, + {Name: "sigDeadline", Type: "uint256"}, + }, + }, + PrimaryType: "PermitSingle", + Domain: apitypes.TypedDataDomain{ + Name: "Permit2", + ChainId: permitSingle.ChainId, + VerifyingContract: permitSingle.VerifyingContract.Hex(), + }, + Message: apitypes.TypedDataMessage{ + "details": map[string]interface{}{ + "token": permitSingle.Details.Token.Hex(), + "amount": permitSingle.Details.Amount, + "expiration": permitSingle.Details.Expiration, + "nonce": permitSingle.Details.Nonce, + }, + "spender": permitSingle.Spender.Hex(), + "sigDeadline": permitSingle.SigDeadline, + }, + } + sig, err := chains.SignTypedData(typedData, signFn) + if err != nil { + e.errs = append(e.errs, errors.Wrap(err, "SignTypedData error")) + return e + } + var args = abi.Arguments{ + { + Name: "PermitSingle", + Type: chains.MostNewAbiType("tuple", "", []abi.ArgumentMarshaling{ + {Name: "details", Type: "tuple", Components: []abi.ArgumentMarshaling{ + {Name: "token", Type: "address"}, + {Name: "amount", Type: "uint160"}, + {Name: "expiration", Type: "uint48"}, + {Name: "nonce", Type: "uint48"}, + }}, + {Name: "spender", Type: "address"}, + {Name: "sigDeadline", Type: "uint256"}, + }), + }, + { + Name: "signature", + Type: chains.MostNewAbiType("bytes", "", []abi.ArgumentMarshaling{}), + }, + } + type PermitSingle struct { + Details PermitDetails `json:"details"` + Spender common.Address `json:"spender"` + SigDeadline *big.Int `json:"sigDeadline"` + } + permit := &PermitSingle{ + Details: permitSingle.Details, + Spender: permitSingle.Spender, + SigDeadline: permitSingle.SigDeadline, + } + input, err := args.Pack(permit, sig) + if err != nil { + e.errs = append(e.errs, errors.Wrap(err, "Pack")) + return e + } + e.commands = append(e.commands, command.Command{ + Command: command.PERMIT2_PERMIT, + Input: input, + }) + return e.lastRevert(isCanRevert...) +} + +// V2SwapExactOut see https://docs.uniswap.org/contracts/universal-router/technical-reference#v2_swap_exact_out +func (e *Execute) V2SwapExactOut(recipient common.Address, tokenOutAmount, tokenInMaxAmount *big.Int, path Paths, + isSenderFromPermit2 bool, isCanRevert ...bool) *Execute { + + return e.appendCommand(command.V2_SWAP_EXACT_OUT, []string{"address", "uint256", "uint256", "address[]", "bool"}, + recipient, tokenOutAmount, tokenInMaxAmount, path.ToV2(), isSenderFromPermit2). + lastRevert(isCanRevert...) +} + +// V2SwapExactIn see https://docs.uniswap.org/contracts/universal-router/technical-reference#v2_swap_exact_in +func (e *Execute) V2SwapExactIn(recipient common.Address, tokenInAmount, tokenInMinAmount *big.Int, path Paths, + isSenderFromPermit2 bool, isCanRevert ...bool) *Execute { + return e.appendCommand(command.V2_SWAP_EXACT_IN, []string{"address", "uint256", "uint256", "bytes", "bool"}, + recipient, tokenInAmount, tokenInMinAmount, path.ToV2(), isSenderFromPermit2). + lastRevert(isCanRevert...) +} + +// PayPortion see https://docs.uniswap.org/contracts/universal-router/technical-reference#pay_portion +func (e *Execute) PayPortion(token, recipient common.Address, amount *big.Int, isCanRevert ...bool) *Execute { + return e.appendCommand(command.PAY_PORTION, []string{"address", "address", "uint256"}, token, recipient, amount). + lastRevert(isCanRevert...) +} + +// Transfer see https://docs.uniswap.org/contracts/universal-router/technical-reference#transfer +func (e *Execute) Transfer(token, recipient common.Address, amount *big.Int, isCanRevert ...bool) *Execute { + return e.appendCommand(command.TRANSFER, []string{"address", "address", "uint256"}, token, recipient, amount). + lastRevert(isCanRevert...) +} + +// Sweep see https://docs.uniswap.org/contracts/universal-router/technical-reference#sweep +func (e *Execute) Sweep(token, recipient common.Address, tokenMinAmount *big.Int, isCanRevert ...bool) *Execute { + return e.appendCommand(command.SWEEP, []string{"address", "address", "uint256"}, token, recipient, tokenMinAmount). + lastRevert(isCanRevert...) +} + +// Permit2TransferFrom see https://docs.uniswap.org/contracts/universal-router/technical-reference#permit2_transfer_from +func (e *Execute) Permit2TransferFrom(fromPermit2Token, recipient common.Address, amount *big.Int, + isCanRevert ...bool) *Execute { + + return e.appendCommand(command.PERMIT2_TRANSFER_FROM, + []string{"address", "address", "uint256"}, fromPermit2Token, recipient, amount).lastRevert(isCanRevert...) +} + +// V3SwapExactOut see https://docs.uniswap.org/contracts/universal-router/technical-reference#v3_swap_exact_out +func (e *Execute) V3SwapExactOut(recipient common.Address, tokenOutAmountWei, tokenInMaxAmountWei *big.Int, path Paths, + isSenderFromPermit2 bool, isCanRevert ...bool) *Execute { + + return e.appendCommand(command.V3_SWAP_EXACT_OUT, []string{"address", "uint256", "uint256", "bytes", "bool"}, + recipient, tokenOutAmountWei, tokenInMaxAmountWei, path.ToBytes(command.V3_SWAP_EXACT_OUT), isSenderFromPermit2). + lastRevert(isCanRevert...) +} + +// V3SwapExactIn see https://docs.uniswap.org/contracts/universal-router/technical-reference#v3_swap_exact_in +func (e *Execute) V3SwapExactIn(recipient common.Address, tokenInAmountWei, tokenOutMinAmountWei *big.Int, path Paths, + isSenderFromPermit2 bool, isCanRevert ...bool) *Execute { + + return e.appendCommand(command.V3_SWAP_EXACT_IN, []string{"address", "uint256", "uint256", "bytes", "bool"}, + recipient, tokenInAmountWei, tokenOutMinAmountWei, path.ToBytes(command.V3_SWAP_EXACT_IN), isSenderFromPermit2). + lastRevert(isCanRevert...) +} + +func (e *Execute) Error() error { + var errs []string + for _, err := range e.errs { + errs = append(errs, err.Error()) + } + if len(errs) == 0 { + return nil + } + return fmt.Errorf(strings.Join(errs, "\n")) +} + +func (e *Execute) Build(deadline *big.Int) ([]byte, error) { + if err := e.Error(); err != nil { + return nil, errors.Wrap(err, "processing commands") + } + var ( + // 2 unused bytes, reserved for future use. Leaving these 2 bits as 0 will save gas, + // but any value passed into the contract will be ignored. + // Later versions of the UniversalRouter will likely expand the 5 bits used for command to use at least 1 of these bits. + commands = make([]byte, 0) + inputs [][]byte + ) + for _, v := range e.commands { + commands = append(commands, v.Command) + inputs = append(inputs, utils.ZFillByte(v.Input, 64)) + } + abiObj, err := v3UniversalRouter.V3UniversalRouterMetaData.GetAbi() + if err != nil { + return nil, err + } + return abiObj.Pack("execute0", commands, inputs, deadline) +} diff --git a/utils/provider/dex/uniswap/utils/execute_test.go b/utils/provider/dex/uniswap/utils/execute_test.go new file mode 100644 index 0000000..670c1cd --- /dev/null +++ b/utils/provider/dex/uniswap/utils/execute_test.go @@ -0,0 +1,199 @@ +package utils + +import ( + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/math" + "github.com/shopspring/decimal" + "github.com/stretchr/testify/assert" + "github.com/uniswapv3-go/uniswapv3-universal-router-decoder-go/command" + "math/big" + "omni-balance/utils/constant" + "omni-balance/utils/wallets" + "testing" +) + +func TestExecute_BuildV3SwapExactInParams(t *testing.T) { + type fields struct { + commands []command.Command + } + type args struct { + recipient common.Address + tokenInAmountWei *big.Int + tokenOutMinAmountWei *big.Int + path Paths + isSenderFromPermit2 bool + } + tests := []struct { + name string + fields fields + args args + want string + wantErr bool + }{ + { + name: "test1", + fields: fields{}, + args: args{ + recipient: common.HexToAddress("0x0000000000000000000000000000000000000002"), + tokenInAmountWei: big.NewInt(28000000000000000), + tokenOutMinAmountWei: big.NewInt(85696421), + path: Paths{ + { + TokenIn: common.HexToAddress("0x82af49447d8a07e3bd95bd0d56f35241523fbab1"), + Fee: 500, + TokenOut: common.HexToAddress("0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"), + }, + }, + isSenderFromPermit2: false, + }, + + want: "3593564c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000006647713d000000000000000000000000000000000000000000000000000000000000000180000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000006379da05b6000000000000000000000000000000000000000000000000000000000000051b9fa500000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002b82af49447d8a07e3bd95bd0d56f35241523fbab10001f4fd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9000000000000000000000000000000000000000000", + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + e := &Execute{ + commands: tt.fields.commands, + } + e = e.V3SwapExactIn(tt.args.recipient, tt.args.tokenInAmountWei, tt.args.tokenOutMinAmountWei, tt.args.path, tt.args.isSenderFromPermit2, true) + got, err := e.Build(big.NewInt(1715958077)) + if (err != nil) != tt.wantErr { + t.Errorf("V3SwapExactIn() error = %v, wantErr %v", err, tt.wantErr) + return + } + assert.Equal(t, tt.want, common.Bytes2Hex(got)) + }) + } +} + +func TestExecute_Build(t *testing.T) { + var ( + // https://arbiscan.io/tx/0x14bfc7289c16e4b1075a6bc6814b4b69042dd4d69b984525ca7a58af30954853 + want = "3593564c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000066483eed00000000000000000000000000000000000000000000000000000000000000050a00000604000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000500000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000002200000000000000000000000000000000000000000000000000000000000000340000000000000000000000000000000000000000000000000000000000000048000000000000000000000000000000000000000000000000000000000000005000000000000000000000000000000000000000000000000000000000000000160000000000000000000000000912ce59144191c1204e64559fe8253a0e49e6548000000000000000000000000ffffffffffffffffffffffffffffffffffffffff00000000000000000000000000000000000000000000000000000000666fcabe00000000000000000000000000000000000000000000000000000000000000000000000000000000000000005e325eda8064b456f4781070c0738d849c82425800000000000000000000000000000000000000000000000000000000664844c600000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000004132f5e06e6caa8d92713f346579eecd6fe4c716cc8024ba8d19d7497b7cc20972707b31289642b5f86c42d707e11bf33b7cc8d7897f3d344fecd113d1ea673c0b1c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000020cc1b7615165a9bf0000000000000000000000000000000000000000000000000000000002493cbd100000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002b912ce59144191c1204e64559fe8253a0e49e65480001f4af88d065e77c8cc2239327c5edb3a432268e58310000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000aeeb3d20707738950000000000000000000000000000000000000000000000000000000000c3071a600000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000042912ce59144191c1204e64559fe8253a0e49e65480001f482af49447d8a07e3bd95bd0d56f35241523fbab10001f4af88d065e77c8cc2239327c5edb3a432268e58310000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000060000000000000000000000000af88d065e77c8cc2239327c5edb3a432268e58310000000000000000000000007ffc3dbf3b2b50ff3a1d5523bc24bb5043837b1400000000000000000000000000000000000000000000000000000000000000190000000000000000000000000000000000000000000000000000000000000060000000000000000000000000af88d065e77c8cc2239327c5edb3a432268e583100000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000030c43d78" + ) + wallet := wallets.NewWallets(wallets.WalletConfig{ + PrivateKey: constant.TestPrivateKey, + Address: common.HexToAddress(constant.TestWalletAddress), + }) + e := new(Execute) + inputData, err := e.Permit2Permit( + PermitSingle{ + SigDeadline: big.NewInt(1716012230), + Details: PermitDetails{ + Token: common.HexToAddress("0x912ce59144191c1204e64559fe8253a0e49e6548"), + Amount: decimal.RequireFromString("1461501637330902918203684832716283019655932542975").BigInt(), + Expiration: big.NewInt(1718602430), + Nonce: big.NewInt(0), + }, + Spender: common.HexToAddress("0x5E325eDA8064b456f4781070C0738d849c824258"), + VerifyingContract: common.HexToAddress("0x0000000000000000000000000000000000000002"), + ChainId: math.NewHexOrDecimal256(1), + }, + wallet.SignRawMessage, + ).V3SwapExactIn( + common.HexToAddress("0x0000000000000000000000000000000000000002"), + decimal.RequireFromString("605003289199755566064").BigInt(), + decimal.RequireFromString("613665745").BigInt(), + Paths{ + { + Fee: 500, + TokenIn: common.HexToAddress("0x912CE59144191C1204E64559FE8253a0e49E6548"), + TokenOut: common.HexToAddress("0xaf88d065e77c8cC2239327C5EDb3A432268e5831"), + }, + }, true, + ).V3SwapExactIn( + common.HexToAddress("0x0000000000000000000000000000000000000002"), + decimal.RequireFromString("201667763066585188688").BigInt(), + decimal.RequireFromString("204501414").BigInt(), + Paths{ + { + Fee: 500, + TokenIn: common.HexToAddress("0x912CE59144191C1204E64559FE8253a0e49E6548"), + TokenOut: common.HexToAddress("0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"), + }, + { + Fee: 500, + TokenIn: common.HexToAddress("0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"), + TokenOut: common.HexToAddress("0xaf88d065e77c8cC2239327C5EDb3A432268e5831"), + }, + }, true, + ).PayPortion( + common.HexToAddress("0xaf88d065e77c8cC2239327C5EDb3A432268e5831"), + common.HexToAddress("0x7FFC3DBF3B2b50Ff3A1D5523bc24Bb5043837B14"), + decimal.RequireFromString("25").BigInt(), false, + ).Sweep( + common.HexToAddress("0xaf88d065e77c8cC2239327C5EDb3A432268e5831"), + common.HexToAddress("0x0000000000000000000000000000000000000001"), + decimal.RequireFromString("818167160").BigInt(), false, + ).Build( + big.NewInt(1716010733), + ) + assert.NoError(t, err) + assert.Equal(t, want, common.Bytes2Hex(inputData)) +} + +func TestPaths_ToBytes(t *testing.T) { + type args struct { + fnName byte + } + tests := []struct { + name string + p Paths + args args + want []byte + }{ + { + name: "V3_SWAP_EXACT_IN", + p: Paths{ + { + Fee: 500, + TokenIn: common.HexToAddress("0x3E29793C9BdEB6ce5A84C2BEceD91AD50c530b16"), + TokenOut: common.HexToAddress("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"), + }, + }, + args: args{ + fnName: command.V3_SWAP_EXACT_IN, + }, + want: common.Hex2Bytes("3E29793C9BdEB6ce5A84C2BEceD91AD50c530b160001f4C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"), + }, + { + name: "V3_SWAP_EXACT_OUT", + p: Paths{ + { + Fee: 500, + TokenIn: common.HexToAddress("0x3E29793C9BdEB6ce5A84C2BEceD91AD50c530b16"), + TokenOut: common.HexToAddress("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"), + }, + }, + args: args{ + fnName: command.V3_SWAP_EXACT_OUT, + }, + want: common.Hex2Bytes("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc20001f43E29793C9BdEB6ce5A84C2BEceD91AD50c530b16"), + }, + { + name: "V3_SWAP_EXACT_OUT", + p: Paths{ + { + Fee: 500, + TokenIn: common.HexToAddress("0x3E29793C9BdEB6ce5A84C2BEceD91AD50c530b16"), + TokenOut: common.HexToAddress("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"), + }, + { + Fee: 300, + TokenIn: common.HexToAddress("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"), + TokenOut: common.HexToAddress("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc4"), + }, + }, + args: args{ + fnName: command.V3_SWAP_EXACT_OUT, + }, + want: common.Hex2Bytes("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc400012cC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc20001f43E29793C9BdEB6ce5A84C2BEceD91AD50c530b16"), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equalf(t, common.Bytes2Hex(tt.want), common.Bytes2Hex(tt.p.ToBytes(tt.args.fnName)), "ToBytes(%v)", tt.args.fnName) + }) + } +} diff --git a/utils/provider/dex/uniswap/utils/permit2.go b/utils/provider/dex/uniswap/utils/permit2.go new file mode 100644 index 0000000..32fcdfd --- /dev/null +++ b/utils/provider/dex/uniswap/utils/permit2.go @@ -0,0 +1,22 @@ +package utils + +import ( + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/math" + "math/big" +) + +type PermitSingle struct { + Details PermitDetails `json:"details"` + Spender common.Address `json:"spender"` + SigDeadline *big.Int `json:"sig_deadline"` + VerifyingContract common.Address `json:"verifying_contract"` + ChainId *math.HexOrDecimal256 `json:"chain_id"` +} + +type PermitDetails struct { + Token common.Address `json:"token"` + Amount *big.Int `json:"amount"` + Expiration *big.Int `json:"expiration"` + Nonce *big.Int `json:"nonce"` +} diff --git a/utils/provider/dex/uniswap/utils/utils.go b/utils/provider/dex/uniswap/utils/utils.go new file mode 100644 index 0000000..6299157 --- /dev/null +++ b/utils/provider/dex/uniswap/utils/utils.go @@ -0,0 +1,339 @@ +package utils + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/common" + "github.com/shopspring/decimal" + "io" + "net/http" + "omni-balance/utils/chains" + "omni-balance/utils/constant" + "omni-balance/utils/error_types" +) + +type GetTokenQuoteParams struct { + ChainName string + TokenIn string + TokenOut string + // wei + Amount decimal.Decimal + Sender common.Address +} + +type TokenQuote struct { + TokenInChainId int `json:"tokenInChainId"` + TokenIn string `json:"tokenIn"` + TokenOutChainId int `json:"tokenOutChainId"` + TokenOut string `json:"tokenOut"` + Amount string `json:"amount"` + SendPortionEnabled bool `json:"sendPortionEnabled"` + Type string `json:"type"` + Intent string `json:"intent"` + Configs []TokenQuoteConfig `json:"configs"` + UseUniswapX bool `json:"useUniswapX"` + Swapper string `json:"swapper"` +} + +type TokenQuoteConfig struct { + UseSyntheticQuotes bool `json:"useSyntheticQuotes,omitempty"` + Swapper string `json:"swapper,omitempty"` + RoutingType string `json:"routingType"` + EnableUniversalRouter bool `json:"enableUniversalRouter,omitempty"` + Protocols []string `json:"protocols,omitempty"` + Recipient string `json:"recipient,omitempty"` + EnableFeeOnTransferFeeFetching bool `json:"enableFeeOnTransferFeeFetching,omitempty"` +} + +type Quote struct { + Routing string `json:"routing"` + Quote struct { + MethodParameters struct { + Calldata string `json:"calldata"` + Value string `json:"value"` + To string `json:"to"` + } `json:"methodParameters"` + BlockNumber string `json:"blockNumber"` + Amount string `json:"amount"` + AmountDecimals string `json:"amountDecimals"` + Quote string `json:"quote"` + QuoteDecimals string `json:"quoteDecimals"` + QuoteGasAdjusted string `json:"quoteGasAdjusted"` + QuoteGasAdjustedDecimals string `json:"quoteGasAdjustedDecimals"` + QuoteGasAndPortionAdjusted string `json:"quoteGasAndPortionAdjusted"` + QuoteGasAndPortionAdjustedDecimals string `json:"quoteGasAndPortionAdjustedDecimals"` + GasUseEstimateQuote string `json:"gasUseEstimateQuote"` + GasUseEstimateQuoteDecimals string `json:"gasUseEstimateQuoteDecimals"` + GasUseEstimate string `json:"gasUseEstimate"` + GasUseEstimateUSD string `json:"gasUseEstimateUSD"` + SimulationStatus string `json:"simulationStatus"` + SimulationError bool `json:"simulationError"` + GasPriceWei string `json:"gasPriceWei"` + Route [][]Route `json:"route"` + RouteString string `json:"routeString"` + QuoteId string `json:"quoteId"` + HitsCachedRoutes bool `json:"hitsCachedRoutes"` + PortionBips int `json:"portionBips"` + PortionRecipient string `json:"portionRecipient"` + PortionAmount string `json:"portionAmount"` + PortionAmountDecimals string `json:"portionAmountDecimals"` + RequestId string `json:"requestId"` + PermitData struct { + Domain struct { + Name string `json:"name"` + ChainId int `json:"chainId"` + VerifyingContract string `json:"verifyingContract"` + } `json:"domain"` + Types struct { + PermitSingle []struct { + Name string `json:"name"` + Type string `json:"type"` + } `json:"PermitSingle"` + PermitDetails []struct { + Name string `json:"name"` + Type string `json:"type"` + } `json:"PermitDetails"` + } `json:"types"` + Values struct { + Details struct { + Token string `json:"token"` + Amount string `json:"amount"` + Expiration string `json:"expiration"` + Nonce string `json:"nonce"` + } `json:"details"` + Spender string `json:"spender"` + SigDeadline string `json:"sigDeadline"` + } `json:"values"` + } `json:"permitData"` + TradeType string `json:"tradeType"` + Slippage float64 `json:"slippage"` + } `json:"quote"` + RequestId string `json:"requestId"` + AllQuotes []struct { + Routing string `json:"routing"` + Quote struct { + MethodParameters struct { + Calldata string `json:"calldata"` + Value string `json:"value"` + To string `json:"to"` + } `json:"methodParameters"` + BlockNumber string `json:"blockNumber"` + Amount string `json:"amount"` + AmountDecimals string `json:"amountDecimals"` + Quote string `json:"quote"` + QuoteDecimals string `json:"quoteDecimals"` + QuoteGasAdjusted string `json:"quoteGasAdjusted"` + QuoteGasAdjustedDecimals string `json:"quoteGasAdjustedDecimals"` + QuoteGasAndPortionAdjusted string `json:"quoteGasAndPortionAdjusted"` + QuoteGasAndPortionAdjustedDecimals string `json:"quoteGasAndPortionAdjustedDecimals"` + GasUseEstimateQuote string `json:"gasUseEstimateQuote"` + GasUseEstimateQuoteDecimals string `json:"gasUseEstimateQuoteDecimals"` + GasUseEstimate string `json:"gasUseEstimate"` + GasUseEstimateUSD string `json:"gasUseEstimateUSD"` + SimulationStatus string `json:"simulationStatus"` + SimulationError bool `json:"simulationError"` + GasPriceWei string `json:"gasPriceWei"` + Route [][]struct { + Type string `json:"type"` + Address string `json:"address"` + TokenIn struct { + ChainId int `json:"chainId"` + Decimals string `json:"decimals"` + Address string `json:"address"` + Symbol string `json:"symbol"` + BuyFeeBps string `json:"buyFeeBps,omitempty"` + SellFeeBps string `json:"sellFeeBps,omitempty"` + } `json:"tokenIn"` + TokenOut struct { + ChainId int `json:"chainId"` + Decimals string `json:"decimals"` + Address string `json:"address"` + Symbol string `json:"symbol"` + BuyFeeBps string `json:"buyFeeBps,omitempty"` + SellFeeBps string `json:"sellFeeBps,omitempty"` + } `json:"tokenOut"` + Reserve0 struct { + Token struct { + ChainId int `json:"chainId"` + Decimals string `json:"decimals"` + Address string `json:"address"` + Symbol string `json:"symbol"` + BuyFeeBps string `json:"buyFeeBps"` + SellFeeBps string `json:"sellFeeBps"` + } `json:"token"` + Quotient string `json:"quotient"` + } `json:"reserve0"` + Reserve1 struct { + Token struct { + ChainId int `json:"chainId"` + Decimals string `json:"decimals"` + Address string `json:"address"` + Symbol string `json:"symbol"` + } `json:"token"` + Quotient string `json:"quotient"` + } `json:"reserve1"` + AmountIn string `json:"amountIn,omitempty"` + AmountOut string `json:"amountOut,omitempty"` + } `json:"route"` + RouteString string `json:"routeString"` + QuoteId string `json:"quoteId"` + HitsCachedRoutes bool `json:"hitsCachedRoutes"` + PortionBips int `json:"portionBips"` + PortionRecipient string `json:"portionRecipient"` + PortionAmount string `json:"portionAmount"` + PortionAmountDecimals string `json:"portionAmountDecimals"` + RequestId string `json:"requestId"` + PermitData PermitData `json:"permitData"` + TradeType string `json:"tradeType"` + Slippage float64 `json:"slippage"` + } `json:"quote"` + } `json:"allQuotes"` +} + +type Route struct { + Type string `json:"type"` + Address string `json:"address"` + TokenIn struct { + ChainId int `json:"chainId"` + Decimals string `json:"decimals"` + Address string `json:"address"` + Symbol string `json:"symbol"` + BuyFeeBps string `json:"buyFeeBps,omitempty"` + SellFeeBps string `json:"sellFeeBps,omitempty"` + } `json:"tokenIn"` + TokenOut struct { + ChainId int `json:"chainId"` + Decimals string `json:"decimals"` + Address string `json:"address"` + Symbol string `json:"symbol"` + BuyFeeBps string `json:"buyFeeBps,omitempty"` + SellFeeBps string `json:"sellFeeBps,omitempty"` + } `json:"tokenOut"` + Reserve0 struct { + Token struct { + ChainId int `json:"chainId"` + Decimals string `json:"decimals"` + Address string `json:"address"` + Symbol string `json:"symbol"` + BuyFeeBps string `json:"buyFeeBps"` + SellFeeBps string `json:"sellFeeBps"` + } `json:"token"` + Quotient string `json:"quotient"` + } `json:"reserve0"` + Reserve1 struct { + Token struct { + ChainId int `json:"chainId"` + Decimals string `json:"decimals"` + Address string `json:"address"` + Symbol string `json:"symbol"` + } `json:"token"` + Quotient string `json:"quotient"` + } `json:"reserve1"` + Fee string `json:"fee"` + SqrtRatioX96 string `json:"sqrtRatioX96,omitempty"` + AmountIn string `json:"amountIn,omitempty"` + AmountOut string `json:"amountOut,omitempty"` +} + +type PermitData struct { + Domain struct { + Name string `json:"name"` + ChainId int `json:"chainId"` + VerifyingContract string `json:"verifyingContract"` + } `json:"domain"` + Types struct { + PermitSingle []struct { + Name string `json:"name"` + Type string `json:"type"` + } `json:"PermitSingle"` + PermitDetails []struct { + Name string `json:"name"` + Type string `json:"type"` + } `json:"PermitDetails"` + } `json:"types"` + Values struct { + Details struct { + Token string `json:"token"` + Amount string `json:"amount"` + Expiration string `json:"expiration"` + Nonce string `json:"nonce"` + } `json:"details"` + Spender string `json:"spender"` + SigDeadline string `json:"sigDeadline"` + } `json:"values"` +} + +func GetTokenExactOutputQuote(ctx context.Context, args GetTokenQuoteParams) (Quote, error) { + chainId := constant.GetChainId(args.ChainName) + body, err := json.Marshal(TokenQuote{ + TokenInChainId: chainId, + TokenIn: args.TokenIn, + TokenOutChainId: chainId, + TokenOut: args.TokenOut, + Amount: args.Amount.String(), + SendPortionEnabled: true, + Type: "EXACT_OUTPUT", + Intent: "quote", + Configs: []TokenQuoteConfig{ + { + RoutingType: "DUTCH_LIMIT", + Swapper: args.Sender.Hex(), + }, + { + EnableFeeOnTransferFeeFetching: true, + EnableUniversalRouter: true, + Protocols: []string{"V2", "V3", "MIXED"}, + Recipient: args.Sender.Hex(), + RoutingType: "CLASSIC", + }, + }, + Swapper: args.Sender.Hex(), + }) + if err != nil { + return Quote{}, err + } + req, err := http.NewRequest("POST", "https://interface.gateway.uniswap.org/v2/quote", bytes.NewReader(body)) + if err != nil { + return Quote{}, err + } + req.Header.Set("Content-Type", "application/json") + // must set origin + req.Header.Set("Origin", "https://bafybeidjiiinp4v64dyircmic5w3lti4sj7e6jd37siispbgtytxx37gai.ipfs.dweb.link") + req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36") + resp, err := http.DefaultClient.Do(req) + if err != nil { + return Quote{}, err + } + defer resp.Body.Close() + if resp.StatusCode == 404 { + return Quote{}, error_types.ErrInsufficientLiquidity + } + if resp.StatusCode != 200 { + data, _ := io.ReadAll(resp.Body) + return Quote{}, fmt.Errorf("status code: %d, error: %s", resp.StatusCode, data) + } + var result Quote + if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { + return Quote{}, err + } + return result, nil +} + +func AbiPack(types []string, values ...interface{}) ([]byte, error) { + if len(types) != len(values) || len(types) == 0 { + return nil, fmt.Errorf("types and values must be same length") + } + var args abi.Arguments + for _, v := range types { + args = append(args, abi.Argument{ + Type: chains.MostNewAbiType(v, v, nil), + }) + } + if args == nil { + return nil, fmt.Errorf("values must not be empty") + } + return args.Pack(values...) +} diff --git a/utils/provider/init.go b/utils/provider/init.go new file mode 100644 index 0000000..89ecba4 --- /dev/null +++ b/utils/provider/init.go @@ -0,0 +1,77 @@ +package provider + +import ( + "github.com/pkg/errors" + "omni-balance/utils/configs" + "sync" +) + +type InitFunc func(conf configs.Config, noInit ...bool) (Provider, error) + +var ( + providers = make(map[configs.LiquidityProviderType][]InitFunc) + m sync.Mutex +) + +func Register(providerType configs.LiquidityProviderType, provider InitFunc) { + m.Lock() + defer m.Unlock() + providers[providerType] = append(providers[providerType], provider) +} + +func ListProviders() map[configs.LiquidityProviderType][]InitFunc { + var result = make(map[configs.LiquidityProviderType][]InitFunc) + for k, v := range providers { + result[k] = v + } + return result +} + +func ListProvidersByConfig(conf configs.Config) map[configs.LiquidityProviderType][]InitFunc { + m.Lock() + defer m.Unlock() + var ( + providerNames = make(map[string]struct{}) + result = make(map[configs.LiquidityProviderType][]InitFunc) + ) + for _, v := range conf.LiquidityProviders { + providerNames[v.LiquidityName] = struct{}{} + } + for providerType, providerInitFuncs := range providers { + for index, fn := range providerInitFuncs { + p, _ := fn(conf, true) + + if _, ok := providerNames[p.Name()]; !ok { + continue + } + result[providerType] = append(result[providerType], providers[providerType][index]) + } + } + return result +} + +func LiquidityProviderTypeAndConf(providerType configs.LiquidityProviderType, conf configs.Config) []InitFunc { + return ListProvidersByConfig(conf)[providerType] +} + +func GetProvider(providerType configs.LiquidityProviderType, name string) (InitFunc, error) { + for _, fn := range providers[providerType] { + p, err := fn(configs.Config{}, true) + if err != nil { + return nil, err + } + if p.Name() != name { + continue + } + return fn, nil + } + return nil, errors.New("provider not found") +} + +func InitializeBridge(providerInitFunc InitFunc, conf configs.Config, noInit ...bool) (Provider, error) { + bridge, err := providerInitFunc(conf, noInit...) + if err != nil { + return nil, errors.Wrap(err, "init bridge error") + } + return bridge, nil +} diff --git a/utils/provider/provider.go b/utils/provider/provider.go new file mode 100644 index 0000000..50f4b59 --- /dev/null +++ b/utils/provider/provider.go @@ -0,0 +1,279 @@ +package provider + +import ( + "context" + "encoding/json" + "github.com/ethereum/go-ethereum/common" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "omni-balance/utils/configs" + "omni-balance/utils/wallets" +) + +type TxStatus string +type TokenInCosts []TokenInCost + +const ( + TxStatusSuccess TxStatus = "success" + TxStatusFailed TxStatus = "failed" + TxStatusPending TxStatus = "pending" +) + +func (t TxStatus) CanRetry() bool { + return t == TxStatusFailed || t == "" +} +func (t TxStatus) String() string { + return string(t) +} + +func (t TokenInCosts) GetBest() (TokenInCost, error) { + if len(t) == 0 { + return TokenInCost{}, errors.New("no token in costs") + } + var bestPrice = t[0] + for _, v := range t { + if v.CostAmount.LessThan(bestPrice.CostAmount) { + continue + } + bestPrice = v + } + return bestPrice, nil +} + +type TokenInCost struct { + TokenName string + // CostAmount: the amount of token need to paid + CostAmount decimal.Decimal +} + +type Price interface { + GetTokenPriceInUSDT(ctx context.Context, tokenName, chainName, tokenAddress string) (decimal.Decimal, error) +} + +type Provider interface { + + // GetCost calculates the cost of swapping tokens + // Params: + // ctx: context + // args: SwapParams containing the necessary variables for the swap + // + // Returns: + // decimal.Decimal: the cost of the swap + // error: an error if the swap failed to calculate the cost + GetCost(ctx context.Context, args SwapParams) (TokenInCosts, error) + + CheckToken(ctx context.Context, tokenName, tokenInChainName, tokenOutChainName string, amount decimal.Decimal) (bool, error) + + // Swap token, param: + // sourceToken: use this token to exchange + // targetToken: exchange to this token + // targetReceiver: receive target token wallet address + // targetChain: target token chain + // amount: exchange amount + Swap(ctx context.Context, args SwapParams) (result SwapResult, err error) + + // Help get provider help + Help() []string + + // Name get provider name + Name() string + + Type() configs.LiquidityProviderType +} + +type CheckParams struct { + Token string + SourceChains []string + Chain string + Amount decimal.Decimal + Wallet string +} + +type TokenPriceParams struct { + SourceToken string + TargetToken string + TargetChain string + SourceChain string + Sender common.Address +} + +type BalanceParams struct { + Token string + Chain string + Wallet string +} + +type SwapParams struct { + SourceToken string `json:"source_token"` + SourceChain string `json:"source_chain"` + Sender wallets.Wallets `json:"sender"` + TargetToken string `json:"target_token"` + Receiver string `json:"receiver"` + TargetChain string `json:"target_chain"` + Amount decimal.Decimal `json:"amount"` + LastHistory SwapHistory `json:"last_history"` + RecordFn func(s SwapHistory, errs ...error) `json:"-"` +} + +type SwapResult struct { + Error string `json:"error,omitempty"` + TokenInChainName string `json:"source_chain_name,omitempty"` + TokenInName string `json:"token_in_name,omitempty"` + ProviderType configs.LiquidityProviderType `json:"type,omitempty"` + ProviderName string `json:"provider_name,omitempty"` + OrderId string `json:"provider_order_id,omitempty"` + Order interface{} `json:"order,omitempty"` + Status TxStatus `json:"status,omitempty"` + CurrentChain string `json:"current_chain_name,omitempty"` + // Tx is the transaction hash + Tx string `json:"tx,omitempty"` +} + +func (s *SwapResult) SetError(err error) *SwapResult { + s.Error = err.Error() + return s +} +func (s *SwapResult) SetTokenInChainName(name string) *SwapResult { + s.TokenInChainName = name + return s +} + +func (s *SwapResult) SetTokenInName(name string) *SwapResult { + s.TokenInName = name + return s +} + +func (s *SwapResult) SetProviderType(tp configs.LiquidityProviderType) *SwapResult { + s.ProviderType = tp + return s +} + +func (s *SwapResult) SetProviderName(name string) *SwapResult { + s.ProviderName = name + return s +} + +func (s *SwapResult) SetOrderId(id string) *SwapResult { + s.OrderId = id + return s +} + +func (s *SwapResult) SetOrder(order interface{}) *SwapResult { + s.Order = order + return s +} + +func (s *SwapResult) SetStatus(status TxStatus) *SwapResult { + s.Status = status + return s +} + +func (s *SwapResult) SetCurrentChain(name string) *SwapResult { + s.CurrentChain = name + return s +} + +func (s *SwapResult) SetTx(tx string) *SwapResult { + s.Tx = tx + return s +} + +func (s *SwapResult) Out() SwapResult { + return *s +} + +func (s SwapResult) Marshal() map[string]interface{} { + data, _ := json.Marshal(s) + var result = make(map[string]interface{}) + _ = json.Unmarshal(data, &result) + return result +} + +func (s SwapResult) MarshalOrder() *json.RawMessage { + if s.Order == nil { + return nil + } + b, err := json.Marshal(s.Order) + if err != nil { + return nil + } + return (*json.RawMessage)(&b) +} + +func (s SwapParams) GetLogs(name string) *logrus.Entry { + return logrus.WithFields(logrus.Fields{ + "source_token": s.SourceToken, + "source_chain": s.SourceChain, + "sender": s.Sender, + "target_token": s.TargetToken, + "receiver": s.Receiver, + "target_chain": s.TargetChain, + "amount": s.Amount, + "last_history": s.LastHistory, + "name": name, + }) +} + +type SwapHistory struct { + ProviderName string + ProviderType string + Actions string + Status string + CurrentChain string + Amount decimal.Decimal + Tx string `json:"tx"` +} + +func (s *SwapHistory) Out() SwapHistory { + return *s +} + +func (s *SwapHistory) SetProviderName(providerName string) *SwapHistory { + s.ProviderName = providerName + return s +} + +func (s *SwapHistory) SetProviderType(providerType configs.LiquidityProviderType) *SwapHistory { + s.ProviderType = string(providerType) + return s +} + +func (s *SwapHistory) SetActions(actions string) *SwapHistory { + s.Actions = actions + return s +} + +func (s *SwapHistory) SetStatus(status TxStatus) *SwapHistory { + s.Status = status.String() + return s +} + +func (s *SwapHistory) SetCurrentChain(currentChain string) *SwapHistory { + s.CurrentChain = currentChain + return s +} + +func (s *SwapHistory) SetAmount(amount decimal.Decimal) *SwapHistory { + s.Amount = amount + return s +} + +func (s *SwapHistory) SetTx(tx string) *SwapHistory { + s.Tx = tx + return s +} + +func (s SwapParams) Clone() SwapParams { + return SwapParams{ + SourceToken: s.SourceToken, + SourceChain: s.SourceChain, + Sender: s.Sender, + TargetToken: s.TargetToken, + Receiver: s.Receiver, + TargetChain: s.TargetChain, + Amount: s.Amount, + LastHistory: s.LastHistory, + RecordFn: s.RecordFn, + } +} diff --git a/utils/provider/utils.go b/utils/provider/utils.go new file mode 100644 index 0000000..137ec68 --- /dev/null +++ b/utils/provider/utils.go @@ -0,0 +1,161 @@ +package provider + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethclient/simulated" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "omni-balance/utils" + "omni-balance/utils/chains" + "omni-balance/utils/configs" +) + +var ( + transferSent = "transferSent" + transferReceived = "transferReceived" +) + +func action2Int(action string) int { + switch action { + case transferSent: + return 0 + case transferReceived: + return 1 + default: + return -1 + } +} + +func Transfer(ctx context.Context, conf configs.Config, args SwapParams, client simulated.Client) (SwapResult, error) { + + var ( + log = utils.GetLogFromCtx(ctx) + last = args.LastHistory + actionNumber = action2Int(args.LastHistory.Actions) + token = conf.GetTokenInfoOnChain(args.TargetToken, args.TargetChain) + result = &SwapResult{ + TokenInChainName: args.TargetChain, + ProviderType: "direct", + TokenInName: args.TargetToken, + ProviderName: "transfer", + CurrentChain: args.TargetChain, + } + recordFn = func(s SwapHistory, errs ...error) { + s.ProviderType = string(result.ProviderType) + s.ProviderName = result.ProviderName + s.Amount = args.Amount + s.CurrentChain = args.TargetChain + args.RecordFn(s, errs...) + } + ) + + log = log.WithFields(logrus.Fields{ + "last": last, + }) + if !utils.InArray(args.LastHistory.Actions, []string{transferSent, transferReceived}) { + actionNumber = 0 + args.LastHistory.Status = "" + log.Debugf("last transfer not found, reinitializing") + } + + var txHash = last.Tx + if actionNumber < 1 && args.LastHistory.Status != TxStatusSuccess.String() { + transaction, err := chains.BuildSendToken(ctx, chains.SendTokenParams{ + Client: client, + Sender: args.Sender.GetAddress(true), + GetBalance: args.Sender.GetBalance, + TokenAddress: common.HexToAddress(token.ContractAddress), + ToAddress: args.Sender.GetAddress(), + AmountWei: decimal.NewFromBigInt(chains.EthToWei(args.Amount, token.Decimals), 0), + }) + + if err != nil { + return *result, errors.Wrap(err, "send token error") + } + log.Debugf("%s transfer %s %s to %s", args.Sender.GetAddress(true), args.TargetToken, + args.Amount, args.Sender.GetAddress()) + recordFn(SwapHistory{ + Actions: transferSent, + Status: TxStatusPending.String(), + }) + tx, err := args.Sender.SendTransaction(ctx, transaction, client) + if err != nil { + recordFn(SwapHistory{ + Actions: transferSent, + Status: TxStatusFailed.String(), + }) + return *result, errors.Wrap(err, "send transaction error") + } + recordFn(SwapHistory{ + Actions: transferSent, + Status: TxStatusSuccess.String(), + Tx: tx.Hex(), + }) + txHash = tx.Hex() + } + + if txHash == "" { + return *result, errors.New("tx is empty") + } + log.Debugf("waiting for tx %s", txHash) + err := args.Sender.WaitTransaction(ctx, common.HexToHash(txHash), client) + if err != nil { + recordFn(SwapHistory{ + Actions: transferReceived, + Status: TxStatusFailed.String(), + Tx: txHash, + }) + return *result, errors.Wrap(err, "wait for tx error") + } + result.Tx = txHash + result.OrderId = txHash + result.Status = TxStatusSuccess + recordFn(SwapHistory{ + Actions: transferReceived, + Status: TxStatusSuccess.String(), + Tx: txHash, + }) + return *result, nil +} + +type GetTokenCrossChainProvidersParams struct { + SourceChains []string + Conf configs.Config + TokenName string + SourceChain string + TargetChain string + Amount decimal.Decimal +} + +// GetTokenCrossChainProviders retrieves the cross-chain providers for the given token and parameters. +func GetTokenCrossChainProviders(ctx context.Context, args GetTokenCrossChainProvidersParams) (providers []Provider, err error) { + for _, fn := range LiquidityProviderTypeAndConf(configs.Bridge, args.Conf) { + bridge, err := fn(args.Conf) + if err != nil { + continue + } + var hasConfig bool + for _, v := range args.Conf.LiquidityProviders { + if v.Type != configs.Bridge || v.LiquidityName == bridge.Name() { + continue + } + hasConfig = true + break + } + if !hasConfig { + continue + } + ok, err := bridge.CheckToken(ctx, args.TokenName, args.SourceChain, args.TargetChain, args.Amount) + if err != nil { + logrus.Warnf("check token %s in %s to %s failed: %s", args.TokenName, args.SourceChain, args.TargetChain, err) + continue + } + if !ok { + continue + } + providers = append(providers, bridge) + } + return providers, nil +} diff --git a/utils/safe_api/all_transactions_schema.go b/utils/safe_api/all_transactions_schema.go new file mode 100644 index 0000000..201a3b5 --- /dev/null +++ b/utils/safe_api/all_transactions_schema.go @@ -0,0 +1,206 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// AllTransactionsSchema all transactions schema +// +// swagger:model AllTransactionsSchema +type AllTransactionsSchema struct { + + // tx type1 + // Required: true + TxType1 *SafeModuleTransactionWithTransfersResponse `json:"txType1"` + + // tx type2 + // Required: true + TxType2 *SafeMultisigTransactionWithTransfersResponse `json:"txType2"` + + // tx type3 + // Required: true + TxType3 *EthereumTxWithTransfersResponse `json:"txType3"` +} + +// Validate validates this all transactions schema +func (m *AllTransactionsSchema) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateTxType1(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTxType2(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTxType3(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AllTransactionsSchema) validateTxType1(formats strfmt.Registry) error { + + if err := validate.Required("txType1", "body", m.TxType1); err != nil { + return err + } + + if m.TxType1 != nil { + if err := m.TxType1.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("txType1") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("txType1") + } + return err + } + } + + return nil +} + +func (m *AllTransactionsSchema) validateTxType2(formats strfmt.Registry) error { + + if err := validate.Required("txType2", "body", m.TxType2); err != nil { + return err + } + + if m.TxType2 != nil { + if err := m.TxType2.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("txType2") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("txType2") + } + return err + } + } + + return nil +} + +func (m *AllTransactionsSchema) validateTxType3(formats strfmt.Registry) error { + + if err := validate.Required("txType3", "body", m.TxType3); err != nil { + return err + } + + if m.TxType3 != nil { + if err := m.TxType3.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("txType3") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("txType3") + } + return err + } + } + + return nil +} + +// ContextValidate validate this all transactions schema based on the context it is used +func (m *AllTransactionsSchema) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateTxType1(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateTxType2(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateTxType3(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AllTransactionsSchema) contextValidateTxType1(ctx context.Context, formats strfmt.Registry) error { + + if m.TxType1 != nil { + + if err := m.TxType1.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("txType1") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("txType1") + } + return err + } + } + + return nil +} + +func (m *AllTransactionsSchema) contextValidateTxType2(ctx context.Context, formats strfmt.Registry) error { + + if m.TxType2 != nil { + + if err := m.TxType2.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("txType2") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("txType2") + } + return err + } + } + + return nil +} + +func (m *AllTransactionsSchema) contextValidateTxType3(ctx context.Context, formats strfmt.Registry) error { + + if m.TxType3 != nil { + + if err := m.TxType3.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("txType3") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("txType3") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *AllTransactionsSchema) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AllTransactionsSchema) UnmarshalBinary(b []byte) error { + var res AllTransactionsSchema + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/client/about/about_client.go b/utils/safe_api/client/about/about_client.go new file mode 100644 index 0000000..2027cb6 --- /dev/null +++ b/utils/safe_api/client/about/about_client.go @@ -0,0 +1,311 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package about + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// New creates a new about API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +// New creates a new about API client with basic auth credentials. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - user: user for basic authentication header. +// - password: password for basic authentication header. +func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BasicAuth(user, password) + return &Client{transport: transport, formats: strfmt.Default} +} + +// New creates a new about API client with a bearer token for authentication. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - bearerToken: bearer token for Bearer authentication header. +func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) + return &Client{transport: transport, formats: strfmt.Default} +} + +/* +Client for about API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption may be used to customize the behavior of Client methods. +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + V1AboutDeploymentsList(params *V1AboutDeploymentsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1AboutDeploymentsListOK, error) + + V1AboutEthereumRPCList(params *V1AboutEthereumRPCListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1AboutEthereumRPCListOK, error) + + V1AboutEthereumTracingRPCList(params *V1AboutEthereumTracingRPCListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1AboutEthereumTracingRPCListOK, error) + + V1AboutIndexingList(params *V1AboutIndexingListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1AboutIndexingListOK, error) + + V1AboutList(params *V1AboutListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1AboutListOK, error) + + V1AboutSingletonsList(params *V1AboutSingletonsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1AboutSingletonsListOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +V1AboutDeploymentsList Returns a list of safe deployments by version. +*/ +func (a *Client) V1AboutDeploymentsList(params *V1AboutDeploymentsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1AboutDeploymentsListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1AboutDeploymentsListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_about_deployments_list", + Method: "GET", + PathPattern: "/v1/about/deployments/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1AboutDeploymentsListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1AboutDeploymentsListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_about_deployments_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1AboutEthereumRPCList Get information about the Ethereum RPC node used by the service +*/ +func (a *Client) V1AboutEthereumRPCList(params *V1AboutEthereumRPCListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1AboutEthereumRPCListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1AboutEthereumRPCListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_about_ethereum-rpc_list", + Method: "GET", + PathPattern: "/v1/about/ethereum-rpc/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1AboutEthereumRPCListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1AboutEthereumRPCListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_about_ethereum-rpc_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1AboutEthereumTracingRPCList Get information about the Ethereum Tracing RPC node used by the service (if any configured) +*/ +func (a *Client) V1AboutEthereumTracingRPCList(params *V1AboutEthereumTracingRPCListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1AboutEthereumTracingRPCListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1AboutEthereumTracingRPCListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_about_ethereum-tracing-rpc_list", + Method: "GET", + PathPattern: "/v1/about/ethereum-tracing-rpc/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1AboutEthereumTracingRPCListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1AboutEthereumTracingRPCListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_about_ethereum-tracing-rpc_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1AboutIndexingList Get current indexing status for ERC20/721 events +*/ +func (a *Client) V1AboutIndexingList(params *V1AboutIndexingListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1AboutIndexingListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1AboutIndexingListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_about_indexing_list", + Method: "GET", + PathPattern: "/v1/about/indexing/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1AboutIndexingListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1AboutIndexingListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_about_indexing_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1AboutList Returns information and configuration of the service +*/ +func (a *Client) V1AboutList(params *V1AboutListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1AboutListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1AboutListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_about_list", + Method: "GET", + PathPattern: "/v1/about/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1AboutListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1AboutListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_about_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1AboutSingletonsList v1 about singletons list API +*/ +func (a *Client) V1AboutSingletonsList(params *V1AboutSingletonsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1AboutSingletonsListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1AboutSingletonsListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_about_singletons_list", + Method: "GET", + PathPattern: "/v1/about/singletons/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1AboutSingletonsListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1AboutSingletonsListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_about_singletons_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/utils/safe_api/client/about/v1_about_deployments_list_parameters.go b/utils/safe_api/client/about/v1_about_deployments_list_parameters.go new file mode 100644 index 0000000..955f514 --- /dev/null +++ b/utils/safe_api/client/about/v1_about_deployments_list_parameters.go @@ -0,0 +1,197 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package about + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1AboutDeploymentsListParams creates a new V1AboutDeploymentsListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1AboutDeploymentsListParams() *V1AboutDeploymentsListParams { + return &V1AboutDeploymentsListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1AboutDeploymentsListParamsWithTimeout creates a new V1AboutDeploymentsListParams object +// with the ability to set a timeout on a request. +func NewV1AboutDeploymentsListParamsWithTimeout(timeout time.Duration) *V1AboutDeploymentsListParams { + return &V1AboutDeploymentsListParams{ + timeout: timeout, + } +} + +// NewV1AboutDeploymentsListParamsWithContext creates a new V1AboutDeploymentsListParams object +// with the ability to set a context for a request. +func NewV1AboutDeploymentsListParamsWithContext(ctx context.Context) *V1AboutDeploymentsListParams { + return &V1AboutDeploymentsListParams{ + Context: ctx, + } +} + +// NewV1AboutDeploymentsListParamsWithHTTPClient creates a new V1AboutDeploymentsListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1AboutDeploymentsListParamsWithHTTPClient(client *http.Client) *V1AboutDeploymentsListParams { + return &V1AboutDeploymentsListParams{ + HTTPClient: client, + } +} + +/* +V1AboutDeploymentsListParams contains all the parameters to send to the API endpoint + + for the v1 about deployments list operation. + + Typically these are written to a http.Request. +*/ +type V1AboutDeploymentsListParams struct { + + /* Contract. + + Filter by Safe contract name + */ + Contract *string + + /* Version. + + Filter by Safe version + */ + Version *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 about deployments list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1AboutDeploymentsListParams) WithDefaults() *V1AboutDeploymentsListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 about deployments list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1AboutDeploymentsListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 about deployments list params +func (o *V1AboutDeploymentsListParams) WithTimeout(timeout time.Duration) *V1AboutDeploymentsListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 about deployments list params +func (o *V1AboutDeploymentsListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 about deployments list params +func (o *V1AboutDeploymentsListParams) WithContext(ctx context.Context) *V1AboutDeploymentsListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 about deployments list params +func (o *V1AboutDeploymentsListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 about deployments list params +func (o *V1AboutDeploymentsListParams) WithHTTPClient(client *http.Client) *V1AboutDeploymentsListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 about deployments list params +func (o *V1AboutDeploymentsListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithContract adds the contract to the v1 about deployments list params +func (o *V1AboutDeploymentsListParams) WithContract(contract *string) *V1AboutDeploymentsListParams { + o.SetContract(contract) + return o +} + +// SetContract adds the contract to the v1 about deployments list params +func (o *V1AboutDeploymentsListParams) SetContract(contract *string) { + o.Contract = contract +} + +// WithVersion adds the version to the v1 about deployments list params +func (o *V1AboutDeploymentsListParams) WithVersion(version *string) *V1AboutDeploymentsListParams { + o.SetVersion(version) + return o +} + +// SetVersion adds the version to the v1 about deployments list params +func (o *V1AboutDeploymentsListParams) SetVersion(version *string) { + o.Version = version +} + +// WriteToRequest writes these params to a swagger request +func (o *V1AboutDeploymentsListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Contract != nil { + + // query param contract + var qrContract string + + if o.Contract != nil { + qrContract = *o.Contract + } + qContract := qrContract + if qContract != "" { + + if err := r.SetQueryParam("contract", qContract); err != nil { + return err + } + } + } + + if o.Version != nil { + + // query param version + var qrVersion string + + if o.Version != nil { + qrVersion = *o.Version + } + qVersion := qrVersion + if qVersion != "" { + + if err := r.SetQueryParam("version", qVersion); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/about/v1_about_deployments_list_responses.go b/utils/safe_api/client/about/v1_about_deployments_list_responses.go new file mode 100644 index 0000000..9b3105b --- /dev/null +++ b/utils/safe_api/client/about/v1_about_deployments_list_responses.go @@ -0,0 +1,166 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package about + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1AboutDeploymentsListReader is a Reader for the V1AboutDeploymentsList structure. +type V1AboutDeploymentsListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1AboutDeploymentsListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1AboutDeploymentsListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewV1AboutDeploymentsListNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/about/deployments/] v1_about_deployments_list", response, response.Code()) + } +} + +// NewV1AboutDeploymentsListOK creates a V1AboutDeploymentsListOK with default headers values +func NewV1AboutDeploymentsListOK() *V1AboutDeploymentsListOK { + return &V1AboutDeploymentsListOK{} +} + +/* +V1AboutDeploymentsListOK describes a response with status code 200, with default header values. + +V1AboutDeploymentsListOK v1 about deployments list o k +*/ +type V1AboutDeploymentsListOK struct { + Payload []*models.SafeDeployment +} + +// IsSuccess returns true when this v1 about deployments list o k response has a 2xx status code +func (o *V1AboutDeploymentsListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 about deployments list o k response has a 3xx status code +func (o *V1AboutDeploymentsListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 about deployments list o k response has a 4xx status code +func (o *V1AboutDeploymentsListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 about deployments list o k response has a 5xx status code +func (o *V1AboutDeploymentsListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 about deployments list o k response a status code equal to that given +func (o *V1AboutDeploymentsListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 about deployments list o k response +func (o *V1AboutDeploymentsListOK) Code() int { + return 200 +} + +func (o *V1AboutDeploymentsListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/about/deployments/][%d] v1AboutDeploymentsListOK %s", 200, payload) +} + +func (o *V1AboutDeploymentsListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/about/deployments/][%d] v1AboutDeploymentsListOK %s", 200, payload) +} + +func (o *V1AboutDeploymentsListOK) GetPayload() []*models.SafeDeployment { + return o.Payload +} + +func (o *V1AboutDeploymentsListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1AboutDeploymentsListNotFound creates a V1AboutDeploymentsListNotFound with default headers values +func NewV1AboutDeploymentsListNotFound() *V1AboutDeploymentsListNotFound { + return &V1AboutDeploymentsListNotFound{} +} + +/* +V1AboutDeploymentsListNotFound describes a response with status code 404, with default header values. + +Provided version does not exist +*/ +type V1AboutDeploymentsListNotFound struct { +} + +// IsSuccess returns true when this v1 about deployments list not found response has a 2xx status code +func (o *V1AboutDeploymentsListNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 about deployments list not found response has a 3xx status code +func (o *V1AboutDeploymentsListNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 about deployments list not found response has a 4xx status code +func (o *V1AboutDeploymentsListNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 about deployments list not found response has a 5xx status code +func (o *V1AboutDeploymentsListNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 about deployments list not found response a status code equal to that given +func (o *V1AboutDeploymentsListNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 about deployments list not found response +func (o *V1AboutDeploymentsListNotFound) Code() int { + return 404 +} + +func (o *V1AboutDeploymentsListNotFound) Error() string { + return fmt.Sprintf("[GET /v1/about/deployments/][%d] v1AboutDeploymentsListNotFound", 404) +} + +func (o *V1AboutDeploymentsListNotFound) String() string { + return fmt.Sprintf("[GET /v1/about/deployments/][%d] v1AboutDeploymentsListNotFound", 404) +} + +func (o *V1AboutDeploymentsListNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/about/v1_about_ethereum_rpc_list_parameters.go b/utils/safe_api/client/about/v1_about_ethereum_rpc_list_parameters.go new file mode 100644 index 0000000..619dc22 --- /dev/null +++ b/utils/safe_api/client/about/v1_about_ethereum_rpc_list_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package about + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1AboutEthereumRPCListParams creates a new V1AboutEthereumRPCListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1AboutEthereumRPCListParams() *V1AboutEthereumRPCListParams { + return &V1AboutEthereumRPCListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1AboutEthereumRPCListParamsWithTimeout creates a new V1AboutEthereumRPCListParams object +// with the ability to set a timeout on a request. +func NewV1AboutEthereumRPCListParamsWithTimeout(timeout time.Duration) *V1AboutEthereumRPCListParams { + return &V1AboutEthereumRPCListParams{ + timeout: timeout, + } +} + +// NewV1AboutEthereumRPCListParamsWithContext creates a new V1AboutEthereumRPCListParams object +// with the ability to set a context for a request. +func NewV1AboutEthereumRPCListParamsWithContext(ctx context.Context) *V1AboutEthereumRPCListParams { + return &V1AboutEthereumRPCListParams{ + Context: ctx, + } +} + +// NewV1AboutEthereumRPCListParamsWithHTTPClient creates a new V1AboutEthereumRPCListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1AboutEthereumRPCListParamsWithHTTPClient(client *http.Client) *V1AboutEthereumRPCListParams { + return &V1AboutEthereumRPCListParams{ + HTTPClient: client, + } +} + +/* +V1AboutEthereumRPCListParams contains all the parameters to send to the API endpoint + + for the v1 about ethereum rpc list operation. + + Typically these are written to a http.Request. +*/ +type V1AboutEthereumRPCListParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 about ethereum rpc list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1AboutEthereumRPCListParams) WithDefaults() *V1AboutEthereumRPCListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 about ethereum rpc list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1AboutEthereumRPCListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 about ethereum rpc list params +func (o *V1AboutEthereumRPCListParams) WithTimeout(timeout time.Duration) *V1AboutEthereumRPCListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 about ethereum rpc list params +func (o *V1AboutEthereumRPCListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 about ethereum rpc list params +func (o *V1AboutEthereumRPCListParams) WithContext(ctx context.Context) *V1AboutEthereumRPCListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 about ethereum rpc list params +func (o *V1AboutEthereumRPCListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 about ethereum rpc list params +func (o *V1AboutEthereumRPCListParams) WithHTTPClient(client *http.Client) *V1AboutEthereumRPCListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 about ethereum rpc list params +func (o *V1AboutEthereumRPCListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *V1AboutEthereumRPCListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/about/v1_about_ethereum_rpc_list_responses.go b/utils/safe_api/client/about/v1_about_ethereum_rpc_list_responses.go new file mode 100644 index 0000000..48cf6a1 --- /dev/null +++ b/utils/safe_api/client/about/v1_about_ethereum_rpc_list_responses.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package about + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// V1AboutEthereumRPCListReader is a Reader for the V1AboutEthereumRPCList structure. +type V1AboutEthereumRPCListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1AboutEthereumRPCListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1AboutEthereumRPCListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[GET /v1/about/ethereum-rpc/] v1_about_ethereum-rpc_list", response, response.Code()) + } +} + +// NewV1AboutEthereumRPCListOK creates a V1AboutEthereumRPCListOK with default headers values +func NewV1AboutEthereumRPCListOK() *V1AboutEthereumRPCListOK { + return &V1AboutEthereumRPCListOK{} +} + +/* +V1AboutEthereumRPCListOK describes a response with status code 200, with default header values. + +V1AboutEthereumRPCListOK v1 about ethereum Rpc list o k +*/ +type V1AboutEthereumRPCListOK struct { +} + +// IsSuccess returns true when this v1 about ethereum Rpc list o k response has a 2xx status code +func (o *V1AboutEthereumRPCListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 about ethereum Rpc list o k response has a 3xx status code +func (o *V1AboutEthereumRPCListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 about ethereum Rpc list o k response has a 4xx status code +func (o *V1AboutEthereumRPCListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 about ethereum Rpc list o k response has a 5xx status code +func (o *V1AboutEthereumRPCListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 about ethereum Rpc list o k response a status code equal to that given +func (o *V1AboutEthereumRPCListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 about ethereum Rpc list o k response +func (o *V1AboutEthereumRPCListOK) Code() int { + return 200 +} + +func (o *V1AboutEthereumRPCListOK) Error() string { + return fmt.Sprintf("[GET /v1/about/ethereum-rpc/][%d] v1AboutEthereumRpcListOK", 200) +} + +func (o *V1AboutEthereumRPCListOK) String() string { + return fmt.Sprintf("[GET /v1/about/ethereum-rpc/][%d] v1AboutEthereumRpcListOK", 200) +} + +func (o *V1AboutEthereumRPCListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/about/v1_about_ethereum_tracing_rpc_list_parameters.go b/utils/safe_api/client/about/v1_about_ethereum_tracing_rpc_list_parameters.go new file mode 100644 index 0000000..4388d94 --- /dev/null +++ b/utils/safe_api/client/about/v1_about_ethereum_tracing_rpc_list_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package about + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1AboutEthereumTracingRPCListParams creates a new V1AboutEthereumTracingRPCListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1AboutEthereumTracingRPCListParams() *V1AboutEthereumTracingRPCListParams { + return &V1AboutEthereumTracingRPCListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1AboutEthereumTracingRPCListParamsWithTimeout creates a new V1AboutEthereumTracingRPCListParams object +// with the ability to set a timeout on a request. +func NewV1AboutEthereumTracingRPCListParamsWithTimeout(timeout time.Duration) *V1AboutEthereumTracingRPCListParams { + return &V1AboutEthereumTracingRPCListParams{ + timeout: timeout, + } +} + +// NewV1AboutEthereumTracingRPCListParamsWithContext creates a new V1AboutEthereumTracingRPCListParams object +// with the ability to set a context for a request. +func NewV1AboutEthereumTracingRPCListParamsWithContext(ctx context.Context) *V1AboutEthereumTracingRPCListParams { + return &V1AboutEthereumTracingRPCListParams{ + Context: ctx, + } +} + +// NewV1AboutEthereumTracingRPCListParamsWithHTTPClient creates a new V1AboutEthereumTracingRPCListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1AboutEthereumTracingRPCListParamsWithHTTPClient(client *http.Client) *V1AboutEthereumTracingRPCListParams { + return &V1AboutEthereumTracingRPCListParams{ + HTTPClient: client, + } +} + +/* +V1AboutEthereumTracingRPCListParams contains all the parameters to send to the API endpoint + + for the v1 about ethereum tracing rpc list operation. + + Typically these are written to a http.Request. +*/ +type V1AboutEthereumTracingRPCListParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 about ethereum tracing rpc list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1AboutEthereumTracingRPCListParams) WithDefaults() *V1AboutEthereumTracingRPCListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 about ethereum tracing rpc list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1AboutEthereumTracingRPCListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 about ethereum tracing rpc list params +func (o *V1AboutEthereumTracingRPCListParams) WithTimeout(timeout time.Duration) *V1AboutEthereumTracingRPCListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 about ethereum tracing rpc list params +func (o *V1AboutEthereumTracingRPCListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 about ethereum tracing rpc list params +func (o *V1AboutEthereumTracingRPCListParams) WithContext(ctx context.Context) *V1AboutEthereumTracingRPCListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 about ethereum tracing rpc list params +func (o *V1AboutEthereumTracingRPCListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 about ethereum tracing rpc list params +func (o *V1AboutEthereumTracingRPCListParams) WithHTTPClient(client *http.Client) *V1AboutEthereumTracingRPCListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 about ethereum tracing rpc list params +func (o *V1AboutEthereumTracingRPCListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *V1AboutEthereumTracingRPCListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/about/v1_about_ethereum_tracing_rpc_list_responses.go b/utils/safe_api/client/about/v1_about_ethereum_tracing_rpc_list_responses.go new file mode 100644 index 0000000..207f02b --- /dev/null +++ b/utils/safe_api/client/about/v1_about_ethereum_tracing_rpc_list_responses.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package about + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// V1AboutEthereumTracingRPCListReader is a Reader for the V1AboutEthereumTracingRPCList structure. +type V1AboutEthereumTracingRPCListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1AboutEthereumTracingRPCListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1AboutEthereumTracingRPCListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[GET /v1/about/ethereum-tracing-rpc/] v1_about_ethereum-tracing-rpc_list", response, response.Code()) + } +} + +// NewV1AboutEthereumTracingRPCListOK creates a V1AboutEthereumTracingRPCListOK with default headers values +func NewV1AboutEthereumTracingRPCListOK() *V1AboutEthereumTracingRPCListOK { + return &V1AboutEthereumTracingRPCListOK{} +} + +/* +V1AboutEthereumTracingRPCListOK describes a response with status code 200, with default header values. + +V1AboutEthereumTracingRPCListOK v1 about ethereum tracing Rpc list o k +*/ +type V1AboutEthereumTracingRPCListOK struct { +} + +// IsSuccess returns true when this v1 about ethereum tracing Rpc list o k response has a 2xx status code +func (o *V1AboutEthereumTracingRPCListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 about ethereum tracing Rpc list o k response has a 3xx status code +func (o *V1AboutEthereumTracingRPCListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 about ethereum tracing Rpc list o k response has a 4xx status code +func (o *V1AboutEthereumTracingRPCListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 about ethereum tracing Rpc list o k response has a 5xx status code +func (o *V1AboutEthereumTracingRPCListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 about ethereum tracing Rpc list o k response a status code equal to that given +func (o *V1AboutEthereumTracingRPCListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 about ethereum tracing Rpc list o k response +func (o *V1AboutEthereumTracingRPCListOK) Code() int { + return 200 +} + +func (o *V1AboutEthereumTracingRPCListOK) Error() string { + return fmt.Sprintf("[GET /v1/about/ethereum-tracing-rpc/][%d] v1AboutEthereumTracingRpcListOK", 200) +} + +func (o *V1AboutEthereumTracingRPCListOK) String() string { + return fmt.Sprintf("[GET /v1/about/ethereum-tracing-rpc/][%d] v1AboutEthereumTracingRpcListOK", 200) +} + +func (o *V1AboutEthereumTracingRPCListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/about/v1_about_indexing_list_parameters.go b/utils/safe_api/client/about/v1_about_indexing_list_parameters.go new file mode 100644 index 0000000..4af8471 --- /dev/null +++ b/utils/safe_api/client/about/v1_about_indexing_list_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package about + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1AboutIndexingListParams creates a new V1AboutIndexingListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1AboutIndexingListParams() *V1AboutIndexingListParams { + return &V1AboutIndexingListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1AboutIndexingListParamsWithTimeout creates a new V1AboutIndexingListParams object +// with the ability to set a timeout on a request. +func NewV1AboutIndexingListParamsWithTimeout(timeout time.Duration) *V1AboutIndexingListParams { + return &V1AboutIndexingListParams{ + timeout: timeout, + } +} + +// NewV1AboutIndexingListParamsWithContext creates a new V1AboutIndexingListParams object +// with the ability to set a context for a request. +func NewV1AboutIndexingListParamsWithContext(ctx context.Context) *V1AboutIndexingListParams { + return &V1AboutIndexingListParams{ + Context: ctx, + } +} + +// NewV1AboutIndexingListParamsWithHTTPClient creates a new V1AboutIndexingListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1AboutIndexingListParamsWithHTTPClient(client *http.Client) *V1AboutIndexingListParams { + return &V1AboutIndexingListParams{ + HTTPClient: client, + } +} + +/* +V1AboutIndexingListParams contains all the parameters to send to the API endpoint + + for the v1 about indexing list operation. + + Typically these are written to a http.Request. +*/ +type V1AboutIndexingListParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 about indexing list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1AboutIndexingListParams) WithDefaults() *V1AboutIndexingListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 about indexing list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1AboutIndexingListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 about indexing list params +func (o *V1AboutIndexingListParams) WithTimeout(timeout time.Duration) *V1AboutIndexingListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 about indexing list params +func (o *V1AboutIndexingListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 about indexing list params +func (o *V1AboutIndexingListParams) WithContext(ctx context.Context) *V1AboutIndexingListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 about indexing list params +func (o *V1AboutIndexingListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 about indexing list params +func (o *V1AboutIndexingListParams) WithHTTPClient(client *http.Client) *V1AboutIndexingListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 about indexing list params +func (o *V1AboutIndexingListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *V1AboutIndexingListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/about/v1_about_indexing_list_responses.go b/utils/safe_api/client/about/v1_about_indexing_list_responses.go new file mode 100644 index 0000000..216f9b3 --- /dev/null +++ b/utils/safe_api/client/about/v1_about_indexing_list_responses.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package about + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1AboutIndexingListReader is a Reader for the V1AboutIndexingList structure. +type V1AboutIndexingListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1AboutIndexingListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1AboutIndexingListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[GET /v1/about/indexing/] v1_about_indexing_list", response, response.Code()) + } +} + +// NewV1AboutIndexingListOK creates a V1AboutIndexingListOK with default headers values +func NewV1AboutIndexingListOK() *V1AboutIndexingListOK { + return &V1AboutIndexingListOK{} +} + +/* +V1AboutIndexingListOK describes a response with status code 200, with default header values. + +V1AboutIndexingListOK v1 about indexing list o k +*/ +type V1AboutIndexingListOK struct { + Payload []*models.IndexingStatus +} + +// IsSuccess returns true when this v1 about indexing list o k response has a 2xx status code +func (o *V1AboutIndexingListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 about indexing list o k response has a 3xx status code +func (o *V1AboutIndexingListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 about indexing list o k response has a 4xx status code +func (o *V1AboutIndexingListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 about indexing list o k response has a 5xx status code +func (o *V1AboutIndexingListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 about indexing list o k response a status code equal to that given +func (o *V1AboutIndexingListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 about indexing list o k response +func (o *V1AboutIndexingListOK) Code() int { + return 200 +} + +func (o *V1AboutIndexingListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/about/indexing/][%d] v1AboutIndexingListOK %s", 200, payload) +} + +func (o *V1AboutIndexingListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/about/indexing/][%d] v1AboutIndexingListOK %s", 200, payload) +} + +func (o *V1AboutIndexingListOK) GetPayload() []*models.IndexingStatus { + return o.Payload +} + +func (o *V1AboutIndexingListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/utils/safe_api/client/about/v1_about_list_parameters.go b/utils/safe_api/client/about/v1_about_list_parameters.go new file mode 100644 index 0000000..b00e649 --- /dev/null +++ b/utils/safe_api/client/about/v1_about_list_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package about + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1AboutListParams creates a new V1AboutListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1AboutListParams() *V1AboutListParams { + return &V1AboutListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1AboutListParamsWithTimeout creates a new V1AboutListParams object +// with the ability to set a timeout on a request. +func NewV1AboutListParamsWithTimeout(timeout time.Duration) *V1AboutListParams { + return &V1AboutListParams{ + timeout: timeout, + } +} + +// NewV1AboutListParamsWithContext creates a new V1AboutListParams object +// with the ability to set a context for a request. +func NewV1AboutListParamsWithContext(ctx context.Context) *V1AboutListParams { + return &V1AboutListParams{ + Context: ctx, + } +} + +// NewV1AboutListParamsWithHTTPClient creates a new V1AboutListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1AboutListParamsWithHTTPClient(client *http.Client) *V1AboutListParams { + return &V1AboutListParams{ + HTTPClient: client, + } +} + +/* +V1AboutListParams contains all the parameters to send to the API endpoint + + for the v1 about list operation. + + Typically these are written to a http.Request. +*/ +type V1AboutListParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 about list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1AboutListParams) WithDefaults() *V1AboutListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 about list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1AboutListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 about list params +func (o *V1AboutListParams) WithTimeout(timeout time.Duration) *V1AboutListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 about list params +func (o *V1AboutListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 about list params +func (o *V1AboutListParams) WithContext(ctx context.Context) *V1AboutListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 about list params +func (o *V1AboutListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 about list params +func (o *V1AboutListParams) WithHTTPClient(client *http.Client) *V1AboutListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 about list params +func (o *V1AboutListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *V1AboutListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/about/v1_about_list_responses.go b/utils/safe_api/client/about/v1_about_list_responses.go new file mode 100644 index 0000000..7aff7e4 --- /dev/null +++ b/utils/safe_api/client/about/v1_about_list_responses.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package about + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// V1AboutListReader is a Reader for the V1AboutList structure. +type V1AboutListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1AboutListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1AboutListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[GET /v1/about/] v1_about_list", response, response.Code()) + } +} + +// NewV1AboutListOK creates a V1AboutListOK with default headers values +func NewV1AboutListOK() *V1AboutListOK { + return &V1AboutListOK{} +} + +/* +V1AboutListOK describes a response with status code 200, with default header values. + +V1AboutListOK v1 about list o k +*/ +type V1AboutListOK struct { +} + +// IsSuccess returns true when this v1 about list o k response has a 2xx status code +func (o *V1AboutListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 about list o k response has a 3xx status code +func (o *V1AboutListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 about list o k response has a 4xx status code +func (o *V1AboutListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 about list o k response has a 5xx status code +func (o *V1AboutListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 about list o k response a status code equal to that given +func (o *V1AboutListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 about list o k response +func (o *V1AboutListOK) Code() int { + return 200 +} + +func (o *V1AboutListOK) Error() string { + return fmt.Sprintf("[GET /v1/about/][%d] v1AboutListOK", 200) +} + +func (o *V1AboutListOK) String() string { + return fmt.Sprintf("[GET /v1/about/][%d] v1AboutListOK", 200) +} + +func (o *V1AboutListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/about/v1_about_singletons_list_parameters.go b/utils/safe_api/client/about/v1_about_singletons_list_parameters.go new file mode 100644 index 0000000..ec53d6b --- /dev/null +++ b/utils/safe_api/client/about/v1_about_singletons_list_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package about + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1AboutSingletonsListParams creates a new V1AboutSingletonsListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1AboutSingletonsListParams() *V1AboutSingletonsListParams { + return &V1AboutSingletonsListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1AboutSingletonsListParamsWithTimeout creates a new V1AboutSingletonsListParams object +// with the ability to set a timeout on a request. +func NewV1AboutSingletonsListParamsWithTimeout(timeout time.Duration) *V1AboutSingletonsListParams { + return &V1AboutSingletonsListParams{ + timeout: timeout, + } +} + +// NewV1AboutSingletonsListParamsWithContext creates a new V1AboutSingletonsListParams object +// with the ability to set a context for a request. +func NewV1AboutSingletonsListParamsWithContext(ctx context.Context) *V1AboutSingletonsListParams { + return &V1AboutSingletonsListParams{ + Context: ctx, + } +} + +// NewV1AboutSingletonsListParamsWithHTTPClient creates a new V1AboutSingletonsListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1AboutSingletonsListParamsWithHTTPClient(client *http.Client) *V1AboutSingletonsListParams { + return &V1AboutSingletonsListParams{ + HTTPClient: client, + } +} + +/* +V1AboutSingletonsListParams contains all the parameters to send to the API endpoint + + for the v1 about singletons list operation. + + Typically these are written to a http.Request. +*/ +type V1AboutSingletonsListParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 about singletons list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1AboutSingletonsListParams) WithDefaults() *V1AboutSingletonsListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 about singletons list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1AboutSingletonsListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 about singletons list params +func (o *V1AboutSingletonsListParams) WithTimeout(timeout time.Duration) *V1AboutSingletonsListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 about singletons list params +func (o *V1AboutSingletonsListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 about singletons list params +func (o *V1AboutSingletonsListParams) WithContext(ctx context.Context) *V1AboutSingletonsListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 about singletons list params +func (o *V1AboutSingletonsListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 about singletons list params +func (o *V1AboutSingletonsListParams) WithHTTPClient(client *http.Client) *V1AboutSingletonsListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 about singletons list params +func (o *V1AboutSingletonsListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *V1AboutSingletonsListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/about/v1_about_singletons_list_responses.go b/utils/safe_api/client/about/v1_about_singletons_list_responses.go new file mode 100644 index 0000000..d57ee28 --- /dev/null +++ b/utils/safe_api/client/about/v1_about_singletons_list_responses.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package about + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1AboutSingletonsListReader is a Reader for the V1AboutSingletonsList structure. +type V1AboutSingletonsListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1AboutSingletonsListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1AboutSingletonsListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[GET /v1/about/singletons/] v1_about_singletons_list", response, response.Code()) + } +} + +// NewV1AboutSingletonsListOK creates a V1AboutSingletonsListOK with default headers values +func NewV1AboutSingletonsListOK() *V1AboutSingletonsListOK { + return &V1AboutSingletonsListOK{} +} + +/* +V1AboutSingletonsListOK describes a response with status code 200, with default header values. + +V1AboutSingletonsListOK v1 about singletons list o k +*/ +type V1AboutSingletonsListOK struct { + Payload []*models.MasterCopyResponse +} + +// IsSuccess returns true when this v1 about singletons list o k response has a 2xx status code +func (o *V1AboutSingletonsListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 about singletons list o k response has a 3xx status code +func (o *V1AboutSingletonsListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 about singletons list o k response has a 4xx status code +func (o *V1AboutSingletonsListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 about singletons list o k response has a 5xx status code +func (o *V1AboutSingletonsListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 about singletons list o k response a status code equal to that given +func (o *V1AboutSingletonsListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 about singletons list o k response +func (o *V1AboutSingletonsListOK) Code() int { + return 200 +} + +func (o *V1AboutSingletonsListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/about/singletons/][%d] v1AboutSingletonsListOK %s", 200, payload) +} + +func (o *V1AboutSingletonsListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/about/singletons/][%d] v1AboutSingletonsListOK %s", 200, payload) +} + +func (o *V1AboutSingletonsListOK) GetPayload() []*models.MasterCopyResponse { + return o.Payload +} + +func (o *V1AboutSingletonsListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/utils/safe_api/client/contracts/contracts_client.go b/utils/safe_api/client/contracts/contracts_client.go new file mode 100644 index 0000000..70a10a7 --- /dev/null +++ b/utils/safe_api/client/contracts/contracts_client.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package contracts + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// New creates a new contracts API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +// New creates a new contracts API client with basic auth credentials. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - user: user for basic authentication header. +// - password: password for basic authentication header. +func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BasicAuth(user, password) + return &Client{transport: transport, formats: strfmt.Default} +} + +// New creates a new contracts API client with a bearer token for authentication. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - bearerToken: bearer token for Bearer authentication header. +func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) + return &Client{transport: transport, formats: strfmt.Default} +} + +/* +Client for contracts API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption may be used to customize the behavior of Client methods. +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + V1ContractsList(params *V1ContractsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1ContractsListOK, error) + + V1ContractsRead(params *V1ContractsReadParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1ContractsReadOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +V1ContractsList v1 contracts list API +*/ +func (a *Client) V1ContractsList(params *V1ContractsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1ContractsListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1ContractsListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_contracts_list", + Method: "GET", + PathPattern: "/v1/contracts/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1ContractsListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1ContractsListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_contracts_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1ContractsRead v1 contracts read API +*/ +func (a *Client) V1ContractsRead(params *V1ContractsReadParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1ContractsReadOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1ContractsReadParams() + } + op := &runtime.ClientOperation{ + ID: "v1_contracts_read", + Method: "GET", + PathPattern: "/v1/contracts/{address}/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1ContractsReadReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1ContractsReadOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_contracts_read: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/utils/safe_api/client/contracts/v1_contracts_list_parameters.go b/utils/safe_api/client/contracts/v1_contracts_list_parameters.go new file mode 100644 index 0000000..9599b9f --- /dev/null +++ b/utils/safe_api/client/contracts/v1_contracts_list_parameters.go @@ -0,0 +1,232 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package contracts + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewV1ContractsListParams creates a new V1ContractsListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1ContractsListParams() *V1ContractsListParams { + return &V1ContractsListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1ContractsListParamsWithTimeout creates a new V1ContractsListParams object +// with the ability to set a timeout on a request. +func NewV1ContractsListParamsWithTimeout(timeout time.Duration) *V1ContractsListParams { + return &V1ContractsListParams{ + timeout: timeout, + } +} + +// NewV1ContractsListParamsWithContext creates a new V1ContractsListParams object +// with the ability to set a context for a request. +func NewV1ContractsListParamsWithContext(ctx context.Context) *V1ContractsListParams { + return &V1ContractsListParams{ + Context: ctx, + } +} + +// NewV1ContractsListParamsWithHTTPClient creates a new V1ContractsListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1ContractsListParamsWithHTTPClient(client *http.Client) *V1ContractsListParams { + return &V1ContractsListParams{ + HTTPClient: client, + } +} + +/* +V1ContractsListParams contains all the parameters to send to the API endpoint + + for the v1 contracts list operation. + + Typically these are written to a http.Request. +*/ +type V1ContractsListParams struct { + + /* Limit. + + Number of results to return per page. + */ + Limit *int64 + + /* Offset. + + The initial index from which to return the results. + */ + Offset *int64 + + /* Ordering. + + Which field to use when ordering the results. + */ + Ordering *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 contracts list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1ContractsListParams) WithDefaults() *V1ContractsListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 contracts list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1ContractsListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 contracts list params +func (o *V1ContractsListParams) WithTimeout(timeout time.Duration) *V1ContractsListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 contracts list params +func (o *V1ContractsListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 contracts list params +func (o *V1ContractsListParams) WithContext(ctx context.Context) *V1ContractsListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 contracts list params +func (o *V1ContractsListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 contracts list params +func (o *V1ContractsListParams) WithHTTPClient(client *http.Client) *V1ContractsListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 contracts list params +func (o *V1ContractsListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithLimit adds the limit to the v1 contracts list params +func (o *V1ContractsListParams) WithLimit(limit *int64) *V1ContractsListParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the v1 contracts list params +func (o *V1ContractsListParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the v1 contracts list params +func (o *V1ContractsListParams) WithOffset(offset *int64) *V1ContractsListParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the v1 contracts list params +func (o *V1ContractsListParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithOrdering adds the ordering to the v1 contracts list params +func (o *V1ContractsListParams) WithOrdering(ordering *string) *V1ContractsListParams { + o.SetOrdering(ordering) + return o +} + +// SetOrdering adds the ordering to the v1 contracts list params +func (o *V1ContractsListParams) SetOrdering(ordering *string) { + o.Ordering = ordering +} + +// WriteToRequest writes these params to a swagger request +func (o *V1ContractsListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Ordering != nil { + + // query param ordering + var qrOrdering string + + if o.Ordering != nil { + qrOrdering = *o.Ordering + } + qOrdering := qrOrdering + if qOrdering != "" { + + if err := r.SetQueryParam("ordering", qOrdering); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/contracts/v1_contracts_list_responses.go b/utils/safe_api/client/contracts/v1_contracts_list_responses.go new file mode 100644 index 0000000..9f71e34 --- /dev/null +++ b/utils/safe_api/client/contracts/v1_contracts_list_responses.go @@ -0,0 +1,277 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package contracts + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + models "omni-balance/utils/safe_api" +) + +// V1ContractsListReader is a Reader for the V1ContractsList structure. +type V1ContractsListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1ContractsListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1ContractsListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[GET /v1/contracts/] v1_contracts_list", response, response.Code()) + } +} + +// NewV1ContractsListOK creates a V1ContractsListOK with default headers values +func NewV1ContractsListOK() *V1ContractsListOK { + return &V1ContractsListOK{} +} + +/* +V1ContractsListOK describes a response with status code 200, with default header values. + +V1ContractsListOK v1 contracts list o k +*/ +type V1ContractsListOK struct { + Payload *V1ContractsListOKBody +} + +// IsSuccess returns true when this v1 contracts list o k response has a 2xx status code +func (o *V1ContractsListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 contracts list o k response has a 3xx status code +func (o *V1ContractsListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 contracts list o k response has a 4xx status code +func (o *V1ContractsListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 contracts list o k response has a 5xx status code +func (o *V1ContractsListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 contracts list o k response a status code equal to that given +func (o *V1ContractsListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 contracts list o k response +func (o *V1ContractsListOK) Code() int { + return 200 +} + +func (o *V1ContractsListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/contracts/][%d] v1ContractsListOK %s", 200, payload) +} + +func (o *V1ContractsListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/contracts/][%d] v1ContractsListOK %s", 200, payload) +} + +func (o *V1ContractsListOK) GetPayload() *V1ContractsListOKBody { + return o.Payload +} + +func (o *V1ContractsListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(V1ContractsListOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +V1ContractsListOKBody v1 contracts list o k body +swagger:model V1ContractsListOKBody +*/ +type V1ContractsListOKBody struct { + + // count + // Required: true + Count *int64 `json:"count"` + + // next + // Format: uri + Next *strfmt.URI `json:"next,omitempty"` + + // previous + // Format: uri + Previous *strfmt.URI `json:"previous,omitempty"` + + // results + // Required: true + Results []*models.Contract `json:"results"` +} + +// Validate validates this v1 contracts list o k body +func (o *V1ContractsListOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateCount(formats); err != nil { + res = append(res, err) + } + + if err := o.validateNext(formats); err != nil { + res = append(res, err) + } + + if err := o.validatePrevious(formats); err != nil { + res = append(res, err) + } + + if err := o.validateResults(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V1ContractsListOKBody) validateCount(formats strfmt.Registry) error { + + if err := validate.Required("v1ContractsListOK"+"."+"count", "body", o.Count); err != nil { + return err + } + + return nil +} + +func (o *V1ContractsListOKBody) validateNext(formats strfmt.Registry) error { + if swag.IsZero(o.Next) { // not required + return nil + } + + if err := validate.FormatOf("v1ContractsListOK"+"."+"next", "body", "uri", o.Next.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V1ContractsListOKBody) validatePrevious(formats strfmt.Registry) error { + if swag.IsZero(o.Previous) { // not required + return nil + } + + if err := validate.FormatOf("v1ContractsListOK"+"."+"previous", "body", "uri", o.Previous.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V1ContractsListOKBody) validateResults(formats strfmt.Registry) error { + + if err := validate.Required("v1ContractsListOK"+"."+"results", "body", o.Results); err != nil { + return err + } + + for i := 0; i < len(o.Results); i++ { + if swag.IsZero(o.Results[i]) { // not required + continue + } + + if o.Results[i] != nil { + if err := o.Results[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v1ContractsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v1ContractsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this v1 contracts list o k body based on the context it is used +func (o *V1ContractsListOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResults(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V1ContractsListOKBody) contextValidateResults(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Results); i++ { + + if o.Results[i] != nil { + + if swag.IsZero(o.Results[i]) { // not required + return nil + } + + if err := o.Results[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v1ContractsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v1ContractsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *V1ContractsListOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *V1ContractsListOKBody) UnmarshalBinary(b []byte) error { + var res V1ContractsListOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/utils/safe_api/client/contracts/v1_contracts_read_parameters.go b/utils/safe_api/client/contracts/v1_contracts_read_parameters.go new file mode 100644 index 0000000..8540f2b --- /dev/null +++ b/utils/safe_api/client/contracts/v1_contracts_read_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package contracts + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1ContractsReadParams creates a new V1ContractsReadParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1ContractsReadParams() *V1ContractsReadParams { + return &V1ContractsReadParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1ContractsReadParamsWithTimeout creates a new V1ContractsReadParams object +// with the ability to set a timeout on a request. +func NewV1ContractsReadParamsWithTimeout(timeout time.Duration) *V1ContractsReadParams { + return &V1ContractsReadParams{ + timeout: timeout, + } +} + +// NewV1ContractsReadParamsWithContext creates a new V1ContractsReadParams object +// with the ability to set a context for a request. +func NewV1ContractsReadParamsWithContext(ctx context.Context) *V1ContractsReadParams { + return &V1ContractsReadParams{ + Context: ctx, + } +} + +// NewV1ContractsReadParamsWithHTTPClient creates a new V1ContractsReadParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1ContractsReadParamsWithHTTPClient(client *http.Client) *V1ContractsReadParams { + return &V1ContractsReadParams{ + HTTPClient: client, + } +} + +/* +V1ContractsReadParams contains all the parameters to send to the API endpoint + + for the v1 contracts read operation. + + Typically these are written to a http.Request. +*/ +type V1ContractsReadParams struct { + + /* Address. + + A unique value identifying this contract. + */ + Address string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 contracts read params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1ContractsReadParams) WithDefaults() *V1ContractsReadParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 contracts read params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1ContractsReadParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 contracts read params +func (o *V1ContractsReadParams) WithTimeout(timeout time.Duration) *V1ContractsReadParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 contracts read params +func (o *V1ContractsReadParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 contracts read params +func (o *V1ContractsReadParams) WithContext(ctx context.Context) *V1ContractsReadParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 contracts read params +func (o *V1ContractsReadParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 contracts read params +func (o *V1ContractsReadParams) WithHTTPClient(client *http.Client) *V1ContractsReadParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 contracts read params +func (o *V1ContractsReadParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 contracts read params +func (o *V1ContractsReadParams) WithAddress(address string) *V1ContractsReadParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 contracts read params +func (o *V1ContractsReadParams) SetAddress(address string) { + o.Address = address +} + +// WriteToRequest writes these params to a swagger request +func (o *V1ContractsReadParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/contracts/v1_contracts_read_responses.go b/utils/safe_api/client/contracts/v1_contracts_read_responses.go new file mode 100644 index 0000000..9126b82 --- /dev/null +++ b/utils/safe_api/client/contracts/v1_contracts_read_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package contracts + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1ContractsReadReader is a Reader for the V1ContractsRead structure. +type V1ContractsReadReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1ContractsReadReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1ContractsReadOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[GET /v1/contracts/{address}/] v1_contracts_read", response, response.Code()) + } +} + +// NewV1ContractsReadOK creates a V1ContractsReadOK with default headers values +func NewV1ContractsReadOK() *V1ContractsReadOK { + return &V1ContractsReadOK{} +} + +/* +V1ContractsReadOK describes a response with status code 200, with default header values. + +V1ContractsReadOK v1 contracts read o k +*/ +type V1ContractsReadOK struct { + Payload *models.Contract +} + +// IsSuccess returns true when this v1 contracts read o k response has a 2xx status code +func (o *V1ContractsReadOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 contracts read o k response has a 3xx status code +func (o *V1ContractsReadOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 contracts read o k response has a 4xx status code +func (o *V1ContractsReadOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 contracts read o k response has a 5xx status code +func (o *V1ContractsReadOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 contracts read o k response a status code equal to that given +func (o *V1ContractsReadOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 contracts read o k response +func (o *V1ContractsReadOK) Code() int { + return 200 +} + +func (o *V1ContractsReadOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/contracts/{address}/][%d] v1ContractsReadOK %s", 200, payload) +} + +func (o *V1ContractsReadOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/contracts/{address}/][%d] v1ContractsReadOK %s", 200, payload) +} + +func (o *V1ContractsReadOK) GetPayload() *models.Contract { + return o.Payload +} + +func (o *V1ContractsReadOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Contract) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/utils/safe_api/client/data_decoder/data_decoder_client.go b/utils/safe_api/client/data_decoder/data_decoder_client.go new file mode 100644 index 0000000..bd8cb01 --- /dev/null +++ b/utils/safe_api/client/data_decoder/data_decoder_client.go @@ -0,0 +1,110 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package data_decoder + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// New creates a new data decoder API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +// New creates a new data decoder API client with basic auth credentials. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - user: user for basic authentication header. +// - password: password for basic authentication header. +func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BasicAuth(user, password) + return &Client{transport: transport, formats: strfmt.Default} +} + +// New creates a new data decoder API client with a bearer token for authentication. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - bearerToken: bearer token for Bearer authentication header. +func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) + return &Client{transport: transport, formats: strfmt.Default} +} + +/* +Client for data decoder API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption may be used to customize the behavior of Client methods. +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + V1DataDecoderCreate(params *V1DataDecoderCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1DataDecoderCreateOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + V1DataDecoderCreate Returns decoded information using tx service internal ABI information given the tx + +data as a `0x` prefixed hexadecimal string. +If address of the receiving contract is provided decoded data will be more accurate, +as in case of ABI collision service will know which ABI to use. +*/ +func (a *Client) V1DataDecoderCreate(params *V1DataDecoderCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1DataDecoderCreateOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1DataDecoderCreateParams() + } + op := &runtime.ClientOperation{ + ID: "v1_data-decoder_create", + Method: "POST", + PathPattern: "/v1/data-decoder/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1DataDecoderCreateReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1DataDecoderCreateOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_data-decoder_create: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/utils/safe_api/client/data_decoder/v1_data_decoder_create_parameters.go b/utils/safe_api/client/data_decoder/v1_data_decoder_create_parameters.go new file mode 100644 index 0000000..cc6d1e4 --- /dev/null +++ b/utils/safe_api/client/data_decoder/v1_data_decoder_create_parameters.go @@ -0,0 +1,150 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package data_decoder + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// NewV1DataDecoderCreateParams creates a new V1DataDecoderCreateParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1DataDecoderCreateParams() *V1DataDecoderCreateParams { + return &V1DataDecoderCreateParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1DataDecoderCreateParamsWithTimeout creates a new V1DataDecoderCreateParams object +// with the ability to set a timeout on a request. +func NewV1DataDecoderCreateParamsWithTimeout(timeout time.Duration) *V1DataDecoderCreateParams { + return &V1DataDecoderCreateParams{ + timeout: timeout, + } +} + +// NewV1DataDecoderCreateParamsWithContext creates a new V1DataDecoderCreateParams object +// with the ability to set a context for a request. +func NewV1DataDecoderCreateParamsWithContext(ctx context.Context) *V1DataDecoderCreateParams { + return &V1DataDecoderCreateParams{ + Context: ctx, + } +} + +// NewV1DataDecoderCreateParamsWithHTTPClient creates a new V1DataDecoderCreateParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1DataDecoderCreateParamsWithHTTPClient(client *http.Client) *V1DataDecoderCreateParams { + return &V1DataDecoderCreateParams{ + HTTPClient: client, + } +} + +/* +V1DataDecoderCreateParams contains all the parameters to send to the API endpoint + + for the v1 data decoder create operation. + + Typically these are written to a http.Request. +*/ +type V1DataDecoderCreateParams struct { + + // Data. + Data *models.DataDecoder + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 data decoder create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1DataDecoderCreateParams) WithDefaults() *V1DataDecoderCreateParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 data decoder create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1DataDecoderCreateParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 data decoder create params +func (o *V1DataDecoderCreateParams) WithTimeout(timeout time.Duration) *V1DataDecoderCreateParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 data decoder create params +func (o *V1DataDecoderCreateParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 data decoder create params +func (o *V1DataDecoderCreateParams) WithContext(ctx context.Context) *V1DataDecoderCreateParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 data decoder create params +func (o *V1DataDecoderCreateParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 data decoder create params +func (o *V1DataDecoderCreateParams) WithHTTPClient(client *http.Client) *V1DataDecoderCreateParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 data decoder create params +func (o *V1DataDecoderCreateParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the v1 data decoder create params +func (o *V1DataDecoderCreateParams) WithData(data *models.DataDecoder) *V1DataDecoderCreateParams { + o.SetData(data) + return o +} + +// SetData adds the data to the v1 data decoder create params +func (o *V1DataDecoderCreateParams) SetData(data *models.DataDecoder) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *V1DataDecoderCreateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/data_decoder/v1_data_decoder_create_responses.go b/utils/safe_api/client/data_decoder/v1_data_decoder_create_responses.go new file mode 100644 index 0000000..cead756 --- /dev/null +++ b/utils/safe_api/client/data_decoder/v1_data_decoder_create_responses.go @@ -0,0 +1,212 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package data_decoder + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// V1DataDecoderCreateReader is a Reader for the V1DataDecoderCreate structure. +type V1DataDecoderCreateReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1DataDecoderCreateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1DataDecoderCreateOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewV1DataDecoderCreateNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 422: + result := NewV1DataDecoderCreateUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /v1/data-decoder/] v1_data-decoder_create", response, response.Code()) + } +} + +// NewV1DataDecoderCreateOK creates a V1DataDecoderCreateOK with default headers values +func NewV1DataDecoderCreateOK() *V1DataDecoderCreateOK { + return &V1DataDecoderCreateOK{} +} + +/* +V1DataDecoderCreateOK describes a response with status code 200, with default header values. + +Decoded data +*/ +type V1DataDecoderCreateOK struct { +} + +// IsSuccess returns true when this v1 data decoder create o k response has a 2xx status code +func (o *V1DataDecoderCreateOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 data decoder create o k response has a 3xx status code +func (o *V1DataDecoderCreateOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 data decoder create o k response has a 4xx status code +func (o *V1DataDecoderCreateOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 data decoder create o k response has a 5xx status code +func (o *V1DataDecoderCreateOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 data decoder create o k response a status code equal to that given +func (o *V1DataDecoderCreateOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 data decoder create o k response +func (o *V1DataDecoderCreateOK) Code() int { + return 200 +} + +func (o *V1DataDecoderCreateOK) Error() string { + return fmt.Sprintf("[POST /v1/data-decoder/][%d] v1DataDecoderCreateOK", 200) +} + +func (o *V1DataDecoderCreateOK) String() string { + return fmt.Sprintf("[POST /v1/data-decoder/][%d] v1DataDecoderCreateOK", 200) +} + +func (o *V1DataDecoderCreateOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1DataDecoderCreateNotFound creates a V1DataDecoderCreateNotFound with default headers values +func NewV1DataDecoderCreateNotFound() *V1DataDecoderCreateNotFound { + return &V1DataDecoderCreateNotFound{} +} + +/* +V1DataDecoderCreateNotFound describes a response with status code 404, with default header values. + +Cannot find function selector to decode data +*/ +type V1DataDecoderCreateNotFound struct { +} + +// IsSuccess returns true when this v1 data decoder create not found response has a 2xx status code +func (o *V1DataDecoderCreateNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 data decoder create not found response has a 3xx status code +func (o *V1DataDecoderCreateNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 data decoder create not found response has a 4xx status code +func (o *V1DataDecoderCreateNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 data decoder create not found response has a 5xx status code +func (o *V1DataDecoderCreateNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 data decoder create not found response a status code equal to that given +func (o *V1DataDecoderCreateNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 data decoder create not found response +func (o *V1DataDecoderCreateNotFound) Code() int { + return 404 +} + +func (o *V1DataDecoderCreateNotFound) Error() string { + return fmt.Sprintf("[POST /v1/data-decoder/][%d] v1DataDecoderCreateNotFound", 404) +} + +func (o *V1DataDecoderCreateNotFound) String() string { + return fmt.Sprintf("[POST /v1/data-decoder/][%d] v1DataDecoderCreateNotFound", 404) +} + +func (o *V1DataDecoderCreateNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1DataDecoderCreateUnprocessableEntity creates a V1DataDecoderCreateUnprocessableEntity with default headers values +func NewV1DataDecoderCreateUnprocessableEntity() *V1DataDecoderCreateUnprocessableEntity { + return &V1DataDecoderCreateUnprocessableEntity{} +} + +/* +V1DataDecoderCreateUnprocessableEntity describes a response with status code 422, with default header values. + +Invalid data +*/ +type V1DataDecoderCreateUnprocessableEntity struct { +} + +// IsSuccess returns true when this v1 data decoder create unprocessable entity response has a 2xx status code +func (o *V1DataDecoderCreateUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 data decoder create unprocessable entity response has a 3xx status code +func (o *V1DataDecoderCreateUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 data decoder create unprocessable entity response has a 4xx status code +func (o *V1DataDecoderCreateUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 data decoder create unprocessable entity response has a 5xx status code +func (o *V1DataDecoderCreateUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 data decoder create unprocessable entity response a status code equal to that given +func (o *V1DataDecoderCreateUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 data decoder create unprocessable entity response +func (o *V1DataDecoderCreateUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1DataDecoderCreateUnprocessableEntity) Error() string { + return fmt.Sprintf("[POST /v1/data-decoder/][%d] v1DataDecoderCreateUnprocessableEntity", 422) +} + +func (o *V1DataDecoderCreateUnprocessableEntity) String() string { + return fmt.Sprintf("[POST /v1/data-decoder/][%d] v1DataDecoderCreateUnprocessableEntity", 422) +} + +func (o *V1DataDecoderCreateUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/delegates/delegates_client.go b/utils/safe_api/client/delegates/delegates_client.go new file mode 100644 index 0000000..fcc1bb2 --- /dev/null +++ b/utils/safe_api/client/delegates/delegates_client.go @@ -0,0 +1,360 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package delegates + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// New creates a new delegates API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +// New creates a new delegates API client with basic auth credentials. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - user: user for basic authentication header. +// - password: password for basic authentication header. +func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BasicAuth(user, password) + return &Client{transport: transport, formats: strfmt.Default} +} + +// New creates a new delegates API client with a bearer token for authentication. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - bearerToken: bearer token for Bearer authentication header. +func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) + return &Client{transport: transport, formats: strfmt.Default} +} + +/* +Client for delegates API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption may be used to customize the behavior of Client methods. +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + V1DelegatesCreate(params *V1DelegatesCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1DelegatesCreateAccepted, error) + + V1DelegatesDelete(params *V1DelegatesDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1DelegatesDeleteNoContent, error) + + V1DelegatesList(params *V1DelegatesListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1DelegatesListOK, error) + + V2DelegatesCreate(params *V2DelegatesCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V2DelegatesCreateAccepted, error) + + V2DelegatesDelete(params *V2DelegatesDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V2DelegatesDeleteNoContent, error) + + V2DelegatesList(params *V2DelegatesListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V2DelegatesListOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + V1DelegatesCreate Create a delegate for a Safe address with a custom label. Calls with same delegate but different label or + +signer will update the label or delegator if different. +For the signature we are using TOTP with `T0=0` and `Tx=3600`. TOTP is calculated by taking the +Unix UTC epoch time (no milliseconds) and dividing by 3600 (natural division, no decimals) +For signature this hash need to be signed: keccak(checksummed address + str(int(current_epoch // 3600))) +For example: + - We want to add the delegate `0x132512f995866CcE1b0092384A6118EDaF4508Ff` and `epoch=1586779140`. + - `TOTP = epoch // 3600 = 1586779140 // 3600 = 440771` + - The hash to sign by a Safe owner would be `keccak("0x132512f995866CcE1b0092384A6118EDaF4508Ff440771")` +*/ +func (a *Client) V1DelegatesCreate(params *V1DelegatesCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1DelegatesCreateAccepted, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1DelegatesCreateParams() + } + op := &runtime.ClientOperation{ + ID: "v1_delegates_create", + Method: "POST", + PathPattern: "/v1/delegates/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1DelegatesCreateReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1DelegatesCreateAccepted) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_delegates_create: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* + V1DelegatesDelete Delete every pair delegate/delegator found. Signature is built the same way as for adding a delegate, + +but in this case the signer can be either the `delegator` (owner) or the `delegate` itself. +Check `POST /delegates/` +*/ +func (a *Client) V1DelegatesDelete(params *V1DelegatesDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1DelegatesDeleteNoContent, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1DelegatesDeleteParams() + } + op := &runtime.ClientOperation{ + ID: "v1_delegates_delete", + Method: "DELETE", + PathPattern: "/v1/delegates/{delegate_address}/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1DelegatesDeleteReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1DelegatesDeleteNoContent) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_delegates_delete: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1DelegatesList Get list of delegates +*/ +func (a *Client) V1DelegatesList(params *V1DelegatesListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1DelegatesListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1DelegatesListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_delegates_list", + Method: "GET", + PathPattern: "/v1/delegates/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1DelegatesListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1DelegatesListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_delegates_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* + V2DelegatesCreate Create a delegate for a Safe address with a custom label. Calls with same delegate but different label or + +signer will update the label or delegator if different. +An EOA is required to sign the following EIP712 data: + +```python + + { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + ], + "AddDelegate": [ + {"name": "delegateAddress", "type": "bytes32"}, + {"name": "totp", "type": "uint256"}, + ], + }, + "primaryType": "AddDelegate", + "domain": { + "name": "Safe Transaction Service", + "version": "1.0", + "chainId": chain_id, + }, + "message": { + "delegateAddress": delegate_address, + "totp": totp, + }, + } + +``` + +`totp` parameter is calculated with `T0=0` and `Tx=3600`. `totp` is calculated by taking the +Unix UTC epoch time (no milliseconds) and dividing by 3600 (natural division, no decimals) +*/ +func (a *Client) V2DelegatesCreate(params *V2DelegatesCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V2DelegatesCreateAccepted, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV2DelegatesCreateParams() + } + op := &runtime.ClientOperation{ + ID: "v2_delegates_create", + Method: "POST", + PathPattern: "/v2/delegates/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V2DelegatesCreateReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V2DelegatesCreateAccepted) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v2_delegates_create: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* + V2DelegatesDelete Removes all delegate/delegator pairs found or combinations of safe/delegate/delegator/delegate. The signature + +is constructed in the same way as for adding a delegate, but in this case the signer can be either the +`delegator` (owner) or the `delegate` itself. Check `POST /delegates/`. +*/ +func (a *Client) V2DelegatesDelete(params *V2DelegatesDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V2DelegatesDeleteNoContent, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV2DelegatesDeleteParams() + } + op := &runtime.ClientOperation{ + ID: "v2_delegates_delete", + Method: "DELETE", + PathPattern: "/v2/delegates/{delegate_address}/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V2DelegatesDeleteReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V2DelegatesDeleteNoContent) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v2_delegates_delete: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V2DelegatesList Get list of delegates +*/ +func (a *Client) V2DelegatesList(params *V2DelegatesListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V2DelegatesListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV2DelegatesListParams() + } + op := &runtime.ClientOperation{ + ID: "v2_delegates_list", + Method: "GET", + PathPattern: "/v2/delegates/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V2DelegatesListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V2DelegatesListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v2_delegates_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/utils/safe_api/client/delegates/v1_delegates_create_parameters.go b/utils/safe_api/client/delegates/v1_delegates_create_parameters.go new file mode 100644 index 0000000..3ad0b0e --- /dev/null +++ b/utils/safe_api/client/delegates/v1_delegates_create_parameters.go @@ -0,0 +1,150 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package delegates + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// NewV1DelegatesCreateParams creates a new V1DelegatesCreateParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1DelegatesCreateParams() *V1DelegatesCreateParams { + return &V1DelegatesCreateParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1DelegatesCreateParamsWithTimeout creates a new V1DelegatesCreateParams object +// with the ability to set a timeout on a request. +func NewV1DelegatesCreateParamsWithTimeout(timeout time.Duration) *V1DelegatesCreateParams { + return &V1DelegatesCreateParams{ + timeout: timeout, + } +} + +// NewV1DelegatesCreateParamsWithContext creates a new V1DelegatesCreateParams object +// with the ability to set a context for a request. +func NewV1DelegatesCreateParamsWithContext(ctx context.Context) *V1DelegatesCreateParams { + return &V1DelegatesCreateParams{ + Context: ctx, + } +} + +// NewV1DelegatesCreateParamsWithHTTPClient creates a new V1DelegatesCreateParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1DelegatesCreateParamsWithHTTPClient(client *http.Client) *V1DelegatesCreateParams { + return &V1DelegatesCreateParams{ + HTTPClient: client, + } +} + +/* +V1DelegatesCreateParams contains all the parameters to send to the API endpoint + + for the v1 delegates create operation. + + Typically these are written to a http.Request. +*/ +type V1DelegatesCreateParams struct { + + // Data. + Data *models.Delegate + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 delegates create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1DelegatesCreateParams) WithDefaults() *V1DelegatesCreateParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 delegates create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1DelegatesCreateParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 delegates create params +func (o *V1DelegatesCreateParams) WithTimeout(timeout time.Duration) *V1DelegatesCreateParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 delegates create params +func (o *V1DelegatesCreateParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 delegates create params +func (o *V1DelegatesCreateParams) WithContext(ctx context.Context) *V1DelegatesCreateParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 delegates create params +func (o *V1DelegatesCreateParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 delegates create params +func (o *V1DelegatesCreateParams) WithHTTPClient(client *http.Client) *V1DelegatesCreateParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 delegates create params +func (o *V1DelegatesCreateParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the v1 delegates create params +func (o *V1DelegatesCreateParams) WithData(data *models.Delegate) *V1DelegatesCreateParams { + o.SetData(data) + return o +} + +// SetData adds the data to the v1 delegates create params +func (o *V1DelegatesCreateParams) SetData(data *models.Delegate) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *V1DelegatesCreateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/delegates/v1_delegates_create_responses.go b/utils/safe_api/client/delegates/v1_delegates_create_responses.go new file mode 100644 index 0000000..b6dbdd2 --- /dev/null +++ b/utils/safe_api/client/delegates/v1_delegates_create_responses.go @@ -0,0 +1,150 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package delegates + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// V1DelegatesCreateReader is a Reader for the V1DelegatesCreate structure. +type V1DelegatesCreateReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1DelegatesCreateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 202: + result := NewV1DelegatesCreateAccepted() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1DelegatesCreateBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /v1/delegates/] v1_delegates_create", response, response.Code()) + } +} + +// NewV1DelegatesCreateAccepted creates a V1DelegatesCreateAccepted with default headers values +func NewV1DelegatesCreateAccepted() *V1DelegatesCreateAccepted { + return &V1DelegatesCreateAccepted{} +} + +/* +V1DelegatesCreateAccepted describes a response with status code 202, with default header values. + +Accepted +*/ +type V1DelegatesCreateAccepted struct { +} + +// IsSuccess returns true when this v1 delegates create accepted response has a 2xx status code +func (o *V1DelegatesCreateAccepted) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 delegates create accepted response has a 3xx status code +func (o *V1DelegatesCreateAccepted) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 delegates create accepted response has a 4xx status code +func (o *V1DelegatesCreateAccepted) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 delegates create accepted response has a 5xx status code +func (o *V1DelegatesCreateAccepted) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 delegates create accepted response a status code equal to that given +func (o *V1DelegatesCreateAccepted) IsCode(code int) bool { + return code == 202 +} + +// Code gets the status code for the v1 delegates create accepted response +func (o *V1DelegatesCreateAccepted) Code() int { + return 202 +} + +func (o *V1DelegatesCreateAccepted) Error() string { + return fmt.Sprintf("[POST /v1/delegates/][%d] v1DelegatesCreateAccepted", 202) +} + +func (o *V1DelegatesCreateAccepted) String() string { + return fmt.Sprintf("[POST /v1/delegates/][%d] v1DelegatesCreateAccepted", 202) +} + +func (o *V1DelegatesCreateAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1DelegatesCreateBadRequest creates a V1DelegatesCreateBadRequest with default headers values +func NewV1DelegatesCreateBadRequest() *V1DelegatesCreateBadRequest { + return &V1DelegatesCreateBadRequest{} +} + +/* +V1DelegatesCreateBadRequest describes a response with status code 400, with default header values. + +Malformed data +*/ +type V1DelegatesCreateBadRequest struct { +} + +// IsSuccess returns true when this v1 delegates create bad request response has a 2xx status code +func (o *V1DelegatesCreateBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 delegates create bad request response has a 3xx status code +func (o *V1DelegatesCreateBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 delegates create bad request response has a 4xx status code +func (o *V1DelegatesCreateBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 delegates create bad request response has a 5xx status code +func (o *V1DelegatesCreateBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 delegates create bad request response a status code equal to that given +func (o *V1DelegatesCreateBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 delegates create bad request response +func (o *V1DelegatesCreateBadRequest) Code() int { + return 400 +} + +func (o *V1DelegatesCreateBadRequest) Error() string { + return fmt.Sprintf("[POST /v1/delegates/][%d] v1DelegatesCreateBadRequest", 400) +} + +func (o *V1DelegatesCreateBadRequest) String() string { + return fmt.Sprintf("[POST /v1/delegates/][%d] v1DelegatesCreateBadRequest", 400) +} + +func (o *V1DelegatesCreateBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/delegates/v1_delegates_delete_parameters.go b/utils/safe_api/client/delegates/v1_delegates_delete_parameters.go new file mode 100644 index 0000000..283a2b6 --- /dev/null +++ b/utils/safe_api/client/delegates/v1_delegates_delete_parameters.go @@ -0,0 +1,169 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package delegates + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// NewV1DelegatesDeleteParams creates a new V1DelegatesDeleteParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1DelegatesDeleteParams() *V1DelegatesDeleteParams { + return &V1DelegatesDeleteParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1DelegatesDeleteParamsWithTimeout creates a new V1DelegatesDeleteParams object +// with the ability to set a timeout on a request. +func NewV1DelegatesDeleteParamsWithTimeout(timeout time.Duration) *V1DelegatesDeleteParams { + return &V1DelegatesDeleteParams{ + timeout: timeout, + } +} + +// NewV1DelegatesDeleteParamsWithContext creates a new V1DelegatesDeleteParams object +// with the ability to set a context for a request. +func NewV1DelegatesDeleteParamsWithContext(ctx context.Context) *V1DelegatesDeleteParams { + return &V1DelegatesDeleteParams{ + Context: ctx, + } +} + +// NewV1DelegatesDeleteParamsWithHTTPClient creates a new V1DelegatesDeleteParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1DelegatesDeleteParamsWithHTTPClient(client *http.Client) *V1DelegatesDeleteParams { + return &V1DelegatesDeleteParams{ + HTTPClient: client, + } +} + +/* +V1DelegatesDeleteParams contains all the parameters to send to the API endpoint + + for the v1 delegates delete operation. + + Typically these are written to a http.Request. +*/ +type V1DelegatesDeleteParams struct { + + // Data. + Data *models.DelegateDelete + + // DelegateAddress. + DelegateAddress string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 delegates delete params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1DelegatesDeleteParams) WithDefaults() *V1DelegatesDeleteParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 delegates delete params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1DelegatesDeleteParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 delegates delete params +func (o *V1DelegatesDeleteParams) WithTimeout(timeout time.Duration) *V1DelegatesDeleteParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 delegates delete params +func (o *V1DelegatesDeleteParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 delegates delete params +func (o *V1DelegatesDeleteParams) WithContext(ctx context.Context) *V1DelegatesDeleteParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 delegates delete params +func (o *V1DelegatesDeleteParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 delegates delete params +func (o *V1DelegatesDeleteParams) WithHTTPClient(client *http.Client) *V1DelegatesDeleteParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 delegates delete params +func (o *V1DelegatesDeleteParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the v1 delegates delete params +func (o *V1DelegatesDeleteParams) WithData(data *models.DelegateDelete) *V1DelegatesDeleteParams { + o.SetData(data) + return o +} + +// SetData adds the data to the v1 delegates delete params +func (o *V1DelegatesDeleteParams) SetData(data *models.DelegateDelete) { + o.Data = data +} + +// WithDelegateAddress adds the delegateAddress to the v1 delegates delete params +func (o *V1DelegatesDeleteParams) WithDelegateAddress(delegateAddress string) *V1DelegatesDeleteParams { + o.SetDelegateAddress(delegateAddress) + return o +} + +// SetDelegateAddress adds the delegateAddress to the v1 delegates delete params +func (o *V1DelegatesDeleteParams) SetDelegateAddress(delegateAddress string) { + o.DelegateAddress = delegateAddress +} + +// WriteToRequest writes these params to a swagger request +func (o *V1DelegatesDeleteParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + // path param delegate_address + if err := r.SetPathParam("delegate_address", o.DelegateAddress); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/delegates/v1_delegates_delete_responses.go b/utils/safe_api/client/delegates/v1_delegates_delete_responses.go new file mode 100644 index 0000000..a80895f --- /dev/null +++ b/utils/safe_api/client/delegates/v1_delegates_delete_responses.go @@ -0,0 +1,274 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package delegates + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// V1DelegatesDeleteReader is a Reader for the V1DelegatesDelete structure. +type V1DelegatesDeleteReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1DelegatesDeleteReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 204: + result := NewV1DelegatesDeleteNoContent() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1DelegatesDeleteBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewV1DelegatesDeleteNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 422: + result := NewV1DelegatesDeleteUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /v1/delegates/{delegate_address}/] v1_delegates_delete", response, response.Code()) + } +} + +// NewV1DelegatesDeleteNoContent creates a V1DelegatesDeleteNoContent with default headers values +func NewV1DelegatesDeleteNoContent() *V1DelegatesDeleteNoContent { + return &V1DelegatesDeleteNoContent{} +} + +/* +V1DelegatesDeleteNoContent describes a response with status code 204, with default header values. + +Deleted +*/ +type V1DelegatesDeleteNoContent struct { +} + +// IsSuccess returns true when this v1 delegates delete no content response has a 2xx status code +func (o *V1DelegatesDeleteNoContent) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 delegates delete no content response has a 3xx status code +func (o *V1DelegatesDeleteNoContent) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 delegates delete no content response has a 4xx status code +func (o *V1DelegatesDeleteNoContent) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 delegates delete no content response has a 5xx status code +func (o *V1DelegatesDeleteNoContent) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 delegates delete no content response a status code equal to that given +func (o *V1DelegatesDeleteNoContent) IsCode(code int) bool { + return code == 204 +} + +// Code gets the status code for the v1 delegates delete no content response +func (o *V1DelegatesDeleteNoContent) Code() int { + return 204 +} + +func (o *V1DelegatesDeleteNoContent) Error() string { + return fmt.Sprintf("[DELETE /v1/delegates/{delegate_address}/][%d] v1DelegatesDeleteNoContent", 204) +} + +func (o *V1DelegatesDeleteNoContent) String() string { + return fmt.Sprintf("[DELETE /v1/delegates/{delegate_address}/][%d] v1DelegatesDeleteNoContent", 204) +} + +func (o *V1DelegatesDeleteNoContent) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1DelegatesDeleteBadRequest creates a V1DelegatesDeleteBadRequest with default headers values +func NewV1DelegatesDeleteBadRequest() *V1DelegatesDeleteBadRequest { + return &V1DelegatesDeleteBadRequest{} +} + +/* +V1DelegatesDeleteBadRequest describes a response with status code 400, with default header values. + +Malformed data +*/ +type V1DelegatesDeleteBadRequest struct { +} + +// IsSuccess returns true when this v1 delegates delete bad request response has a 2xx status code +func (o *V1DelegatesDeleteBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 delegates delete bad request response has a 3xx status code +func (o *V1DelegatesDeleteBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 delegates delete bad request response has a 4xx status code +func (o *V1DelegatesDeleteBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 delegates delete bad request response has a 5xx status code +func (o *V1DelegatesDeleteBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 delegates delete bad request response a status code equal to that given +func (o *V1DelegatesDeleteBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 delegates delete bad request response +func (o *V1DelegatesDeleteBadRequest) Code() int { + return 400 +} + +func (o *V1DelegatesDeleteBadRequest) Error() string { + return fmt.Sprintf("[DELETE /v1/delegates/{delegate_address}/][%d] v1DelegatesDeleteBadRequest", 400) +} + +func (o *V1DelegatesDeleteBadRequest) String() string { + return fmt.Sprintf("[DELETE /v1/delegates/{delegate_address}/][%d] v1DelegatesDeleteBadRequest", 400) +} + +func (o *V1DelegatesDeleteBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1DelegatesDeleteNotFound creates a V1DelegatesDeleteNotFound with default headers values +func NewV1DelegatesDeleteNotFound() *V1DelegatesDeleteNotFound { + return &V1DelegatesDeleteNotFound{} +} + +/* +V1DelegatesDeleteNotFound describes a response with status code 404, with default header values. + +Delegate not found +*/ +type V1DelegatesDeleteNotFound struct { +} + +// IsSuccess returns true when this v1 delegates delete not found response has a 2xx status code +func (o *V1DelegatesDeleteNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 delegates delete not found response has a 3xx status code +func (o *V1DelegatesDeleteNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 delegates delete not found response has a 4xx status code +func (o *V1DelegatesDeleteNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 delegates delete not found response has a 5xx status code +func (o *V1DelegatesDeleteNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 delegates delete not found response a status code equal to that given +func (o *V1DelegatesDeleteNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 delegates delete not found response +func (o *V1DelegatesDeleteNotFound) Code() int { + return 404 +} + +func (o *V1DelegatesDeleteNotFound) Error() string { + return fmt.Sprintf("[DELETE /v1/delegates/{delegate_address}/][%d] v1DelegatesDeleteNotFound", 404) +} + +func (o *V1DelegatesDeleteNotFound) String() string { + return fmt.Sprintf("[DELETE /v1/delegates/{delegate_address}/][%d] v1DelegatesDeleteNotFound", 404) +} + +func (o *V1DelegatesDeleteNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1DelegatesDeleteUnprocessableEntity creates a V1DelegatesDeleteUnprocessableEntity with default headers values +func NewV1DelegatesDeleteUnprocessableEntity() *V1DelegatesDeleteUnprocessableEntity { + return &V1DelegatesDeleteUnprocessableEntity{} +} + +/* +V1DelegatesDeleteUnprocessableEntity describes a response with status code 422, with default header values. + +Invalid Ethereum address/Error processing data +*/ +type V1DelegatesDeleteUnprocessableEntity struct { +} + +// IsSuccess returns true when this v1 delegates delete unprocessable entity response has a 2xx status code +func (o *V1DelegatesDeleteUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 delegates delete unprocessable entity response has a 3xx status code +func (o *V1DelegatesDeleteUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 delegates delete unprocessable entity response has a 4xx status code +func (o *V1DelegatesDeleteUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 delegates delete unprocessable entity response has a 5xx status code +func (o *V1DelegatesDeleteUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 delegates delete unprocessable entity response a status code equal to that given +func (o *V1DelegatesDeleteUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 delegates delete unprocessable entity response +func (o *V1DelegatesDeleteUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1DelegatesDeleteUnprocessableEntity) Error() string { + return fmt.Sprintf("[DELETE /v1/delegates/{delegate_address}/][%d] v1DelegatesDeleteUnprocessableEntity", 422) +} + +func (o *V1DelegatesDeleteUnprocessableEntity) String() string { + return fmt.Sprintf("[DELETE /v1/delegates/{delegate_address}/][%d] v1DelegatesDeleteUnprocessableEntity", 422) +} + +func (o *V1DelegatesDeleteUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/delegates/v1_delegates_list_parameters.go b/utils/safe_api/client/delegates/v1_delegates_list_parameters.go new file mode 100644 index 0000000..0d9d415 --- /dev/null +++ b/utils/safe_api/client/delegates/v1_delegates_list_parameters.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package delegates + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewV1DelegatesListParams creates a new V1DelegatesListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1DelegatesListParams() *V1DelegatesListParams { + return &V1DelegatesListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1DelegatesListParamsWithTimeout creates a new V1DelegatesListParams object +// with the ability to set a timeout on a request. +func NewV1DelegatesListParamsWithTimeout(timeout time.Duration) *V1DelegatesListParams { + return &V1DelegatesListParams{ + timeout: timeout, + } +} + +// NewV1DelegatesListParamsWithContext creates a new V1DelegatesListParams object +// with the ability to set a context for a request. +func NewV1DelegatesListParamsWithContext(ctx context.Context) *V1DelegatesListParams { + return &V1DelegatesListParams{ + Context: ctx, + } +} + +// NewV1DelegatesListParamsWithHTTPClient creates a new V1DelegatesListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1DelegatesListParamsWithHTTPClient(client *http.Client) *V1DelegatesListParams { + return &V1DelegatesListParams{ + HTTPClient: client, + } +} + +/* +V1DelegatesListParams contains all the parameters to send to the API endpoint + + for the v1 delegates list operation. + + Typically these are written to a http.Request. +*/ +type V1DelegatesListParams struct { + + /* Delegate. + + delegate + */ + Delegate *string + + /* Delegator. + + delegator + */ + Delegator *string + + /* Label. + + label + */ + Label *string + + /* Limit. + + Number of results to return per page. + */ + Limit *int64 + + /* Offset. + + The initial index from which to return the results. + */ + Offset *int64 + + /* Safe. + + safe + */ + Safe *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 delegates list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1DelegatesListParams) WithDefaults() *V1DelegatesListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 delegates list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1DelegatesListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 delegates list params +func (o *V1DelegatesListParams) WithTimeout(timeout time.Duration) *V1DelegatesListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 delegates list params +func (o *V1DelegatesListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 delegates list params +func (o *V1DelegatesListParams) WithContext(ctx context.Context) *V1DelegatesListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 delegates list params +func (o *V1DelegatesListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 delegates list params +func (o *V1DelegatesListParams) WithHTTPClient(client *http.Client) *V1DelegatesListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 delegates list params +func (o *V1DelegatesListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithDelegate adds the delegate to the v1 delegates list params +func (o *V1DelegatesListParams) WithDelegate(delegate *string) *V1DelegatesListParams { + o.SetDelegate(delegate) + return o +} + +// SetDelegate adds the delegate to the v1 delegates list params +func (o *V1DelegatesListParams) SetDelegate(delegate *string) { + o.Delegate = delegate +} + +// WithDelegator adds the delegator to the v1 delegates list params +func (o *V1DelegatesListParams) WithDelegator(delegator *string) *V1DelegatesListParams { + o.SetDelegator(delegator) + return o +} + +// SetDelegator adds the delegator to the v1 delegates list params +func (o *V1DelegatesListParams) SetDelegator(delegator *string) { + o.Delegator = delegator +} + +// WithLabel adds the label to the v1 delegates list params +func (o *V1DelegatesListParams) WithLabel(label *string) *V1DelegatesListParams { + o.SetLabel(label) + return o +} + +// SetLabel adds the label to the v1 delegates list params +func (o *V1DelegatesListParams) SetLabel(label *string) { + o.Label = label +} + +// WithLimit adds the limit to the v1 delegates list params +func (o *V1DelegatesListParams) WithLimit(limit *int64) *V1DelegatesListParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the v1 delegates list params +func (o *V1DelegatesListParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the v1 delegates list params +func (o *V1DelegatesListParams) WithOffset(offset *int64) *V1DelegatesListParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the v1 delegates list params +func (o *V1DelegatesListParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithSafe adds the safe to the v1 delegates list params +func (o *V1DelegatesListParams) WithSafe(safe *string) *V1DelegatesListParams { + o.SetSafe(safe) + return o +} + +// SetSafe adds the safe to the v1 delegates list params +func (o *V1DelegatesListParams) SetSafe(safe *string) { + o.Safe = safe +} + +// WriteToRequest writes these params to a swagger request +func (o *V1DelegatesListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Delegate != nil { + + // query param delegate + var qrDelegate string + + if o.Delegate != nil { + qrDelegate = *o.Delegate + } + qDelegate := qrDelegate + if qDelegate != "" { + + if err := r.SetQueryParam("delegate", qDelegate); err != nil { + return err + } + } + } + + if o.Delegator != nil { + + // query param delegator + var qrDelegator string + + if o.Delegator != nil { + qrDelegator = *o.Delegator + } + qDelegator := qrDelegator + if qDelegator != "" { + + if err := r.SetQueryParam("delegator", qDelegator); err != nil { + return err + } + } + } + + if o.Label != nil { + + // query param label + var qrLabel string + + if o.Label != nil { + qrLabel = *o.Label + } + qLabel := qrLabel + if qLabel != "" { + + if err := r.SetQueryParam("label", qLabel); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Safe != nil { + + // query param safe + var qrSafe string + + if o.Safe != nil { + qrSafe = *o.Safe + } + qSafe := qrSafe + if qSafe != "" { + + if err := r.SetQueryParam("safe", qSafe); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/delegates/v1_delegates_list_responses.go b/utils/safe_api/client/delegates/v1_delegates_list_responses.go new file mode 100644 index 0000000..7db7830 --- /dev/null +++ b/utils/safe_api/client/delegates/v1_delegates_list_responses.go @@ -0,0 +1,339 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package delegates + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + models "omni-balance/utils/safe_api" +) + +// V1DelegatesListReader is a Reader for the V1DelegatesList structure. +type V1DelegatesListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1DelegatesListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1DelegatesListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1DelegatesListBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/delegates/] v1_delegates_list", response, response.Code()) + } +} + +// NewV1DelegatesListOK creates a V1DelegatesListOK with default headers values +func NewV1DelegatesListOK() *V1DelegatesListOK { + return &V1DelegatesListOK{} +} + +/* +V1DelegatesListOK describes a response with status code 200, with default header values. + +V1DelegatesListOK v1 delegates list o k +*/ +type V1DelegatesListOK struct { + Payload *V1DelegatesListOKBody +} + +// IsSuccess returns true when this v1 delegates list o k response has a 2xx status code +func (o *V1DelegatesListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 delegates list o k response has a 3xx status code +func (o *V1DelegatesListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 delegates list o k response has a 4xx status code +func (o *V1DelegatesListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 delegates list o k response has a 5xx status code +func (o *V1DelegatesListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 delegates list o k response a status code equal to that given +func (o *V1DelegatesListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 delegates list o k response +func (o *V1DelegatesListOK) Code() int { + return 200 +} + +func (o *V1DelegatesListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/delegates/][%d] v1DelegatesListOK %s", 200, payload) +} + +func (o *V1DelegatesListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/delegates/][%d] v1DelegatesListOK %s", 200, payload) +} + +func (o *V1DelegatesListOK) GetPayload() *V1DelegatesListOKBody { + return o.Payload +} + +func (o *V1DelegatesListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(V1DelegatesListOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1DelegatesListBadRequest creates a V1DelegatesListBadRequest with default headers values +func NewV1DelegatesListBadRequest() *V1DelegatesListBadRequest { + return &V1DelegatesListBadRequest{} +} + +/* +V1DelegatesListBadRequest describes a response with status code 400, with default header values. + +Invalid data +*/ +type V1DelegatesListBadRequest struct { +} + +// IsSuccess returns true when this v1 delegates list bad request response has a 2xx status code +func (o *V1DelegatesListBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 delegates list bad request response has a 3xx status code +func (o *V1DelegatesListBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 delegates list bad request response has a 4xx status code +func (o *V1DelegatesListBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 delegates list bad request response has a 5xx status code +func (o *V1DelegatesListBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 delegates list bad request response a status code equal to that given +func (o *V1DelegatesListBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 delegates list bad request response +func (o *V1DelegatesListBadRequest) Code() int { + return 400 +} + +func (o *V1DelegatesListBadRequest) Error() string { + return fmt.Sprintf("[GET /v1/delegates/][%d] v1DelegatesListBadRequest", 400) +} + +func (o *V1DelegatesListBadRequest) String() string { + return fmt.Sprintf("[GET /v1/delegates/][%d] v1DelegatesListBadRequest", 400) +} + +func (o *V1DelegatesListBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +/* +V1DelegatesListOKBody v1 delegates list o k body +swagger:model V1DelegatesListOKBody +*/ +type V1DelegatesListOKBody struct { + + // count + // Required: true + Count *int64 `json:"count"` + + // next + // Format: uri + Next *strfmt.URI `json:"next,omitempty"` + + // previous + // Format: uri + Previous *strfmt.URI `json:"previous,omitempty"` + + // results + // Required: true + Results []*models.SafeDelegateResponse `json:"results"` +} + +// Validate validates this v1 delegates list o k body +func (o *V1DelegatesListOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateCount(formats); err != nil { + res = append(res, err) + } + + if err := o.validateNext(formats); err != nil { + res = append(res, err) + } + + if err := o.validatePrevious(formats); err != nil { + res = append(res, err) + } + + if err := o.validateResults(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V1DelegatesListOKBody) validateCount(formats strfmt.Registry) error { + + if err := validate.Required("v1DelegatesListOK"+"."+"count", "body", o.Count); err != nil { + return err + } + + return nil +} + +func (o *V1DelegatesListOKBody) validateNext(formats strfmt.Registry) error { + if swag.IsZero(o.Next) { // not required + return nil + } + + if err := validate.FormatOf("v1DelegatesListOK"+"."+"next", "body", "uri", o.Next.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V1DelegatesListOKBody) validatePrevious(formats strfmt.Registry) error { + if swag.IsZero(o.Previous) { // not required + return nil + } + + if err := validate.FormatOf("v1DelegatesListOK"+"."+"previous", "body", "uri", o.Previous.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V1DelegatesListOKBody) validateResults(formats strfmt.Registry) error { + + if err := validate.Required("v1DelegatesListOK"+"."+"results", "body", o.Results); err != nil { + return err + } + + for i := 0; i < len(o.Results); i++ { + if swag.IsZero(o.Results[i]) { // not required + continue + } + + if o.Results[i] != nil { + if err := o.Results[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v1DelegatesListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v1DelegatesListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this v1 delegates list o k body based on the context it is used +func (o *V1DelegatesListOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResults(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V1DelegatesListOKBody) contextValidateResults(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Results); i++ { + + if o.Results[i] != nil { + + if swag.IsZero(o.Results[i]) { // not required + return nil + } + + if err := o.Results[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v1DelegatesListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v1DelegatesListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *V1DelegatesListOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *V1DelegatesListOKBody) UnmarshalBinary(b []byte) error { + var res V1DelegatesListOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/utils/safe_api/client/delegates/v2_delegates_create_parameters.go b/utils/safe_api/client/delegates/v2_delegates_create_parameters.go new file mode 100644 index 0000000..14209f1 --- /dev/null +++ b/utils/safe_api/client/delegates/v2_delegates_create_parameters.go @@ -0,0 +1,150 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package delegates + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// NewV2DelegatesCreateParams creates a new V2DelegatesCreateParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV2DelegatesCreateParams() *V2DelegatesCreateParams { + return &V2DelegatesCreateParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV2DelegatesCreateParamsWithTimeout creates a new V2DelegatesCreateParams object +// with the ability to set a timeout on a request. +func NewV2DelegatesCreateParamsWithTimeout(timeout time.Duration) *V2DelegatesCreateParams { + return &V2DelegatesCreateParams{ + timeout: timeout, + } +} + +// NewV2DelegatesCreateParamsWithContext creates a new V2DelegatesCreateParams object +// with the ability to set a context for a request. +func NewV2DelegatesCreateParamsWithContext(ctx context.Context) *V2DelegatesCreateParams { + return &V2DelegatesCreateParams{ + Context: ctx, + } +} + +// NewV2DelegatesCreateParamsWithHTTPClient creates a new V2DelegatesCreateParams object +// with the ability to set a custom HTTPClient for a request. +func NewV2DelegatesCreateParamsWithHTTPClient(client *http.Client) *V2DelegatesCreateParams { + return &V2DelegatesCreateParams{ + HTTPClient: client, + } +} + +/* +V2DelegatesCreateParams contains all the parameters to send to the API endpoint + + for the v2 delegates create operation. + + Typically these are written to a http.Request. +*/ +type V2DelegatesCreateParams struct { + + // Data. + Data *models.DelegateSerializerV2 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v2 delegates create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V2DelegatesCreateParams) WithDefaults() *V2DelegatesCreateParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v2 delegates create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V2DelegatesCreateParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v2 delegates create params +func (o *V2DelegatesCreateParams) WithTimeout(timeout time.Duration) *V2DelegatesCreateParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v2 delegates create params +func (o *V2DelegatesCreateParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v2 delegates create params +func (o *V2DelegatesCreateParams) WithContext(ctx context.Context) *V2DelegatesCreateParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v2 delegates create params +func (o *V2DelegatesCreateParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v2 delegates create params +func (o *V2DelegatesCreateParams) WithHTTPClient(client *http.Client) *V2DelegatesCreateParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v2 delegates create params +func (o *V2DelegatesCreateParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the v2 delegates create params +func (o *V2DelegatesCreateParams) WithData(data *models.DelegateSerializerV2) *V2DelegatesCreateParams { + o.SetData(data) + return o +} + +// SetData adds the data to the v2 delegates create params +func (o *V2DelegatesCreateParams) SetData(data *models.DelegateSerializerV2) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *V2DelegatesCreateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/delegates/v2_delegates_create_responses.go b/utils/safe_api/client/delegates/v2_delegates_create_responses.go new file mode 100644 index 0000000..500d9e9 --- /dev/null +++ b/utils/safe_api/client/delegates/v2_delegates_create_responses.go @@ -0,0 +1,150 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package delegates + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// V2DelegatesCreateReader is a Reader for the V2DelegatesCreate structure. +type V2DelegatesCreateReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V2DelegatesCreateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 202: + result := NewV2DelegatesCreateAccepted() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV2DelegatesCreateBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /v2/delegates/] v2_delegates_create", response, response.Code()) + } +} + +// NewV2DelegatesCreateAccepted creates a V2DelegatesCreateAccepted with default headers values +func NewV2DelegatesCreateAccepted() *V2DelegatesCreateAccepted { + return &V2DelegatesCreateAccepted{} +} + +/* +V2DelegatesCreateAccepted describes a response with status code 202, with default header values. + +Accepted +*/ +type V2DelegatesCreateAccepted struct { +} + +// IsSuccess returns true when this v2 delegates create accepted response has a 2xx status code +func (o *V2DelegatesCreateAccepted) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v2 delegates create accepted response has a 3xx status code +func (o *V2DelegatesCreateAccepted) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v2 delegates create accepted response has a 4xx status code +func (o *V2DelegatesCreateAccepted) IsClientError() bool { + return false +} + +// IsServerError returns true when this v2 delegates create accepted response has a 5xx status code +func (o *V2DelegatesCreateAccepted) IsServerError() bool { + return false +} + +// IsCode returns true when this v2 delegates create accepted response a status code equal to that given +func (o *V2DelegatesCreateAccepted) IsCode(code int) bool { + return code == 202 +} + +// Code gets the status code for the v2 delegates create accepted response +func (o *V2DelegatesCreateAccepted) Code() int { + return 202 +} + +func (o *V2DelegatesCreateAccepted) Error() string { + return fmt.Sprintf("[POST /v2/delegates/][%d] v2DelegatesCreateAccepted", 202) +} + +func (o *V2DelegatesCreateAccepted) String() string { + return fmt.Sprintf("[POST /v2/delegates/][%d] v2DelegatesCreateAccepted", 202) +} + +func (o *V2DelegatesCreateAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV2DelegatesCreateBadRequest creates a V2DelegatesCreateBadRequest with default headers values +func NewV2DelegatesCreateBadRequest() *V2DelegatesCreateBadRequest { + return &V2DelegatesCreateBadRequest{} +} + +/* +V2DelegatesCreateBadRequest describes a response with status code 400, with default header values. + +Malformed data +*/ +type V2DelegatesCreateBadRequest struct { +} + +// IsSuccess returns true when this v2 delegates create bad request response has a 2xx status code +func (o *V2DelegatesCreateBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v2 delegates create bad request response has a 3xx status code +func (o *V2DelegatesCreateBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v2 delegates create bad request response has a 4xx status code +func (o *V2DelegatesCreateBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v2 delegates create bad request response has a 5xx status code +func (o *V2DelegatesCreateBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v2 delegates create bad request response a status code equal to that given +func (o *V2DelegatesCreateBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v2 delegates create bad request response +func (o *V2DelegatesCreateBadRequest) Code() int { + return 400 +} + +func (o *V2DelegatesCreateBadRequest) Error() string { + return fmt.Sprintf("[POST /v2/delegates/][%d] v2DelegatesCreateBadRequest", 400) +} + +func (o *V2DelegatesCreateBadRequest) String() string { + return fmt.Sprintf("[POST /v2/delegates/][%d] v2DelegatesCreateBadRequest", 400) +} + +func (o *V2DelegatesCreateBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/delegates/v2_delegates_delete_parameters.go b/utils/safe_api/client/delegates/v2_delegates_delete_parameters.go new file mode 100644 index 0000000..1e528d0 --- /dev/null +++ b/utils/safe_api/client/delegates/v2_delegates_delete_parameters.go @@ -0,0 +1,169 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package delegates + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// NewV2DelegatesDeleteParams creates a new V2DelegatesDeleteParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV2DelegatesDeleteParams() *V2DelegatesDeleteParams { + return &V2DelegatesDeleteParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV2DelegatesDeleteParamsWithTimeout creates a new V2DelegatesDeleteParams object +// with the ability to set a timeout on a request. +func NewV2DelegatesDeleteParamsWithTimeout(timeout time.Duration) *V2DelegatesDeleteParams { + return &V2DelegatesDeleteParams{ + timeout: timeout, + } +} + +// NewV2DelegatesDeleteParamsWithContext creates a new V2DelegatesDeleteParams object +// with the ability to set a context for a request. +func NewV2DelegatesDeleteParamsWithContext(ctx context.Context) *V2DelegatesDeleteParams { + return &V2DelegatesDeleteParams{ + Context: ctx, + } +} + +// NewV2DelegatesDeleteParamsWithHTTPClient creates a new V2DelegatesDeleteParams object +// with the ability to set a custom HTTPClient for a request. +func NewV2DelegatesDeleteParamsWithHTTPClient(client *http.Client) *V2DelegatesDeleteParams { + return &V2DelegatesDeleteParams{ + HTTPClient: client, + } +} + +/* +V2DelegatesDeleteParams contains all the parameters to send to the API endpoint + + for the v2 delegates delete operation. + + Typically these are written to a http.Request. +*/ +type V2DelegatesDeleteParams struct { + + // Data. + Data *models.DelegateDeleteSerializerV2 + + // DelegateAddress. + DelegateAddress string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v2 delegates delete params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V2DelegatesDeleteParams) WithDefaults() *V2DelegatesDeleteParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v2 delegates delete params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V2DelegatesDeleteParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v2 delegates delete params +func (o *V2DelegatesDeleteParams) WithTimeout(timeout time.Duration) *V2DelegatesDeleteParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v2 delegates delete params +func (o *V2DelegatesDeleteParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v2 delegates delete params +func (o *V2DelegatesDeleteParams) WithContext(ctx context.Context) *V2DelegatesDeleteParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v2 delegates delete params +func (o *V2DelegatesDeleteParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v2 delegates delete params +func (o *V2DelegatesDeleteParams) WithHTTPClient(client *http.Client) *V2DelegatesDeleteParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v2 delegates delete params +func (o *V2DelegatesDeleteParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the v2 delegates delete params +func (o *V2DelegatesDeleteParams) WithData(data *models.DelegateDeleteSerializerV2) *V2DelegatesDeleteParams { + o.SetData(data) + return o +} + +// SetData adds the data to the v2 delegates delete params +func (o *V2DelegatesDeleteParams) SetData(data *models.DelegateDeleteSerializerV2) { + o.Data = data +} + +// WithDelegateAddress adds the delegateAddress to the v2 delegates delete params +func (o *V2DelegatesDeleteParams) WithDelegateAddress(delegateAddress string) *V2DelegatesDeleteParams { + o.SetDelegateAddress(delegateAddress) + return o +} + +// SetDelegateAddress adds the delegateAddress to the v2 delegates delete params +func (o *V2DelegatesDeleteParams) SetDelegateAddress(delegateAddress string) { + o.DelegateAddress = delegateAddress +} + +// WriteToRequest writes these params to a swagger request +func (o *V2DelegatesDeleteParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + // path param delegate_address + if err := r.SetPathParam("delegate_address", o.DelegateAddress); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/delegates/v2_delegates_delete_responses.go b/utils/safe_api/client/delegates/v2_delegates_delete_responses.go new file mode 100644 index 0000000..53968b3 --- /dev/null +++ b/utils/safe_api/client/delegates/v2_delegates_delete_responses.go @@ -0,0 +1,274 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package delegates + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// V2DelegatesDeleteReader is a Reader for the V2DelegatesDelete structure. +type V2DelegatesDeleteReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V2DelegatesDeleteReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 204: + result := NewV2DelegatesDeleteNoContent() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV2DelegatesDeleteBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewV2DelegatesDeleteNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 422: + result := NewV2DelegatesDeleteUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /v2/delegates/{delegate_address}/] v2_delegates_delete", response, response.Code()) + } +} + +// NewV2DelegatesDeleteNoContent creates a V2DelegatesDeleteNoContent with default headers values +func NewV2DelegatesDeleteNoContent() *V2DelegatesDeleteNoContent { + return &V2DelegatesDeleteNoContent{} +} + +/* +V2DelegatesDeleteNoContent describes a response with status code 204, with default header values. + +Deleted +*/ +type V2DelegatesDeleteNoContent struct { +} + +// IsSuccess returns true when this v2 delegates delete no content response has a 2xx status code +func (o *V2DelegatesDeleteNoContent) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v2 delegates delete no content response has a 3xx status code +func (o *V2DelegatesDeleteNoContent) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v2 delegates delete no content response has a 4xx status code +func (o *V2DelegatesDeleteNoContent) IsClientError() bool { + return false +} + +// IsServerError returns true when this v2 delegates delete no content response has a 5xx status code +func (o *V2DelegatesDeleteNoContent) IsServerError() bool { + return false +} + +// IsCode returns true when this v2 delegates delete no content response a status code equal to that given +func (o *V2DelegatesDeleteNoContent) IsCode(code int) bool { + return code == 204 +} + +// Code gets the status code for the v2 delegates delete no content response +func (o *V2DelegatesDeleteNoContent) Code() int { + return 204 +} + +func (o *V2DelegatesDeleteNoContent) Error() string { + return fmt.Sprintf("[DELETE /v2/delegates/{delegate_address}/][%d] v2DelegatesDeleteNoContent", 204) +} + +func (o *V2DelegatesDeleteNoContent) String() string { + return fmt.Sprintf("[DELETE /v2/delegates/{delegate_address}/][%d] v2DelegatesDeleteNoContent", 204) +} + +func (o *V2DelegatesDeleteNoContent) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV2DelegatesDeleteBadRequest creates a V2DelegatesDeleteBadRequest with default headers values +func NewV2DelegatesDeleteBadRequest() *V2DelegatesDeleteBadRequest { + return &V2DelegatesDeleteBadRequest{} +} + +/* +V2DelegatesDeleteBadRequest describes a response with status code 400, with default header values. + +Malformed data +*/ +type V2DelegatesDeleteBadRequest struct { +} + +// IsSuccess returns true when this v2 delegates delete bad request response has a 2xx status code +func (o *V2DelegatesDeleteBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v2 delegates delete bad request response has a 3xx status code +func (o *V2DelegatesDeleteBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v2 delegates delete bad request response has a 4xx status code +func (o *V2DelegatesDeleteBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v2 delegates delete bad request response has a 5xx status code +func (o *V2DelegatesDeleteBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v2 delegates delete bad request response a status code equal to that given +func (o *V2DelegatesDeleteBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v2 delegates delete bad request response +func (o *V2DelegatesDeleteBadRequest) Code() int { + return 400 +} + +func (o *V2DelegatesDeleteBadRequest) Error() string { + return fmt.Sprintf("[DELETE /v2/delegates/{delegate_address}/][%d] v2DelegatesDeleteBadRequest", 400) +} + +func (o *V2DelegatesDeleteBadRequest) String() string { + return fmt.Sprintf("[DELETE /v2/delegates/{delegate_address}/][%d] v2DelegatesDeleteBadRequest", 400) +} + +func (o *V2DelegatesDeleteBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV2DelegatesDeleteNotFound creates a V2DelegatesDeleteNotFound with default headers values +func NewV2DelegatesDeleteNotFound() *V2DelegatesDeleteNotFound { + return &V2DelegatesDeleteNotFound{} +} + +/* +V2DelegatesDeleteNotFound describes a response with status code 404, with default header values. + +Delegate not found +*/ +type V2DelegatesDeleteNotFound struct { +} + +// IsSuccess returns true when this v2 delegates delete not found response has a 2xx status code +func (o *V2DelegatesDeleteNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v2 delegates delete not found response has a 3xx status code +func (o *V2DelegatesDeleteNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v2 delegates delete not found response has a 4xx status code +func (o *V2DelegatesDeleteNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v2 delegates delete not found response has a 5xx status code +func (o *V2DelegatesDeleteNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v2 delegates delete not found response a status code equal to that given +func (o *V2DelegatesDeleteNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v2 delegates delete not found response +func (o *V2DelegatesDeleteNotFound) Code() int { + return 404 +} + +func (o *V2DelegatesDeleteNotFound) Error() string { + return fmt.Sprintf("[DELETE /v2/delegates/{delegate_address}/][%d] v2DelegatesDeleteNotFound", 404) +} + +func (o *V2DelegatesDeleteNotFound) String() string { + return fmt.Sprintf("[DELETE /v2/delegates/{delegate_address}/][%d] v2DelegatesDeleteNotFound", 404) +} + +func (o *V2DelegatesDeleteNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV2DelegatesDeleteUnprocessableEntity creates a V2DelegatesDeleteUnprocessableEntity with default headers values +func NewV2DelegatesDeleteUnprocessableEntity() *V2DelegatesDeleteUnprocessableEntity { + return &V2DelegatesDeleteUnprocessableEntity{} +} + +/* +V2DelegatesDeleteUnprocessableEntity describes a response with status code 422, with default header values. + +Invalid Ethereum address/Error processing data +*/ +type V2DelegatesDeleteUnprocessableEntity struct { +} + +// IsSuccess returns true when this v2 delegates delete unprocessable entity response has a 2xx status code +func (o *V2DelegatesDeleteUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v2 delegates delete unprocessable entity response has a 3xx status code +func (o *V2DelegatesDeleteUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v2 delegates delete unprocessable entity response has a 4xx status code +func (o *V2DelegatesDeleteUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v2 delegates delete unprocessable entity response has a 5xx status code +func (o *V2DelegatesDeleteUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v2 delegates delete unprocessable entity response a status code equal to that given +func (o *V2DelegatesDeleteUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v2 delegates delete unprocessable entity response +func (o *V2DelegatesDeleteUnprocessableEntity) Code() int { + return 422 +} + +func (o *V2DelegatesDeleteUnprocessableEntity) Error() string { + return fmt.Sprintf("[DELETE /v2/delegates/{delegate_address}/][%d] v2DelegatesDeleteUnprocessableEntity", 422) +} + +func (o *V2DelegatesDeleteUnprocessableEntity) String() string { + return fmt.Sprintf("[DELETE /v2/delegates/{delegate_address}/][%d] v2DelegatesDeleteUnprocessableEntity", 422) +} + +func (o *V2DelegatesDeleteUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/delegates/v2_delegates_list_parameters.go b/utils/safe_api/client/delegates/v2_delegates_list_parameters.go new file mode 100644 index 0000000..6f40558 --- /dev/null +++ b/utils/safe_api/client/delegates/v2_delegates_list_parameters.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package delegates + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewV2DelegatesListParams creates a new V2DelegatesListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV2DelegatesListParams() *V2DelegatesListParams { + return &V2DelegatesListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV2DelegatesListParamsWithTimeout creates a new V2DelegatesListParams object +// with the ability to set a timeout on a request. +func NewV2DelegatesListParamsWithTimeout(timeout time.Duration) *V2DelegatesListParams { + return &V2DelegatesListParams{ + timeout: timeout, + } +} + +// NewV2DelegatesListParamsWithContext creates a new V2DelegatesListParams object +// with the ability to set a context for a request. +func NewV2DelegatesListParamsWithContext(ctx context.Context) *V2DelegatesListParams { + return &V2DelegatesListParams{ + Context: ctx, + } +} + +// NewV2DelegatesListParamsWithHTTPClient creates a new V2DelegatesListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV2DelegatesListParamsWithHTTPClient(client *http.Client) *V2DelegatesListParams { + return &V2DelegatesListParams{ + HTTPClient: client, + } +} + +/* +V2DelegatesListParams contains all the parameters to send to the API endpoint + + for the v2 delegates list operation. + + Typically these are written to a http.Request. +*/ +type V2DelegatesListParams struct { + + /* Delegate. + + delegate + */ + Delegate *string + + /* Delegator. + + delegator + */ + Delegator *string + + /* Label. + + label + */ + Label *string + + /* Limit. + + Number of results to return per page. + */ + Limit *int64 + + /* Offset. + + The initial index from which to return the results. + */ + Offset *int64 + + /* Safe. + + safe + */ + Safe *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v2 delegates list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V2DelegatesListParams) WithDefaults() *V2DelegatesListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v2 delegates list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V2DelegatesListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v2 delegates list params +func (o *V2DelegatesListParams) WithTimeout(timeout time.Duration) *V2DelegatesListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v2 delegates list params +func (o *V2DelegatesListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v2 delegates list params +func (o *V2DelegatesListParams) WithContext(ctx context.Context) *V2DelegatesListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v2 delegates list params +func (o *V2DelegatesListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v2 delegates list params +func (o *V2DelegatesListParams) WithHTTPClient(client *http.Client) *V2DelegatesListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v2 delegates list params +func (o *V2DelegatesListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithDelegate adds the delegate to the v2 delegates list params +func (o *V2DelegatesListParams) WithDelegate(delegate *string) *V2DelegatesListParams { + o.SetDelegate(delegate) + return o +} + +// SetDelegate adds the delegate to the v2 delegates list params +func (o *V2DelegatesListParams) SetDelegate(delegate *string) { + o.Delegate = delegate +} + +// WithDelegator adds the delegator to the v2 delegates list params +func (o *V2DelegatesListParams) WithDelegator(delegator *string) *V2DelegatesListParams { + o.SetDelegator(delegator) + return o +} + +// SetDelegator adds the delegator to the v2 delegates list params +func (o *V2DelegatesListParams) SetDelegator(delegator *string) { + o.Delegator = delegator +} + +// WithLabel adds the label to the v2 delegates list params +func (o *V2DelegatesListParams) WithLabel(label *string) *V2DelegatesListParams { + o.SetLabel(label) + return o +} + +// SetLabel adds the label to the v2 delegates list params +func (o *V2DelegatesListParams) SetLabel(label *string) { + o.Label = label +} + +// WithLimit adds the limit to the v2 delegates list params +func (o *V2DelegatesListParams) WithLimit(limit *int64) *V2DelegatesListParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the v2 delegates list params +func (o *V2DelegatesListParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the v2 delegates list params +func (o *V2DelegatesListParams) WithOffset(offset *int64) *V2DelegatesListParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the v2 delegates list params +func (o *V2DelegatesListParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithSafe adds the safe to the v2 delegates list params +func (o *V2DelegatesListParams) WithSafe(safe *string) *V2DelegatesListParams { + o.SetSafe(safe) + return o +} + +// SetSafe adds the safe to the v2 delegates list params +func (o *V2DelegatesListParams) SetSafe(safe *string) { + o.Safe = safe +} + +// WriteToRequest writes these params to a swagger request +func (o *V2DelegatesListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Delegate != nil { + + // query param delegate + var qrDelegate string + + if o.Delegate != nil { + qrDelegate = *o.Delegate + } + qDelegate := qrDelegate + if qDelegate != "" { + + if err := r.SetQueryParam("delegate", qDelegate); err != nil { + return err + } + } + } + + if o.Delegator != nil { + + // query param delegator + var qrDelegator string + + if o.Delegator != nil { + qrDelegator = *o.Delegator + } + qDelegator := qrDelegator + if qDelegator != "" { + + if err := r.SetQueryParam("delegator", qDelegator); err != nil { + return err + } + } + } + + if o.Label != nil { + + // query param label + var qrLabel string + + if o.Label != nil { + qrLabel = *o.Label + } + qLabel := qrLabel + if qLabel != "" { + + if err := r.SetQueryParam("label", qLabel); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Safe != nil { + + // query param safe + var qrSafe string + + if o.Safe != nil { + qrSafe = *o.Safe + } + qSafe := qrSafe + if qSafe != "" { + + if err := r.SetQueryParam("safe", qSafe); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/delegates/v2_delegates_list_responses.go b/utils/safe_api/client/delegates/v2_delegates_list_responses.go new file mode 100644 index 0000000..3c1b90f --- /dev/null +++ b/utils/safe_api/client/delegates/v2_delegates_list_responses.go @@ -0,0 +1,339 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package delegates + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + models "omni-balance/utils/safe_api" +) + +// V2DelegatesListReader is a Reader for the V2DelegatesList structure. +type V2DelegatesListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V2DelegatesListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV2DelegatesListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV2DelegatesListBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v2/delegates/] v2_delegates_list", response, response.Code()) + } +} + +// NewV2DelegatesListOK creates a V2DelegatesListOK with default headers values +func NewV2DelegatesListOK() *V2DelegatesListOK { + return &V2DelegatesListOK{} +} + +/* +V2DelegatesListOK describes a response with status code 200, with default header values. + +V2DelegatesListOK v2 delegates list o k +*/ +type V2DelegatesListOK struct { + Payload *V2DelegatesListOKBody +} + +// IsSuccess returns true when this v2 delegates list o k response has a 2xx status code +func (o *V2DelegatesListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v2 delegates list o k response has a 3xx status code +func (o *V2DelegatesListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v2 delegates list o k response has a 4xx status code +func (o *V2DelegatesListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v2 delegates list o k response has a 5xx status code +func (o *V2DelegatesListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v2 delegates list o k response a status code equal to that given +func (o *V2DelegatesListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v2 delegates list o k response +func (o *V2DelegatesListOK) Code() int { + return 200 +} + +func (o *V2DelegatesListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v2/delegates/][%d] v2DelegatesListOK %s", 200, payload) +} + +func (o *V2DelegatesListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v2/delegates/][%d] v2DelegatesListOK %s", 200, payload) +} + +func (o *V2DelegatesListOK) GetPayload() *V2DelegatesListOKBody { + return o.Payload +} + +func (o *V2DelegatesListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(V2DelegatesListOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV2DelegatesListBadRequest creates a V2DelegatesListBadRequest with default headers values +func NewV2DelegatesListBadRequest() *V2DelegatesListBadRequest { + return &V2DelegatesListBadRequest{} +} + +/* +V2DelegatesListBadRequest describes a response with status code 400, with default header values. + +Invalid data +*/ +type V2DelegatesListBadRequest struct { +} + +// IsSuccess returns true when this v2 delegates list bad request response has a 2xx status code +func (o *V2DelegatesListBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v2 delegates list bad request response has a 3xx status code +func (o *V2DelegatesListBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v2 delegates list bad request response has a 4xx status code +func (o *V2DelegatesListBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v2 delegates list bad request response has a 5xx status code +func (o *V2DelegatesListBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v2 delegates list bad request response a status code equal to that given +func (o *V2DelegatesListBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v2 delegates list bad request response +func (o *V2DelegatesListBadRequest) Code() int { + return 400 +} + +func (o *V2DelegatesListBadRequest) Error() string { + return fmt.Sprintf("[GET /v2/delegates/][%d] v2DelegatesListBadRequest", 400) +} + +func (o *V2DelegatesListBadRequest) String() string { + return fmt.Sprintf("[GET /v2/delegates/][%d] v2DelegatesListBadRequest", 400) +} + +func (o *V2DelegatesListBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +/* +V2DelegatesListOKBody v2 delegates list o k body +swagger:model V2DelegatesListOKBody +*/ +type V2DelegatesListOKBody struct { + + // count + // Required: true + Count *int64 `json:"count"` + + // next + // Format: uri + Next *strfmt.URI `json:"next,omitempty"` + + // previous + // Format: uri + Previous *strfmt.URI `json:"previous,omitempty"` + + // results + // Required: true + Results []*models.SafeDelegateResponse `json:"results"` +} + +// Validate validates this v2 delegates list o k body +func (o *V2DelegatesListOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateCount(formats); err != nil { + res = append(res, err) + } + + if err := o.validateNext(formats); err != nil { + res = append(res, err) + } + + if err := o.validatePrevious(formats); err != nil { + res = append(res, err) + } + + if err := o.validateResults(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V2DelegatesListOKBody) validateCount(formats strfmt.Registry) error { + + if err := validate.Required("v2DelegatesListOK"+"."+"count", "body", o.Count); err != nil { + return err + } + + return nil +} + +func (o *V2DelegatesListOKBody) validateNext(formats strfmt.Registry) error { + if swag.IsZero(o.Next) { // not required + return nil + } + + if err := validate.FormatOf("v2DelegatesListOK"+"."+"next", "body", "uri", o.Next.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V2DelegatesListOKBody) validatePrevious(formats strfmt.Registry) error { + if swag.IsZero(o.Previous) { // not required + return nil + } + + if err := validate.FormatOf("v2DelegatesListOK"+"."+"previous", "body", "uri", o.Previous.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V2DelegatesListOKBody) validateResults(formats strfmt.Registry) error { + + if err := validate.Required("v2DelegatesListOK"+"."+"results", "body", o.Results); err != nil { + return err + } + + for i := 0; i < len(o.Results); i++ { + if swag.IsZero(o.Results[i]) { // not required + continue + } + + if o.Results[i] != nil { + if err := o.Results[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v2DelegatesListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v2DelegatesListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this v2 delegates list o k body based on the context it is used +func (o *V2DelegatesListOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResults(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V2DelegatesListOKBody) contextValidateResults(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Results); i++ { + + if o.Results[i] != nil { + + if swag.IsZero(o.Results[i]) { // not required + return nil + } + + if err := o.Results[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v2DelegatesListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v2DelegatesListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *V2DelegatesListOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *V2DelegatesListOKBody) UnmarshalBinary(b []byte) error { + var res V2DelegatesListOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/utils/safe_api/client/messages/messages_client.go b/utils/safe_api/client/messages/messages_client.go new file mode 100644 index 0000000..35f1057 --- /dev/null +++ b/utils/safe_api/client/messages/messages_client.go @@ -0,0 +1,235 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package messages + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// New creates a new messages API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +// New creates a new messages API client with basic auth credentials. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - user: user for basic authentication header. +// - password: password for basic authentication header. +func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BasicAuth(user, password) + return &Client{transport: transport, formats: strfmt.Default} +} + +// New creates a new messages API client with a bearer token for authentication. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - bearerToken: bearer token for Bearer authentication header. +func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) + return &Client{transport: transport, formats: strfmt.Default} +} + +/* +Client for messages API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption may be used to customize the behavior of Client methods. +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + V1MessagesRead(params *V1MessagesReadParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1MessagesReadOK, error) + + V1MessagesSignaturesCreate(params *V1MessagesSignaturesCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1MessagesSignaturesCreateCreated, error) + + V1SafesMessagesCreate(params *V1SafesMessagesCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesMessagesCreateCreated, error) + + V1SafesMessagesList(params *V1SafesMessagesListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesMessagesListOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +V1MessagesRead v1 messages read API +*/ +func (a *Client) V1MessagesRead(params *V1MessagesReadParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1MessagesReadOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1MessagesReadParams() + } + op := &runtime.ClientOperation{ + ID: "v1_messages_read", + Method: "GET", + PathPattern: "/v1/messages/{message_hash}/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1MessagesReadReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1MessagesReadOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_messages_read: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1MessagesSignaturesCreate v1 messages signatures create API +*/ +func (a *Client) V1MessagesSignaturesCreate(params *V1MessagesSignaturesCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1MessagesSignaturesCreateCreated, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1MessagesSignaturesCreateParams() + } + op := &runtime.ClientOperation{ + ID: "v1_messages_signatures_create", + Method: "POST", + PathPattern: "/v1/messages/{message_hash}/signatures/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1MessagesSignaturesCreateReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1MessagesSignaturesCreateCreated) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_messages_signatures_create: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* + V1SafesMessagesCreate Create a new signed message for a Safe. Message can be: + +- A “string“, so “EIP191“ will be used to get the hash. +- An “EIP712“ “object“. + +Hash will be calculated from the provided “message“. Sending a raw “hash“ will not be accepted, +service needs to derive it itself. +*/ +func (a *Client) V1SafesMessagesCreate(params *V1SafesMessagesCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesMessagesCreateCreated, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SafesMessagesCreateParams() + } + op := &runtime.ClientOperation{ + ID: "v1_safes_messages_create", + Method: "POST", + PathPattern: "/v1/safes/{address}/messages/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1SafesMessagesCreateReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SafesMessagesCreateCreated) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_safes_messages_create: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1SafesMessagesList v1 safes messages list API +*/ +func (a *Client) V1SafesMessagesList(params *V1SafesMessagesListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesMessagesListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SafesMessagesListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_safes_messages_list", + Method: "GET", + PathPattern: "/v1/safes/{address}/messages/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1SafesMessagesListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SafesMessagesListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_safes_messages_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/utils/safe_api/client/messages/v1_messages_read_parameters.go b/utils/safe_api/client/messages/v1_messages_read_parameters.go new file mode 100644 index 0000000..47b25c8 --- /dev/null +++ b/utils/safe_api/client/messages/v1_messages_read_parameters.go @@ -0,0 +1,156 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package messages + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "io" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1MessagesReadParams creates a new V1MessagesReadParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1MessagesReadParams() *V1MessagesReadParams { + return &V1MessagesReadParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1MessagesReadParamsWithTimeout creates a new V1MessagesReadParams object +// with the ability to set a timeout on a request. +func NewV1MessagesReadParamsWithTimeout(timeout time.Duration) *V1MessagesReadParams { + return &V1MessagesReadParams{ + timeout: timeout, + } +} + +// NewV1MessagesReadParamsWithContext creates a new V1MessagesReadParams object +// with the ability to set a context for a request. +func NewV1MessagesReadParamsWithContext(ctx context.Context) *V1MessagesReadParams { + return &V1MessagesReadParams{ + Context: ctx, + } +} + +// NewV1MessagesReadParamsWithHTTPClient creates a new V1MessagesReadParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1MessagesReadParamsWithHTTPClient(client *http.Client) *V1MessagesReadParams { + return &V1MessagesReadParams{ + HTTPClient: client, + } +} + +/* +V1MessagesReadParams contains all the parameters to send to the API endpoint + + for the v1 messages read operation. + + Typically these are written to a http.Request. +*/ +type V1MessagesReadParams struct { + + /* MessageHash. + + A unique value identifying this safe message. + + Format: binary + */ + MessageHash io.Reader + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 messages read params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1MessagesReadParams) WithDefaults() *V1MessagesReadParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 messages read params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1MessagesReadParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 messages read params +func (o *V1MessagesReadParams) WithTimeout(timeout time.Duration) *V1MessagesReadParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 messages read params +func (o *V1MessagesReadParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 messages read params +func (o *V1MessagesReadParams) WithContext(ctx context.Context) *V1MessagesReadParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 messages read params +func (o *V1MessagesReadParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 messages read params +func (o *V1MessagesReadParams) WithHTTPClient(client *http.Client) *V1MessagesReadParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 messages read params +func (o *V1MessagesReadParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithMessageHash adds the messageHash to the v1 messages read params +func (o *V1MessagesReadParams) WithMessageHash(messageHash io.ReadCloser) *V1MessagesReadParams { + o.SetMessageHash(messageHash) + return o +} + +// SetMessageHash adds the messageHash to the v1 messages read params +func (o *V1MessagesReadParams) SetMessageHash(messageHash io.ReadCloser) { + o.MessageHash = messageHash +} + +// WriteToRequest writes these params to a swagger request +func (o *V1MessagesReadParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param message_hash + var p []byte + o.MessageHash.Read(p) + if err := r.SetPathParam("message_hash", string(p)); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/messages/v1_messages_read_responses.go b/utils/safe_api/client/messages/v1_messages_read_responses.go new file mode 100644 index 0000000..0a7adf8 --- /dev/null +++ b/utils/safe_api/client/messages/v1_messages_read_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package messages + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1MessagesReadReader is a Reader for the V1MessagesRead structure. +type V1MessagesReadReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1MessagesReadReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1MessagesReadOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[GET /v1/messages/{message_hash}/] v1_messages_read", response, response.Code()) + } +} + +// NewV1MessagesReadOK creates a V1MessagesReadOK with default headers values +func NewV1MessagesReadOK() *V1MessagesReadOK { + return &V1MessagesReadOK{} +} + +/* +V1MessagesReadOK describes a response with status code 200, with default header values. + +V1MessagesReadOK v1 messages read o k +*/ +type V1MessagesReadOK struct { + Payload *models.SafeMessageResponse +} + +// IsSuccess returns true when this v1 messages read o k response has a 2xx status code +func (o *V1MessagesReadOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 messages read o k response has a 3xx status code +func (o *V1MessagesReadOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 messages read o k response has a 4xx status code +func (o *V1MessagesReadOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 messages read o k response has a 5xx status code +func (o *V1MessagesReadOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 messages read o k response a status code equal to that given +func (o *V1MessagesReadOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 messages read o k response +func (o *V1MessagesReadOK) Code() int { + return 200 +} + +func (o *V1MessagesReadOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/messages/{message_hash}/][%d] v1MessagesReadOK %s", 200, payload) +} + +func (o *V1MessagesReadOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/messages/{message_hash}/][%d] v1MessagesReadOK %s", 200, payload) +} + +func (o *V1MessagesReadOK) GetPayload() *models.SafeMessageResponse { + return o.Payload +} + +func (o *V1MessagesReadOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.SafeMessageResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/utils/safe_api/client/messages/v1_messages_signatures_create_parameters.go b/utils/safe_api/client/messages/v1_messages_signatures_create_parameters.go new file mode 100644 index 0000000..e6ffda2 --- /dev/null +++ b/utils/safe_api/client/messages/v1_messages_signatures_create_parameters.go @@ -0,0 +1,169 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package messages + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// NewV1MessagesSignaturesCreateParams creates a new V1MessagesSignaturesCreateParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1MessagesSignaturesCreateParams() *V1MessagesSignaturesCreateParams { + return &V1MessagesSignaturesCreateParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1MessagesSignaturesCreateParamsWithTimeout creates a new V1MessagesSignaturesCreateParams object +// with the ability to set a timeout on a request. +func NewV1MessagesSignaturesCreateParamsWithTimeout(timeout time.Duration) *V1MessagesSignaturesCreateParams { + return &V1MessagesSignaturesCreateParams{ + timeout: timeout, + } +} + +// NewV1MessagesSignaturesCreateParamsWithContext creates a new V1MessagesSignaturesCreateParams object +// with the ability to set a context for a request. +func NewV1MessagesSignaturesCreateParamsWithContext(ctx context.Context) *V1MessagesSignaturesCreateParams { + return &V1MessagesSignaturesCreateParams{ + Context: ctx, + } +} + +// NewV1MessagesSignaturesCreateParamsWithHTTPClient creates a new V1MessagesSignaturesCreateParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1MessagesSignaturesCreateParamsWithHTTPClient(client *http.Client) *V1MessagesSignaturesCreateParams { + return &V1MessagesSignaturesCreateParams{ + HTTPClient: client, + } +} + +/* +V1MessagesSignaturesCreateParams contains all the parameters to send to the API endpoint + + for the v1 messages signatures create operation. + + Typically these are written to a http.Request. +*/ +type V1MessagesSignaturesCreateParams struct { + + // Data. + Data *models.SafeMessageSignature + + // MessageHash. + MessageHash string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 messages signatures create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1MessagesSignaturesCreateParams) WithDefaults() *V1MessagesSignaturesCreateParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 messages signatures create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1MessagesSignaturesCreateParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 messages signatures create params +func (o *V1MessagesSignaturesCreateParams) WithTimeout(timeout time.Duration) *V1MessagesSignaturesCreateParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 messages signatures create params +func (o *V1MessagesSignaturesCreateParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 messages signatures create params +func (o *V1MessagesSignaturesCreateParams) WithContext(ctx context.Context) *V1MessagesSignaturesCreateParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 messages signatures create params +func (o *V1MessagesSignaturesCreateParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 messages signatures create params +func (o *V1MessagesSignaturesCreateParams) WithHTTPClient(client *http.Client) *V1MessagesSignaturesCreateParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 messages signatures create params +func (o *V1MessagesSignaturesCreateParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the v1 messages signatures create params +func (o *V1MessagesSignaturesCreateParams) WithData(data *models.SafeMessageSignature) *V1MessagesSignaturesCreateParams { + o.SetData(data) + return o +} + +// SetData adds the data to the v1 messages signatures create params +func (o *V1MessagesSignaturesCreateParams) SetData(data *models.SafeMessageSignature) { + o.Data = data +} + +// WithMessageHash adds the messageHash to the v1 messages signatures create params +func (o *V1MessagesSignaturesCreateParams) WithMessageHash(messageHash string) *V1MessagesSignaturesCreateParams { + o.SetMessageHash(messageHash) + return o +} + +// SetMessageHash adds the messageHash to the v1 messages signatures create params +func (o *V1MessagesSignaturesCreateParams) SetMessageHash(messageHash string) { + o.MessageHash = messageHash +} + +// WriteToRequest writes these params to a swagger request +func (o *V1MessagesSignaturesCreateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + // path param message_hash + if err := r.SetPathParam("message_hash", o.MessageHash); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/messages/v1_messages_signatures_create_responses.go b/utils/safe_api/client/messages/v1_messages_signatures_create_responses.go new file mode 100644 index 0000000..8a477b6 --- /dev/null +++ b/utils/safe_api/client/messages/v1_messages_signatures_create_responses.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package messages + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// V1MessagesSignaturesCreateReader is a Reader for the V1MessagesSignaturesCreate structure. +type V1MessagesSignaturesCreateReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1MessagesSignaturesCreateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 201: + result := NewV1MessagesSignaturesCreateCreated() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[POST /v1/messages/{message_hash}/signatures/] v1_messages_signatures_create", response, response.Code()) + } +} + +// NewV1MessagesSignaturesCreateCreated creates a V1MessagesSignaturesCreateCreated with default headers values +func NewV1MessagesSignaturesCreateCreated() *V1MessagesSignaturesCreateCreated { + return &V1MessagesSignaturesCreateCreated{} +} + +/* +V1MessagesSignaturesCreateCreated describes a response with status code 201, with default header values. + +Created +*/ +type V1MessagesSignaturesCreateCreated struct { +} + +// IsSuccess returns true when this v1 messages signatures create created response has a 2xx status code +func (o *V1MessagesSignaturesCreateCreated) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 messages signatures create created response has a 3xx status code +func (o *V1MessagesSignaturesCreateCreated) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 messages signatures create created response has a 4xx status code +func (o *V1MessagesSignaturesCreateCreated) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 messages signatures create created response has a 5xx status code +func (o *V1MessagesSignaturesCreateCreated) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 messages signatures create created response a status code equal to that given +func (o *V1MessagesSignaturesCreateCreated) IsCode(code int) bool { + return code == 201 +} + +// Code gets the status code for the v1 messages signatures create created response +func (o *V1MessagesSignaturesCreateCreated) Code() int { + return 201 +} + +func (o *V1MessagesSignaturesCreateCreated) Error() string { + return fmt.Sprintf("[POST /v1/messages/{message_hash}/signatures/][%d] v1MessagesSignaturesCreateCreated", 201) +} + +func (o *V1MessagesSignaturesCreateCreated) String() string { + return fmt.Sprintf("[POST /v1/messages/{message_hash}/signatures/][%d] v1MessagesSignaturesCreateCreated", 201) +} + +func (o *V1MessagesSignaturesCreateCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/messages/v1_safes_messages_create_parameters.go b/utils/safe_api/client/messages/v1_safes_messages_create_parameters.go new file mode 100644 index 0000000..270b499 --- /dev/null +++ b/utils/safe_api/client/messages/v1_safes_messages_create_parameters.go @@ -0,0 +1,169 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package messages + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// NewV1SafesMessagesCreateParams creates a new V1SafesMessagesCreateParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SafesMessagesCreateParams() *V1SafesMessagesCreateParams { + return &V1SafesMessagesCreateParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SafesMessagesCreateParamsWithTimeout creates a new V1SafesMessagesCreateParams object +// with the ability to set a timeout on a request. +func NewV1SafesMessagesCreateParamsWithTimeout(timeout time.Duration) *V1SafesMessagesCreateParams { + return &V1SafesMessagesCreateParams{ + timeout: timeout, + } +} + +// NewV1SafesMessagesCreateParamsWithContext creates a new V1SafesMessagesCreateParams object +// with the ability to set a context for a request. +func NewV1SafesMessagesCreateParamsWithContext(ctx context.Context) *V1SafesMessagesCreateParams { + return &V1SafesMessagesCreateParams{ + Context: ctx, + } +} + +// NewV1SafesMessagesCreateParamsWithHTTPClient creates a new V1SafesMessagesCreateParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SafesMessagesCreateParamsWithHTTPClient(client *http.Client) *V1SafesMessagesCreateParams { + return &V1SafesMessagesCreateParams{ + HTTPClient: client, + } +} + +/* +V1SafesMessagesCreateParams contains all the parameters to send to the API endpoint + + for the v1 safes messages create operation. + + Typically these are written to a http.Request. +*/ +type V1SafesMessagesCreateParams struct { + + // Address. + Address string + + // Data. + Data *models.SafeMessage + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 safes messages create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesMessagesCreateParams) WithDefaults() *V1SafesMessagesCreateParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 safes messages create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesMessagesCreateParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 safes messages create params +func (o *V1SafesMessagesCreateParams) WithTimeout(timeout time.Duration) *V1SafesMessagesCreateParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 safes messages create params +func (o *V1SafesMessagesCreateParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 safes messages create params +func (o *V1SafesMessagesCreateParams) WithContext(ctx context.Context) *V1SafesMessagesCreateParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 safes messages create params +func (o *V1SafesMessagesCreateParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 safes messages create params +func (o *V1SafesMessagesCreateParams) WithHTTPClient(client *http.Client) *V1SafesMessagesCreateParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 safes messages create params +func (o *V1SafesMessagesCreateParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 safes messages create params +func (o *V1SafesMessagesCreateParams) WithAddress(address string) *V1SafesMessagesCreateParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 safes messages create params +func (o *V1SafesMessagesCreateParams) SetAddress(address string) { + o.Address = address +} + +// WithData adds the data to the v1 safes messages create params +func (o *V1SafesMessagesCreateParams) WithData(data *models.SafeMessage) *V1SafesMessagesCreateParams { + o.SetData(data) + return o +} + +// SetData adds the data to the v1 safes messages create params +func (o *V1SafesMessagesCreateParams) SetData(data *models.SafeMessage) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SafesMessagesCreateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/messages/v1_safes_messages_create_responses.go b/utils/safe_api/client/messages/v1_safes_messages_create_responses.go new file mode 100644 index 0000000..e435c71 --- /dev/null +++ b/utils/safe_api/client/messages/v1_safes_messages_create_responses.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package messages + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// V1SafesMessagesCreateReader is a Reader for the V1SafesMessagesCreate structure. +type V1SafesMessagesCreateReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SafesMessagesCreateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 201: + result := NewV1SafesMessagesCreateCreated() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[POST /v1/safes/{address}/messages/] v1_safes_messages_create", response, response.Code()) + } +} + +// NewV1SafesMessagesCreateCreated creates a V1SafesMessagesCreateCreated with default headers values +func NewV1SafesMessagesCreateCreated() *V1SafesMessagesCreateCreated { + return &V1SafesMessagesCreateCreated{} +} + +/* +V1SafesMessagesCreateCreated describes a response with status code 201, with default header values. + +Created +*/ +type V1SafesMessagesCreateCreated struct { +} + +// IsSuccess returns true when this v1 safes messages create created response has a 2xx status code +func (o *V1SafesMessagesCreateCreated) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 safes messages create created response has a 3xx status code +func (o *V1SafesMessagesCreateCreated) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes messages create created response has a 4xx status code +func (o *V1SafesMessagesCreateCreated) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 safes messages create created response has a 5xx status code +func (o *V1SafesMessagesCreateCreated) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes messages create created response a status code equal to that given +func (o *V1SafesMessagesCreateCreated) IsCode(code int) bool { + return code == 201 +} + +// Code gets the status code for the v1 safes messages create created response +func (o *V1SafesMessagesCreateCreated) Code() int { + return 201 +} + +func (o *V1SafesMessagesCreateCreated) Error() string { + return fmt.Sprintf("[POST /v1/safes/{address}/messages/][%d] v1SafesMessagesCreateCreated", 201) +} + +func (o *V1SafesMessagesCreateCreated) String() string { + return fmt.Sprintf("[POST /v1/safes/{address}/messages/][%d] v1SafesMessagesCreateCreated", 201) +} + +func (o *V1SafesMessagesCreateCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/messages/v1_safes_messages_list_parameters.go b/utils/safe_api/client/messages/v1_safes_messages_list_parameters.go new file mode 100644 index 0000000..511d227 --- /dev/null +++ b/utils/safe_api/client/messages/v1_safes_messages_list_parameters.go @@ -0,0 +1,251 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package messages + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewV1SafesMessagesListParams creates a new V1SafesMessagesListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SafesMessagesListParams() *V1SafesMessagesListParams { + return &V1SafesMessagesListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SafesMessagesListParamsWithTimeout creates a new V1SafesMessagesListParams object +// with the ability to set a timeout on a request. +func NewV1SafesMessagesListParamsWithTimeout(timeout time.Duration) *V1SafesMessagesListParams { + return &V1SafesMessagesListParams{ + timeout: timeout, + } +} + +// NewV1SafesMessagesListParamsWithContext creates a new V1SafesMessagesListParams object +// with the ability to set a context for a request. +func NewV1SafesMessagesListParamsWithContext(ctx context.Context) *V1SafesMessagesListParams { + return &V1SafesMessagesListParams{ + Context: ctx, + } +} + +// NewV1SafesMessagesListParamsWithHTTPClient creates a new V1SafesMessagesListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SafesMessagesListParamsWithHTTPClient(client *http.Client) *V1SafesMessagesListParams { + return &V1SafesMessagesListParams{ + HTTPClient: client, + } +} + +/* +V1SafesMessagesListParams contains all the parameters to send to the API endpoint + + for the v1 safes messages list operation. + + Typically these are written to a http.Request. +*/ +type V1SafesMessagesListParams struct { + + // Address. + Address string + + /* Limit. + + Number of results to return per page. + */ + Limit *int64 + + /* Offset. + + The initial index from which to return the results. + */ + Offset *int64 + + /* Ordering. + + Which field to use when ordering the results. + */ + Ordering *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 safes messages list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesMessagesListParams) WithDefaults() *V1SafesMessagesListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 safes messages list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesMessagesListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 safes messages list params +func (o *V1SafesMessagesListParams) WithTimeout(timeout time.Duration) *V1SafesMessagesListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 safes messages list params +func (o *V1SafesMessagesListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 safes messages list params +func (o *V1SafesMessagesListParams) WithContext(ctx context.Context) *V1SafesMessagesListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 safes messages list params +func (o *V1SafesMessagesListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 safes messages list params +func (o *V1SafesMessagesListParams) WithHTTPClient(client *http.Client) *V1SafesMessagesListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 safes messages list params +func (o *V1SafesMessagesListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 safes messages list params +func (o *V1SafesMessagesListParams) WithAddress(address string) *V1SafesMessagesListParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 safes messages list params +func (o *V1SafesMessagesListParams) SetAddress(address string) { + o.Address = address +} + +// WithLimit adds the limit to the v1 safes messages list params +func (o *V1SafesMessagesListParams) WithLimit(limit *int64) *V1SafesMessagesListParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the v1 safes messages list params +func (o *V1SafesMessagesListParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the v1 safes messages list params +func (o *V1SafesMessagesListParams) WithOffset(offset *int64) *V1SafesMessagesListParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the v1 safes messages list params +func (o *V1SafesMessagesListParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithOrdering adds the ordering to the v1 safes messages list params +func (o *V1SafesMessagesListParams) WithOrdering(ordering *string) *V1SafesMessagesListParams { + o.SetOrdering(ordering) + return o +} + +// SetOrdering adds the ordering to the v1 safes messages list params +func (o *V1SafesMessagesListParams) SetOrdering(ordering *string) { + o.Ordering = ordering +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SafesMessagesListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Ordering != nil { + + // query param ordering + var qrOrdering string + + if o.Ordering != nil { + qrOrdering = *o.Ordering + } + qOrdering := qrOrdering + if qOrdering != "" { + + if err := r.SetQueryParam("ordering", qOrdering); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/messages/v1_safes_messages_list_responses.go b/utils/safe_api/client/messages/v1_safes_messages_list_responses.go new file mode 100644 index 0000000..691f908 --- /dev/null +++ b/utils/safe_api/client/messages/v1_safes_messages_list_responses.go @@ -0,0 +1,277 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package messages + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + models "omni-balance/utils/safe_api" +) + +// V1SafesMessagesListReader is a Reader for the V1SafesMessagesList structure. +type V1SafesMessagesListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SafesMessagesListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1SafesMessagesListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[GET /v1/safes/{address}/messages/] v1_safes_messages_list", response, response.Code()) + } +} + +// NewV1SafesMessagesListOK creates a V1SafesMessagesListOK with default headers values +func NewV1SafesMessagesListOK() *V1SafesMessagesListOK { + return &V1SafesMessagesListOK{} +} + +/* +V1SafesMessagesListOK describes a response with status code 200, with default header values. + +V1SafesMessagesListOK v1 safes messages list o k +*/ +type V1SafesMessagesListOK struct { + Payload *V1SafesMessagesListOKBody +} + +// IsSuccess returns true when this v1 safes messages list o k response has a 2xx status code +func (o *V1SafesMessagesListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 safes messages list o k response has a 3xx status code +func (o *V1SafesMessagesListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes messages list o k response has a 4xx status code +func (o *V1SafesMessagesListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 safes messages list o k response has a 5xx status code +func (o *V1SafesMessagesListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes messages list o k response a status code equal to that given +func (o *V1SafesMessagesListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 safes messages list o k response +func (o *V1SafesMessagesListOK) Code() int { + return 200 +} + +func (o *V1SafesMessagesListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/messages/][%d] v1SafesMessagesListOK %s", 200, payload) +} + +func (o *V1SafesMessagesListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/messages/][%d] v1SafesMessagesListOK %s", 200, payload) +} + +func (o *V1SafesMessagesListOK) GetPayload() *V1SafesMessagesListOKBody { + return o.Payload +} + +func (o *V1SafesMessagesListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(V1SafesMessagesListOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +V1SafesMessagesListOKBody v1 safes messages list o k body +swagger:model V1SafesMessagesListOKBody +*/ +type V1SafesMessagesListOKBody struct { + + // count + // Required: true + Count *int64 `json:"count"` + + // next + // Format: uri + Next *strfmt.URI `json:"next,omitempty"` + + // previous + // Format: uri + Previous *strfmt.URI `json:"previous,omitempty"` + + // results + // Required: true + Results []*models.SafeMessageResponse `json:"results"` +} + +// Validate validates this v1 safes messages list o k body +func (o *V1SafesMessagesListOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateCount(formats); err != nil { + res = append(res, err) + } + + if err := o.validateNext(formats); err != nil { + res = append(res, err) + } + + if err := o.validatePrevious(formats); err != nil { + res = append(res, err) + } + + if err := o.validateResults(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V1SafesMessagesListOKBody) validateCount(formats strfmt.Registry) error { + + if err := validate.Required("v1SafesMessagesListOK"+"."+"count", "body", o.Count); err != nil { + return err + } + + return nil +} + +func (o *V1SafesMessagesListOKBody) validateNext(formats strfmt.Registry) error { + if swag.IsZero(o.Next) { // not required + return nil + } + + if err := validate.FormatOf("v1SafesMessagesListOK"+"."+"next", "body", "uri", o.Next.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V1SafesMessagesListOKBody) validatePrevious(formats strfmt.Registry) error { + if swag.IsZero(o.Previous) { // not required + return nil + } + + if err := validate.FormatOf("v1SafesMessagesListOK"+"."+"previous", "body", "uri", o.Previous.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V1SafesMessagesListOKBody) validateResults(formats strfmt.Registry) error { + + if err := validate.Required("v1SafesMessagesListOK"+"."+"results", "body", o.Results); err != nil { + return err + } + + for i := 0; i < len(o.Results); i++ { + if swag.IsZero(o.Results[i]) { // not required + continue + } + + if o.Results[i] != nil { + if err := o.Results[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v1SafesMessagesListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v1SafesMessagesListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this v1 safes messages list o k body based on the context it is used +func (o *V1SafesMessagesListOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResults(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V1SafesMessagesListOKBody) contextValidateResults(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Results); i++ { + + if o.Results[i] != nil { + + if swag.IsZero(o.Results[i]) { // not required + return nil + } + + if err := o.Results[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v1SafesMessagesListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v1SafesMessagesListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *V1SafesMessagesListOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *V1SafesMessagesListOKBody) UnmarshalBinary(b []byte) error { + var res V1SafesMessagesListOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/utils/safe_api/client/modules/modules_client.go b/utils/safe_api/client/modules/modules_client.go new file mode 100644 index 0000000..457d619 --- /dev/null +++ b/utils/safe_api/client/modules/modules_client.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package modules + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// New creates a new modules API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +// New creates a new modules API client with basic auth credentials. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - user: user for basic authentication header. +// - password: password for basic authentication header. +func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BasicAuth(user, password) + return &Client{transport: transport, formats: strfmt.Default} +} + +// New creates a new modules API client with a bearer token for authentication. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - bearerToken: bearer token for Bearer authentication header. +func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) + return &Client{transport: transport, formats: strfmt.Default} +} + +/* +Client for modules API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption may be used to customize the behavior of Client methods. +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + V1ModulesSafesList(params *V1ModulesSafesListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1ModulesSafesListOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +V1ModulesSafesList Return Safes where the module address provided is enabled +*/ +func (a *Client) V1ModulesSafesList(params *V1ModulesSafesListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1ModulesSafesListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1ModulesSafesListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_modules_safes_list", + Method: "GET", + PathPattern: "/v1/modules/{address}/safes/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1ModulesSafesListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1ModulesSafesListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_modules_safes_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/utils/safe_api/client/modules/v1_modules_safes_list_parameters.go b/utils/safe_api/client/modules/v1_modules_safes_list_parameters.go new file mode 100644 index 0000000..d134f55 --- /dev/null +++ b/utils/safe_api/client/modules/v1_modules_safes_list_parameters.go @@ -0,0 +1,148 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package modules + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1ModulesSafesListParams creates a new V1ModulesSafesListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1ModulesSafesListParams() *V1ModulesSafesListParams { + return &V1ModulesSafesListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1ModulesSafesListParamsWithTimeout creates a new V1ModulesSafesListParams object +// with the ability to set a timeout on a request. +func NewV1ModulesSafesListParamsWithTimeout(timeout time.Duration) *V1ModulesSafesListParams { + return &V1ModulesSafesListParams{ + timeout: timeout, + } +} + +// NewV1ModulesSafesListParamsWithContext creates a new V1ModulesSafesListParams object +// with the ability to set a context for a request. +func NewV1ModulesSafesListParamsWithContext(ctx context.Context) *V1ModulesSafesListParams { + return &V1ModulesSafesListParams{ + Context: ctx, + } +} + +// NewV1ModulesSafesListParamsWithHTTPClient creates a new V1ModulesSafesListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1ModulesSafesListParamsWithHTTPClient(client *http.Client) *V1ModulesSafesListParams { + return &V1ModulesSafesListParams{ + HTTPClient: client, + } +} + +/* +V1ModulesSafesListParams contains all the parameters to send to the API endpoint + + for the v1 modules safes list operation. + + Typically these are written to a http.Request. +*/ +type V1ModulesSafesListParams struct { + + // Address. + Address string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 modules safes list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1ModulesSafesListParams) WithDefaults() *V1ModulesSafesListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 modules safes list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1ModulesSafesListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 modules safes list params +func (o *V1ModulesSafesListParams) WithTimeout(timeout time.Duration) *V1ModulesSafesListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 modules safes list params +func (o *V1ModulesSafesListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 modules safes list params +func (o *V1ModulesSafesListParams) WithContext(ctx context.Context) *V1ModulesSafesListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 modules safes list params +func (o *V1ModulesSafesListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 modules safes list params +func (o *V1ModulesSafesListParams) WithHTTPClient(client *http.Client) *V1ModulesSafesListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 modules safes list params +func (o *V1ModulesSafesListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 modules safes list params +func (o *V1ModulesSafesListParams) WithAddress(address string) *V1ModulesSafesListParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 modules safes list params +func (o *V1ModulesSafesListParams) SetAddress(address string) { + o.Address = address +} + +// WriteToRequest writes these params to a swagger request +func (o *V1ModulesSafesListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/modules/v1_modules_safes_list_responses.go b/utils/safe_api/client/modules/v1_modules_safes_list_responses.go new file mode 100644 index 0000000..1283c34 --- /dev/null +++ b/utils/safe_api/client/modules/v1_modules_safes_list_responses.go @@ -0,0 +1,168 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package modules + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1ModulesSafesListReader is a Reader for the V1ModulesSafesList structure. +type V1ModulesSafesListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1ModulesSafesListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1ModulesSafesListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 422: + result := NewV1ModulesSafesListUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/modules/{address}/safes/] v1_modules_safes_list", response, response.Code()) + } +} + +// NewV1ModulesSafesListOK creates a V1ModulesSafesListOK with default headers values +func NewV1ModulesSafesListOK() *V1ModulesSafesListOK { + return &V1ModulesSafesListOK{} +} + +/* +V1ModulesSafesListOK describes a response with status code 200, with default header values. + +V1ModulesSafesListOK v1 modules safes list o k +*/ +type V1ModulesSafesListOK struct { + Payload *models.ModulesResponse +} + +// IsSuccess returns true when this v1 modules safes list o k response has a 2xx status code +func (o *V1ModulesSafesListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 modules safes list o k response has a 3xx status code +func (o *V1ModulesSafesListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 modules safes list o k response has a 4xx status code +func (o *V1ModulesSafesListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 modules safes list o k response has a 5xx status code +func (o *V1ModulesSafesListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 modules safes list o k response a status code equal to that given +func (o *V1ModulesSafesListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 modules safes list o k response +func (o *V1ModulesSafesListOK) Code() int { + return 200 +} + +func (o *V1ModulesSafesListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/modules/{address}/safes/][%d] v1ModulesSafesListOK %s", 200, payload) +} + +func (o *V1ModulesSafesListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/modules/{address}/safes/][%d] v1ModulesSafesListOK %s", 200, payload) +} + +func (o *V1ModulesSafesListOK) GetPayload() *models.ModulesResponse { + return o.Payload +} + +func (o *V1ModulesSafesListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ModulesResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1ModulesSafesListUnprocessableEntity creates a V1ModulesSafesListUnprocessableEntity with default headers values +func NewV1ModulesSafesListUnprocessableEntity() *V1ModulesSafesListUnprocessableEntity { + return &V1ModulesSafesListUnprocessableEntity{} +} + +/* +V1ModulesSafesListUnprocessableEntity describes a response with status code 422, with default header values. + +Module address checksum not valid +*/ +type V1ModulesSafesListUnprocessableEntity struct { +} + +// IsSuccess returns true when this v1 modules safes list unprocessable entity response has a 2xx status code +func (o *V1ModulesSafesListUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 modules safes list unprocessable entity response has a 3xx status code +func (o *V1ModulesSafesListUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 modules safes list unprocessable entity response has a 4xx status code +func (o *V1ModulesSafesListUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 modules safes list unprocessable entity response has a 5xx status code +func (o *V1ModulesSafesListUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 modules safes list unprocessable entity response a status code equal to that given +func (o *V1ModulesSafesListUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 modules safes list unprocessable entity response +func (o *V1ModulesSafesListUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1ModulesSafesListUnprocessableEntity) Error() string { + return fmt.Sprintf("[GET /v1/modules/{address}/safes/][%d] v1ModulesSafesListUnprocessableEntity", 422) +} + +func (o *V1ModulesSafesListUnprocessableEntity) String() string { + return fmt.Sprintf("[GET /v1/modules/{address}/safes/][%d] v1ModulesSafesListUnprocessableEntity", 422) +} + +func (o *V1ModulesSafesListUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/notifications/notifications_client.go b/utils/safe_api/client/notifications/notifications_client.go new file mode 100644 index 0000000..f8fb2e8 --- /dev/null +++ b/utils/safe_api/client/notifications/notifications_client.go @@ -0,0 +1,194 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package notifications + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// New creates a new notifications API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +// New creates a new notifications API client with basic auth credentials. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - user: user for basic authentication header. +// - password: password for basic authentication header. +func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BasicAuth(user, password) + return &Client{transport: transport, formats: strfmt.Default} +} + +// New creates a new notifications API client with a bearer token for authentication. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - bearerToken: bearer token for Bearer authentication header. +func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) + return &Client{transport: transport, formats: strfmt.Default} +} + +/* +Client for notifications API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption may be used to customize the behavior of Client methods. +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + V1NotificationsDevicesCreate(params *V1NotificationsDevicesCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1NotificationsDevicesCreateOK, error) + + V1NotificationsDevicesDelete(params *V1NotificationsDevicesDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1NotificationsDevicesDeleteNoContent, error) + + V1NotificationsDevicesSafesDelete(params *V1NotificationsDevicesSafesDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1NotificationsDevicesSafesDeleteNoContent, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + V1NotificationsDevicesCreate Creates a new FirebaseDevice. If uuid is not provided a new device will be created. + +If a uuid for an existing Safe is provided the FirebaseDevice will be updated with all the new data provided. +Safes provided on the request are always added and never removed/replaced +Signature must sign `keccack256('gnosis-safe{timestamp-epoch}{uuid}{cloud_messaging_token}{safes_sorted}': + - `{timestamp-epoch}` must be an integer (no milliseconds) + - `{safes_sorted}` must be checksummed safe addresses sorted and joined with no spaces +*/ +func (a *Client) V1NotificationsDevicesCreate(params *V1NotificationsDevicesCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1NotificationsDevicesCreateOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1NotificationsDevicesCreateParams() + } + op := &runtime.ClientOperation{ + ID: "v1_notifications_devices_create", + Method: "POST", + PathPattern: "/v1/notifications/devices/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1NotificationsDevicesCreateReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1NotificationsDevicesCreateOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_notifications_devices_create: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1NotificationsDevicesDelete Remove a FirebaseDevice +*/ +func (a *Client) V1NotificationsDevicesDelete(params *V1NotificationsDevicesDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1NotificationsDevicesDeleteNoContent, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1NotificationsDevicesDeleteParams() + } + op := &runtime.ClientOperation{ + ID: "v1_notifications_devices_delete", + Method: "DELETE", + PathPattern: "/v1/notifications/devices/{uuid}/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1NotificationsDevicesDeleteReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1NotificationsDevicesDeleteNoContent) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_notifications_devices_delete: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1NotificationsDevicesSafesDelete Remove a Safe for a FirebaseDevice +*/ +func (a *Client) V1NotificationsDevicesSafesDelete(params *V1NotificationsDevicesSafesDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1NotificationsDevicesSafesDeleteNoContent, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1NotificationsDevicesSafesDeleteParams() + } + op := &runtime.ClientOperation{ + ID: "v1_notifications_devices_safes_delete", + Method: "DELETE", + PathPattern: "/v1/notifications/devices/{uuid}/safes/{address}/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1NotificationsDevicesSafesDeleteReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1NotificationsDevicesSafesDeleteNoContent) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_notifications_devices_safes_delete: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/utils/safe_api/client/notifications/v1_notifications_devices_create_parameters.go b/utils/safe_api/client/notifications/v1_notifications_devices_create_parameters.go new file mode 100644 index 0000000..2e2cf7a --- /dev/null +++ b/utils/safe_api/client/notifications/v1_notifications_devices_create_parameters.go @@ -0,0 +1,150 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package notifications + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// NewV1NotificationsDevicesCreateParams creates a new V1NotificationsDevicesCreateParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1NotificationsDevicesCreateParams() *V1NotificationsDevicesCreateParams { + return &V1NotificationsDevicesCreateParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1NotificationsDevicesCreateParamsWithTimeout creates a new V1NotificationsDevicesCreateParams object +// with the ability to set a timeout on a request. +func NewV1NotificationsDevicesCreateParamsWithTimeout(timeout time.Duration) *V1NotificationsDevicesCreateParams { + return &V1NotificationsDevicesCreateParams{ + timeout: timeout, + } +} + +// NewV1NotificationsDevicesCreateParamsWithContext creates a new V1NotificationsDevicesCreateParams object +// with the ability to set a context for a request. +func NewV1NotificationsDevicesCreateParamsWithContext(ctx context.Context) *V1NotificationsDevicesCreateParams { + return &V1NotificationsDevicesCreateParams{ + Context: ctx, + } +} + +// NewV1NotificationsDevicesCreateParamsWithHTTPClient creates a new V1NotificationsDevicesCreateParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1NotificationsDevicesCreateParamsWithHTTPClient(client *http.Client) *V1NotificationsDevicesCreateParams { + return &V1NotificationsDevicesCreateParams{ + HTTPClient: client, + } +} + +/* +V1NotificationsDevicesCreateParams contains all the parameters to send to the API endpoint + + for the v1 notifications devices create operation. + + Typically these are written to a http.Request. +*/ +type V1NotificationsDevicesCreateParams struct { + + // Data. + Data *models.FirebaseDevice + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 notifications devices create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1NotificationsDevicesCreateParams) WithDefaults() *V1NotificationsDevicesCreateParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 notifications devices create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1NotificationsDevicesCreateParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 notifications devices create params +func (o *V1NotificationsDevicesCreateParams) WithTimeout(timeout time.Duration) *V1NotificationsDevicesCreateParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 notifications devices create params +func (o *V1NotificationsDevicesCreateParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 notifications devices create params +func (o *V1NotificationsDevicesCreateParams) WithContext(ctx context.Context) *V1NotificationsDevicesCreateParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 notifications devices create params +func (o *V1NotificationsDevicesCreateParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 notifications devices create params +func (o *V1NotificationsDevicesCreateParams) WithHTTPClient(client *http.Client) *V1NotificationsDevicesCreateParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 notifications devices create params +func (o *V1NotificationsDevicesCreateParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the v1 notifications devices create params +func (o *V1NotificationsDevicesCreateParams) WithData(data *models.FirebaseDevice) *V1NotificationsDevicesCreateParams { + o.SetData(data) + return o +} + +// SetData adds the data to the v1 notifications devices create params +func (o *V1NotificationsDevicesCreateParams) SetData(data *models.FirebaseDevice) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *V1NotificationsDevicesCreateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/notifications/v1_notifications_devices_create_responses.go b/utils/safe_api/client/notifications/v1_notifications_devices_create_responses.go new file mode 100644 index 0000000..fc9d699 --- /dev/null +++ b/utils/safe_api/client/notifications/v1_notifications_devices_create_responses.go @@ -0,0 +1,168 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package notifications + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1NotificationsDevicesCreateReader is a Reader for the V1NotificationsDevicesCreate structure. +type V1NotificationsDevicesCreateReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1NotificationsDevicesCreateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1NotificationsDevicesCreateOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1NotificationsDevicesCreateBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /v1/notifications/devices/] v1_notifications_devices_create", response, response.Code()) + } +} + +// NewV1NotificationsDevicesCreateOK creates a V1NotificationsDevicesCreateOK with default headers values +func NewV1NotificationsDevicesCreateOK() *V1NotificationsDevicesCreateOK { + return &V1NotificationsDevicesCreateOK{} +} + +/* +V1NotificationsDevicesCreateOK describes a response with status code 200, with default header values. + +V1NotificationsDevicesCreateOK v1 notifications devices create o k +*/ +type V1NotificationsDevicesCreateOK struct { + Payload *models.FirebaseDeviceSerializerWithOwnersResponse +} + +// IsSuccess returns true when this v1 notifications devices create o k response has a 2xx status code +func (o *V1NotificationsDevicesCreateOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 notifications devices create o k response has a 3xx status code +func (o *V1NotificationsDevicesCreateOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 notifications devices create o k response has a 4xx status code +func (o *V1NotificationsDevicesCreateOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 notifications devices create o k response has a 5xx status code +func (o *V1NotificationsDevicesCreateOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 notifications devices create o k response a status code equal to that given +func (o *V1NotificationsDevicesCreateOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 notifications devices create o k response +func (o *V1NotificationsDevicesCreateOK) Code() int { + return 200 +} + +func (o *V1NotificationsDevicesCreateOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/notifications/devices/][%d] v1NotificationsDevicesCreateOK %s", 200, payload) +} + +func (o *V1NotificationsDevicesCreateOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/notifications/devices/][%d] v1NotificationsDevicesCreateOK %s", 200, payload) +} + +func (o *V1NotificationsDevicesCreateOK) GetPayload() *models.FirebaseDeviceSerializerWithOwnersResponse { + return o.Payload +} + +func (o *V1NotificationsDevicesCreateOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.FirebaseDeviceSerializerWithOwnersResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1NotificationsDevicesCreateBadRequest creates a V1NotificationsDevicesCreateBadRequest with default headers values +func NewV1NotificationsDevicesCreateBadRequest() *V1NotificationsDevicesCreateBadRequest { + return &V1NotificationsDevicesCreateBadRequest{} +} + +/* +V1NotificationsDevicesCreateBadRequest describes a response with status code 400, with default header values. + +Invalid data +*/ +type V1NotificationsDevicesCreateBadRequest struct { +} + +// IsSuccess returns true when this v1 notifications devices create bad request response has a 2xx status code +func (o *V1NotificationsDevicesCreateBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 notifications devices create bad request response has a 3xx status code +func (o *V1NotificationsDevicesCreateBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 notifications devices create bad request response has a 4xx status code +func (o *V1NotificationsDevicesCreateBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 notifications devices create bad request response has a 5xx status code +func (o *V1NotificationsDevicesCreateBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 notifications devices create bad request response a status code equal to that given +func (o *V1NotificationsDevicesCreateBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 notifications devices create bad request response +func (o *V1NotificationsDevicesCreateBadRequest) Code() int { + return 400 +} + +func (o *V1NotificationsDevicesCreateBadRequest) Error() string { + return fmt.Sprintf("[POST /v1/notifications/devices/][%d] v1NotificationsDevicesCreateBadRequest", 400) +} + +func (o *V1NotificationsDevicesCreateBadRequest) String() string { + return fmt.Sprintf("[POST /v1/notifications/devices/][%d] v1NotificationsDevicesCreateBadRequest", 400) +} + +func (o *V1NotificationsDevicesCreateBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/notifications/v1_notifications_devices_delete_parameters.go b/utils/safe_api/client/notifications/v1_notifications_devices_delete_parameters.go new file mode 100644 index 0000000..d0258e0 --- /dev/null +++ b/utils/safe_api/client/notifications/v1_notifications_devices_delete_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package notifications + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1NotificationsDevicesDeleteParams creates a new V1NotificationsDevicesDeleteParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1NotificationsDevicesDeleteParams() *V1NotificationsDevicesDeleteParams { + return &V1NotificationsDevicesDeleteParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1NotificationsDevicesDeleteParamsWithTimeout creates a new V1NotificationsDevicesDeleteParams object +// with the ability to set a timeout on a request. +func NewV1NotificationsDevicesDeleteParamsWithTimeout(timeout time.Duration) *V1NotificationsDevicesDeleteParams { + return &V1NotificationsDevicesDeleteParams{ + timeout: timeout, + } +} + +// NewV1NotificationsDevicesDeleteParamsWithContext creates a new V1NotificationsDevicesDeleteParams object +// with the ability to set a context for a request. +func NewV1NotificationsDevicesDeleteParamsWithContext(ctx context.Context) *V1NotificationsDevicesDeleteParams { + return &V1NotificationsDevicesDeleteParams{ + Context: ctx, + } +} + +// NewV1NotificationsDevicesDeleteParamsWithHTTPClient creates a new V1NotificationsDevicesDeleteParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1NotificationsDevicesDeleteParamsWithHTTPClient(client *http.Client) *V1NotificationsDevicesDeleteParams { + return &V1NotificationsDevicesDeleteParams{ + HTTPClient: client, + } +} + +/* +V1NotificationsDevicesDeleteParams contains all the parameters to send to the API endpoint + + for the v1 notifications devices delete operation. + + Typically these are written to a http.Request. +*/ +type V1NotificationsDevicesDeleteParams struct { + + /* UUID. + + A UUID string identifying this Firebase Device. + + Format: uuid + */ + UUID strfmt.UUID + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 notifications devices delete params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1NotificationsDevicesDeleteParams) WithDefaults() *V1NotificationsDevicesDeleteParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 notifications devices delete params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1NotificationsDevicesDeleteParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 notifications devices delete params +func (o *V1NotificationsDevicesDeleteParams) WithTimeout(timeout time.Duration) *V1NotificationsDevicesDeleteParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 notifications devices delete params +func (o *V1NotificationsDevicesDeleteParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 notifications devices delete params +func (o *V1NotificationsDevicesDeleteParams) WithContext(ctx context.Context) *V1NotificationsDevicesDeleteParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 notifications devices delete params +func (o *V1NotificationsDevicesDeleteParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 notifications devices delete params +func (o *V1NotificationsDevicesDeleteParams) WithHTTPClient(client *http.Client) *V1NotificationsDevicesDeleteParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 notifications devices delete params +func (o *V1NotificationsDevicesDeleteParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithUUID adds the uuid to the v1 notifications devices delete params +func (o *V1NotificationsDevicesDeleteParams) WithUUID(uuid strfmt.UUID) *V1NotificationsDevicesDeleteParams { + o.SetUUID(uuid) + return o +} + +// SetUUID adds the uuid to the v1 notifications devices delete params +func (o *V1NotificationsDevicesDeleteParams) SetUUID(uuid strfmt.UUID) { + o.UUID = uuid +} + +// WriteToRequest writes these params to a swagger request +func (o *V1NotificationsDevicesDeleteParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param uuid + if err := r.SetPathParam("uuid", o.UUID.String()); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/notifications/v1_notifications_devices_delete_responses.go b/utils/safe_api/client/notifications/v1_notifications_devices_delete_responses.go new file mode 100644 index 0000000..d38dcf3 --- /dev/null +++ b/utils/safe_api/client/notifications/v1_notifications_devices_delete_responses.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package notifications + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// V1NotificationsDevicesDeleteReader is a Reader for the V1NotificationsDevicesDelete structure. +type V1NotificationsDevicesDeleteReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1NotificationsDevicesDeleteReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 204: + result := NewV1NotificationsDevicesDeleteNoContent() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[DELETE /v1/notifications/devices/{uuid}/] v1_notifications_devices_delete", response, response.Code()) + } +} + +// NewV1NotificationsDevicesDeleteNoContent creates a V1NotificationsDevicesDeleteNoContent with default headers values +func NewV1NotificationsDevicesDeleteNoContent() *V1NotificationsDevicesDeleteNoContent { + return &V1NotificationsDevicesDeleteNoContent{} +} + +/* +V1NotificationsDevicesDeleteNoContent describes a response with status code 204, with default header values. + +V1NotificationsDevicesDeleteNoContent v1 notifications devices delete no content +*/ +type V1NotificationsDevicesDeleteNoContent struct { +} + +// IsSuccess returns true when this v1 notifications devices delete no content response has a 2xx status code +func (o *V1NotificationsDevicesDeleteNoContent) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 notifications devices delete no content response has a 3xx status code +func (o *V1NotificationsDevicesDeleteNoContent) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 notifications devices delete no content response has a 4xx status code +func (o *V1NotificationsDevicesDeleteNoContent) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 notifications devices delete no content response has a 5xx status code +func (o *V1NotificationsDevicesDeleteNoContent) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 notifications devices delete no content response a status code equal to that given +func (o *V1NotificationsDevicesDeleteNoContent) IsCode(code int) bool { + return code == 204 +} + +// Code gets the status code for the v1 notifications devices delete no content response +func (o *V1NotificationsDevicesDeleteNoContent) Code() int { + return 204 +} + +func (o *V1NotificationsDevicesDeleteNoContent) Error() string { + return fmt.Sprintf("[DELETE /v1/notifications/devices/{uuid}/][%d] v1NotificationsDevicesDeleteNoContent", 204) +} + +func (o *V1NotificationsDevicesDeleteNoContent) String() string { + return fmt.Sprintf("[DELETE /v1/notifications/devices/{uuid}/][%d] v1NotificationsDevicesDeleteNoContent", 204) +} + +func (o *V1NotificationsDevicesDeleteNoContent) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/notifications/v1_notifications_devices_safes_delete_parameters.go b/utils/safe_api/client/notifications/v1_notifications_devices_safes_delete_parameters.go new file mode 100644 index 0000000..bca92ef --- /dev/null +++ b/utils/safe_api/client/notifications/v1_notifications_devices_safes_delete_parameters.go @@ -0,0 +1,172 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package notifications + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1NotificationsDevicesSafesDeleteParams creates a new V1NotificationsDevicesSafesDeleteParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1NotificationsDevicesSafesDeleteParams() *V1NotificationsDevicesSafesDeleteParams { + return &V1NotificationsDevicesSafesDeleteParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1NotificationsDevicesSafesDeleteParamsWithTimeout creates a new V1NotificationsDevicesSafesDeleteParams object +// with the ability to set a timeout on a request. +func NewV1NotificationsDevicesSafesDeleteParamsWithTimeout(timeout time.Duration) *V1NotificationsDevicesSafesDeleteParams { + return &V1NotificationsDevicesSafesDeleteParams{ + timeout: timeout, + } +} + +// NewV1NotificationsDevicesSafesDeleteParamsWithContext creates a new V1NotificationsDevicesSafesDeleteParams object +// with the ability to set a context for a request. +func NewV1NotificationsDevicesSafesDeleteParamsWithContext(ctx context.Context) *V1NotificationsDevicesSafesDeleteParams { + return &V1NotificationsDevicesSafesDeleteParams{ + Context: ctx, + } +} + +// NewV1NotificationsDevicesSafesDeleteParamsWithHTTPClient creates a new V1NotificationsDevicesSafesDeleteParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1NotificationsDevicesSafesDeleteParamsWithHTTPClient(client *http.Client) *V1NotificationsDevicesSafesDeleteParams { + return &V1NotificationsDevicesSafesDeleteParams{ + HTTPClient: client, + } +} + +/* +V1NotificationsDevicesSafesDeleteParams contains all the parameters to send to the API endpoint + + for the v1 notifications devices safes delete operation. + + Typically these are written to a http.Request. +*/ +type V1NotificationsDevicesSafesDeleteParams struct { + + // Address. + Address string + + /* UUID. + + A UUID string identifying this Firebase Device. + + Format: uuid + */ + UUID strfmt.UUID + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 notifications devices safes delete params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1NotificationsDevicesSafesDeleteParams) WithDefaults() *V1NotificationsDevicesSafesDeleteParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 notifications devices safes delete params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1NotificationsDevicesSafesDeleteParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 notifications devices safes delete params +func (o *V1NotificationsDevicesSafesDeleteParams) WithTimeout(timeout time.Duration) *V1NotificationsDevicesSafesDeleteParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 notifications devices safes delete params +func (o *V1NotificationsDevicesSafesDeleteParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 notifications devices safes delete params +func (o *V1NotificationsDevicesSafesDeleteParams) WithContext(ctx context.Context) *V1NotificationsDevicesSafesDeleteParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 notifications devices safes delete params +func (o *V1NotificationsDevicesSafesDeleteParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 notifications devices safes delete params +func (o *V1NotificationsDevicesSafesDeleteParams) WithHTTPClient(client *http.Client) *V1NotificationsDevicesSafesDeleteParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 notifications devices safes delete params +func (o *V1NotificationsDevicesSafesDeleteParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 notifications devices safes delete params +func (o *V1NotificationsDevicesSafesDeleteParams) WithAddress(address string) *V1NotificationsDevicesSafesDeleteParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 notifications devices safes delete params +func (o *V1NotificationsDevicesSafesDeleteParams) SetAddress(address string) { + o.Address = address +} + +// WithUUID adds the uuid to the v1 notifications devices safes delete params +func (o *V1NotificationsDevicesSafesDeleteParams) WithUUID(uuid strfmt.UUID) *V1NotificationsDevicesSafesDeleteParams { + o.SetUUID(uuid) + return o +} + +// SetUUID adds the uuid to the v1 notifications devices safes delete params +func (o *V1NotificationsDevicesSafesDeleteParams) SetUUID(uuid strfmt.UUID) { + o.UUID = uuid +} + +// WriteToRequest writes these params to a swagger request +func (o *V1NotificationsDevicesSafesDeleteParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + + // path param uuid + if err := r.SetPathParam("uuid", o.UUID.String()); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/notifications/v1_notifications_devices_safes_delete_responses.go b/utils/safe_api/client/notifications/v1_notifications_devices_safes_delete_responses.go new file mode 100644 index 0000000..8cc63fe --- /dev/null +++ b/utils/safe_api/client/notifications/v1_notifications_devices_safes_delete_responses.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package notifications + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// V1NotificationsDevicesSafesDeleteReader is a Reader for the V1NotificationsDevicesSafesDelete structure. +type V1NotificationsDevicesSafesDeleteReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1NotificationsDevicesSafesDeleteReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 204: + result := NewV1NotificationsDevicesSafesDeleteNoContent() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[DELETE /v1/notifications/devices/{uuid}/safes/{address}/] v1_notifications_devices_safes_delete", response, response.Code()) + } +} + +// NewV1NotificationsDevicesSafesDeleteNoContent creates a V1NotificationsDevicesSafesDeleteNoContent with default headers values +func NewV1NotificationsDevicesSafesDeleteNoContent() *V1NotificationsDevicesSafesDeleteNoContent { + return &V1NotificationsDevicesSafesDeleteNoContent{} +} + +/* +V1NotificationsDevicesSafesDeleteNoContent describes a response with status code 204, with default header values. + +V1NotificationsDevicesSafesDeleteNoContent v1 notifications devices safes delete no content +*/ +type V1NotificationsDevicesSafesDeleteNoContent struct { +} + +// IsSuccess returns true when this v1 notifications devices safes delete no content response has a 2xx status code +func (o *V1NotificationsDevicesSafesDeleteNoContent) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 notifications devices safes delete no content response has a 3xx status code +func (o *V1NotificationsDevicesSafesDeleteNoContent) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 notifications devices safes delete no content response has a 4xx status code +func (o *V1NotificationsDevicesSafesDeleteNoContent) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 notifications devices safes delete no content response has a 5xx status code +func (o *V1NotificationsDevicesSafesDeleteNoContent) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 notifications devices safes delete no content response a status code equal to that given +func (o *V1NotificationsDevicesSafesDeleteNoContent) IsCode(code int) bool { + return code == 204 +} + +// Code gets the status code for the v1 notifications devices safes delete no content response +func (o *V1NotificationsDevicesSafesDeleteNoContent) Code() int { + return 204 +} + +func (o *V1NotificationsDevicesSafesDeleteNoContent) Error() string { + return fmt.Sprintf("[DELETE /v1/notifications/devices/{uuid}/safes/{address}/][%d] v1NotificationsDevicesSafesDeleteNoContent", 204) +} + +func (o *V1NotificationsDevicesSafesDeleteNoContent) String() string { + return fmt.Sprintf("[DELETE /v1/notifications/devices/{uuid}/safes/{address}/][%d] v1NotificationsDevicesSafesDeleteNoContent", 204) +} + +func (o *V1NotificationsDevicesSafesDeleteNoContent) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/nr4337/nr4337_client.go b/utils/safe_api/client/nr4337/nr4337_client.go new file mode 100644 index 0000000..0f850fd --- /dev/null +++ b/utils/safe_api/client/nr4337/nr4337_client.go @@ -0,0 +1,277 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package nr4337 + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// New creates a new nr4337 API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +// New creates a new nr4337 API client with basic auth credentials. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - user: user for basic authentication header. +// - password: password for basic authentication header. +func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BasicAuth(user, password) + return &Client{transport: transport, formats: strfmt.Default} +} + +// New creates a new nr4337 API client with a bearer token for authentication. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - bearerToken: bearer token for Bearer authentication header. +func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) + return &Client{transport: transport, formats: strfmt.Default} +} + +/* +Client for nr4337 API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption may be used to customize the behavior of Client methods. +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + V1SafeOperationsRead(params *V1SafeOperationsReadParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafeOperationsReadOK, error) + + V1SafesSafeOperationsCreate(params *V1SafesSafeOperationsCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesSafeOperationsCreateCreated, error) + + V1SafesSafeOperationsList(params *V1SafesSafeOperationsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesSafeOperationsListOK, error) + + V1SafesUserOperationsList(params *V1SafesUserOperationsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesUserOperationsListOK, error) + + V1UserOperationsRead(params *V1UserOperationsReadParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1UserOperationsReadOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +V1SafeOperationsRead v1 safe operations read API +*/ +func (a *Client) V1SafeOperationsRead(params *V1SafeOperationsReadParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafeOperationsReadOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SafeOperationsReadParams() + } + op := &runtime.ClientOperation{ + ID: "v1_safe-operations_read", + Method: "GET", + PathPattern: "/v1/safe-operations/{safe_operation_hash}/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1SafeOperationsReadReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SafeOperationsReadOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_safe-operations_read: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* + V1SafesSafeOperationsCreate creates a new 4337 safe operation for a safe + + :param request: + +:param address: +:param args: +:param kwargs: +:return: +*/ +func (a *Client) V1SafesSafeOperationsCreate(params *V1SafesSafeOperationsCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesSafeOperationsCreateCreated, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SafesSafeOperationsCreateParams() + } + op := &runtime.ClientOperation{ + ID: "v1_safes_safe-operations_create", + Method: "POST", + PathPattern: "/v1/safes/{address}/safe-operations/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1SafesSafeOperationsCreateReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SafesSafeOperationsCreateCreated) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_safes_safe-operations_create: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1SafesSafeOperationsList v1 safes safe operations list API +*/ +func (a *Client) V1SafesSafeOperationsList(params *V1SafesSafeOperationsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesSafeOperationsListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SafesSafeOperationsListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_safes_safe-operations_list", + Method: "GET", + PathPattern: "/v1/safes/{address}/safe-operations/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1SafesSafeOperationsListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SafesSafeOperationsListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_safes_safe-operations_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1SafesUserOperationsList v1 safes user operations list API +*/ +func (a *Client) V1SafesUserOperationsList(params *V1SafesUserOperationsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesUserOperationsListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SafesUserOperationsListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_safes_user-operations_list", + Method: "GET", + PathPattern: "/v1/safes/{address}/user-operations/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1SafesUserOperationsListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SafesUserOperationsListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_safes_user-operations_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1UserOperationsRead v1 user operations read API +*/ +func (a *Client) V1UserOperationsRead(params *V1UserOperationsReadParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1UserOperationsReadOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1UserOperationsReadParams() + } + op := &runtime.ClientOperation{ + ID: "v1_user-operations_read", + Method: "GET", + PathPattern: "/v1/user-operations/{user_operation_hash}/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1UserOperationsReadReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1UserOperationsReadOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_user-operations_read: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/utils/safe_api/client/nr4337/v1_safe_operations_read_parameters.go b/utils/safe_api/client/nr4337/v1_safe_operations_read_parameters.go new file mode 100644 index 0000000..53e3167 --- /dev/null +++ b/utils/safe_api/client/nr4337/v1_safe_operations_read_parameters.go @@ -0,0 +1,148 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package nr4337 + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1SafeOperationsReadParams creates a new V1SafeOperationsReadParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SafeOperationsReadParams() *V1SafeOperationsReadParams { + return &V1SafeOperationsReadParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SafeOperationsReadParamsWithTimeout creates a new V1SafeOperationsReadParams object +// with the ability to set a timeout on a request. +func NewV1SafeOperationsReadParamsWithTimeout(timeout time.Duration) *V1SafeOperationsReadParams { + return &V1SafeOperationsReadParams{ + timeout: timeout, + } +} + +// NewV1SafeOperationsReadParamsWithContext creates a new V1SafeOperationsReadParams object +// with the ability to set a context for a request. +func NewV1SafeOperationsReadParamsWithContext(ctx context.Context) *V1SafeOperationsReadParams { + return &V1SafeOperationsReadParams{ + Context: ctx, + } +} + +// NewV1SafeOperationsReadParamsWithHTTPClient creates a new V1SafeOperationsReadParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SafeOperationsReadParamsWithHTTPClient(client *http.Client) *V1SafeOperationsReadParams { + return &V1SafeOperationsReadParams{ + HTTPClient: client, + } +} + +/* +V1SafeOperationsReadParams contains all the parameters to send to the API endpoint + + for the v1 safe operations read operation. + + Typically these are written to a http.Request. +*/ +type V1SafeOperationsReadParams struct { + + // SafeOperationHash. + SafeOperationHash string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 safe operations read params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafeOperationsReadParams) WithDefaults() *V1SafeOperationsReadParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 safe operations read params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafeOperationsReadParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 safe operations read params +func (o *V1SafeOperationsReadParams) WithTimeout(timeout time.Duration) *V1SafeOperationsReadParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 safe operations read params +func (o *V1SafeOperationsReadParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 safe operations read params +func (o *V1SafeOperationsReadParams) WithContext(ctx context.Context) *V1SafeOperationsReadParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 safe operations read params +func (o *V1SafeOperationsReadParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 safe operations read params +func (o *V1SafeOperationsReadParams) WithHTTPClient(client *http.Client) *V1SafeOperationsReadParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 safe operations read params +func (o *V1SafeOperationsReadParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithSafeOperationHash adds the safeOperationHash to the v1 safe operations read params +func (o *V1SafeOperationsReadParams) WithSafeOperationHash(safeOperationHash string) *V1SafeOperationsReadParams { + o.SetSafeOperationHash(safeOperationHash) + return o +} + +// SetSafeOperationHash adds the safeOperationHash to the v1 safe operations read params +func (o *V1SafeOperationsReadParams) SetSafeOperationHash(safeOperationHash string) { + o.SafeOperationHash = safeOperationHash +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SafeOperationsReadParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param safe_operation_hash + if err := r.SetPathParam("safe_operation_hash", o.SafeOperationHash); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/nr4337/v1_safe_operations_read_responses.go b/utils/safe_api/client/nr4337/v1_safe_operations_read_responses.go new file mode 100644 index 0000000..3518cd5 --- /dev/null +++ b/utils/safe_api/client/nr4337/v1_safe_operations_read_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package nr4337 + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1SafeOperationsReadReader is a Reader for the V1SafeOperationsRead structure. +type V1SafeOperationsReadReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SafeOperationsReadReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1SafeOperationsReadOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[GET /v1/safe-operations/{safe_operation_hash}/] v1_safe-operations_read", response, response.Code()) + } +} + +// NewV1SafeOperationsReadOK creates a V1SafeOperationsReadOK with default headers values +func NewV1SafeOperationsReadOK() *V1SafeOperationsReadOK { + return &V1SafeOperationsReadOK{} +} + +/* +V1SafeOperationsReadOK describes a response with status code 200, with default header values. + +V1SafeOperationsReadOK v1 safe operations read o k +*/ +type V1SafeOperationsReadOK struct { + Payload *models.SafeOperationWithUserOperationResponse +} + +// IsSuccess returns true when this v1 safe operations read o k response has a 2xx status code +func (o *V1SafeOperationsReadOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 safe operations read o k response has a 3xx status code +func (o *V1SafeOperationsReadOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safe operations read o k response has a 4xx status code +func (o *V1SafeOperationsReadOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 safe operations read o k response has a 5xx status code +func (o *V1SafeOperationsReadOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safe operations read o k response a status code equal to that given +func (o *V1SafeOperationsReadOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 safe operations read o k response +func (o *V1SafeOperationsReadOK) Code() int { + return 200 +} + +func (o *V1SafeOperationsReadOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safe-operations/{safe_operation_hash}/][%d] v1SafeOperationsReadOK %s", 200, payload) +} + +func (o *V1SafeOperationsReadOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safe-operations/{safe_operation_hash}/][%d] v1SafeOperationsReadOK %s", 200, payload) +} + +func (o *V1SafeOperationsReadOK) GetPayload() *models.SafeOperationWithUserOperationResponse { + return o.Payload +} + +func (o *V1SafeOperationsReadOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.SafeOperationWithUserOperationResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/utils/safe_api/client/nr4337/v1_safes_safe_operations_create_parameters.go b/utils/safe_api/client/nr4337/v1_safes_safe_operations_create_parameters.go new file mode 100644 index 0000000..46dbda9 --- /dev/null +++ b/utils/safe_api/client/nr4337/v1_safes_safe_operations_create_parameters.go @@ -0,0 +1,169 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package nr4337 + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// NewV1SafesSafeOperationsCreateParams creates a new V1SafesSafeOperationsCreateParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SafesSafeOperationsCreateParams() *V1SafesSafeOperationsCreateParams { + return &V1SafesSafeOperationsCreateParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SafesSafeOperationsCreateParamsWithTimeout creates a new V1SafesSafeOperationsCreateParams object +// with the ability to set a timeout on a request. +func NewV1SafesSafeOperationsCreateParamsWithTimeout(timeout time.Duration) *V1SafesSafeOperationsCreateParams { + return &V1SafesSafeOperationsCreateParams{ + timeout: timeout, + } +} + +// NewV1SafesSafeOperationsCreateParamsWithContext creates a new V1SafesSafeOperationsCreateParams object +// with the ability to set a context for a request. +func NewV1SafesSafeOperationsCreateParamsWithContext(ctx context.Context) *V1SafesSafeOperationsCreateParams { + return &V1SafesSafeOperationsCreateParams{ + Context: ctx, + } +} + +// NewV1SafesSafeOperationsCreateParamsWithHTTPClient creates a new V1SafesSafeOperationsCreateParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SafesSafeOperationsCreateParamsWithHTTPClient(client *http.Client) *V1SafesSafeOperationsCreateParams { + return &V1SafesSafeOperationsCreateParams{ + HTTPClient: client, + } +} + +/* +V1SafesSafeOperationsCreateParams contains all the parameters to send to the API endpoint + + for the v1 safes safe operations create operation. + + Typically these are written to a http.Request. +*/ +type V1SafesSafeOperationsCreateParams struct { + + // Address. + Address string + + // Data. + Data *models.SafeOperation + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 safes safe operations create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesSafeOperationsCreateParams) WithDefaults() *V1SafesSafeOperationsCreateParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 safes safe operations create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesSafeOperationsCreateParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 safes safe operations create params +func (o *V1SafesSafeOperationsCreateParams) WithTimeout(timeout time.Duration) *V1SafesSafeOperationsCreateParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 safes safe operations create params +func (o *V1SafesSafeOperationsCreateParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 safes safe operations create params +func (o *V1SafesSafeOperationsCreateParams) WithContext(ctx context.Context) *V1SafesSafeOperationsCreateParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 safes safe operations create params +func (o *V1SafesSafeOperationsCreateParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 safes safe operations create params +func (o *V1SafesSafeOperationsCreateParams) WithHTTPClient(client *http.Client) *V1SafesSafeOperationsCreateParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 safes safe operations create params +func (o *V1SafesSafeOperationsCreateParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 safes safe operations create params +func (o *V1SafesSafeOperationsCreateParams) WithAddress(address string) *V1SafesSafeOperationsCreateParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 safes safe operations create params +func (o *V1SafesSafeOperationsCreateParams) SetAddress(address string) { + o.Address = address +} + +// WithData adds the data to the v1 safes safe operations create params +func (o *V1SafesSafeOperationsCreateParams) WithData(data *models.SafeOperation) *V1SafesSafeOperationsCreateParams { + o.SetData(data) + return o +} + +// SetData adds the data to the v1 safes safe operations create params +func (o *V1SafesSafeOperationsCreateParams) SetData(data *models.SafeOperation) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SafesSafeOperationsCreateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/nr4337/v1_safes_safe_operations_create_responses.go b/utils/safe_api/client/nr4337/v1_safes_safe_operations_create_responses.go new file mode 100644 index 0000000..acaf9a7 --- /dev/null +++ b/utils/safe_api/client/nr4337/v1_safes_safe_operations_create_responses.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package nr4337 + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// V1SafesSafeOperationsCreateReader is a Reader for the V1SafesSafeOperationsCreate structure. +type V1SafesSafeOperationsCreateReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SafesSafeOperationsCreateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 201: + result := NewV1SafesSafeOperationsCreateCreated() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[POST /v1/safes/{address}/safe-operations/] v1_safes_safe-operations_create", response, response.Code()) + } +} + +// NewV1SafesSafeOperationsCreateCreated creates a V1SafesSafeOperationsCreateCreated with default headers values +func NewV1SafesSafeOperationsCreateCreated() *V1SafesSafeOperationsCreateCreated { + return &V1SafesSafeOperationsCreateCreated{} +} + +/* +V1SafesSafeOperationsCreateCreated describes a response with status code 201, with default header values. + +Created +*/ +type V1SafesSafeOperationsCreateCreated struct { +} + +// IsSuccess returns true when this v1 safes safe operations create created response has a 2xx status code +func (o *V1SafesSafeOperationsCreateCreated) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 safes safe operations create created response has a 3xx status code +func (o *V1SafesSafeOperationsCreateCreated) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes safe operations create created response has a 4xx status code +func (o *V1SafesSafeOperationsCreateCreated) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 safes safe operations create created response has a 5xx status code +func (o *V1SafesSafeOperationsCreateCreated) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes safe operations create created response a status code equal to that given +func (o *V1SafesSafeOperationsCreateCreated) IsCode(code int) bool { + return code == 201 +} + +// Code gets the status code for the v1 safes safe operations create created response +func (o *V1SafesSafeOperationsCreateCreated) Code() int { + return 201 +} + +func (o *V1SafesSafeOperationsCreateCreated) Error() string { + return fmt.Sprintf("[POST /v1/safes/{address}/safe-operations/][%d] v1SafesSafeOperationsCreateCreated", 201) +} + +func (o *V1SafesSafeOperationsCreateCreated) String() string { + return fmt.Sprintf("[POST /v1/safes/{address}/safe-operations/][%d] v1SafesSafeOperationsCreateCreated", 201) +} + +func (o *V1SafesSafeOperationsCreateCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/nr4337/v1_safes_safe_operations_list_parameters.go b/utils/safe_api/client/nr4337/v1_safes_safe_operations_list_parameters.go new file mode 100644 index 0000000..b6897ad --- /dev/null +++ b/utils/safe_api/client/nr4337/v1_safes_safe_operations_list_parameters.go @@ -0,0 +1,251 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package nr4337 + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewV1SafesSafeOperationsListParams creates a new V1SafesSafeOperationsListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SafesSafeOperationsListParams() *V1SafesSafeOperationsListParams { + return &V1SafesSafeOperationsListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SafesSafeOperationsListParamsWithTimeout creates a new V1SafesSafeOperationsListParams object +// with the ability to set a timeout on a request. +func NewV1SafesSafeOperationsListParamsWithTimeout(timeout time.Duration) *V1SafesSafeOperationsListParams { + return &V1SafesSafeOperationsListParams{ + timeout: timeout, + } +} + +// NewV1SafesSafeOperationsListParamsWithContext creates a new V1SafesSafeOperationsListParams object +// with the ability to set a context for a request. +func NewV1SafesSafeOperationsListParamsWithContext(ctx context.Context) *V1SafesSafeOperationsListParams { + return &V1SafesSafeOperationsListParams{ + Context: ctx, + } +} + +// NewV1SafesSafeOperationsListParamsWithHTTPClient creates a new V1SafesSafeOperationsListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SafesSafeOperationsListParamsWithHTTPClient(client *http.Client) *V1SafesSafeOperationsListParams { + return &V1SafesSafeOperationsListParams{ + HTTPClient: client, + } +} + +/* +V1SafesSafeOperationsListParams contains all the parameters to send to the API endpoint + + for the v1 safes safe operations list operation. + + Typically these are written to a http.Request. +*/ +type V1SafesSafeOperationsListParams struct { + + // Address. + Address string + + /* Limit. + + Number of results to return per page. + */ + Limit *int64 + + /* Offset. + + The initial index from which to return the results. + */ + Offset *int64 + + /* Ordering. + + Which field to use when ordering the results. + */ + Ordering *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 safes safe operations list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesSafeOperationsListParams) WithDefaults() *V1SafesSafeOperationsListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 safes safe operations list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesSafeOperationsListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 safes safe operations list params +func (o *V1SafesSafeOperationsListParams) WithTimeout(timeout time.Duration) *V1SafesSafeOperationsListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 safes safe operations list params +func (o *V1SafesSafeOperationsListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 safes safe operations list params +func (o *V1SafesSafeOperationsListParams) WithContext(ctx context.Context) *V1SafesSafeOperationsListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 safes safe operations list params +func (o *V1SafesSafeOperationsListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 safes safe operations list params +func (o *V1SafesSafeOperationsListParams) WithHTTPClient(client *http.Client) *V1SafesSafeOperationsListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 safes safe operations list params +func (o *V1SafesSafeOperationsListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 safes safe operations list params +func (o *V1SafesSafeOperationsListParams) WithAddress(address string) *V1SafesSafeOperationsListParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 safes safe operations list params +func (o *V1SafesSafeOperationsListParams) SetAddress(address string) { + o.Address = address +} + +// WithLimit adds the limit to the v1 safes safe operations list params +func (o *V1SafesSafeOperationsListParams) WithLimit(limit *int64) *V1SafesSafeOperationsListParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the v1 safes safe operations list params +func (o *V1SafesSafeOperationsListParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the v1 safes safe operations list params +func (o *V1SafesSafeOperationsListParams) WithOffset(offset *int64) *V1SafesSafeOperationsListParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the v1 safes safe operations list params +func (o *V1SafesSafeOperationsListParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithOrdering adds the ordering to the v1 safes safe operations list params +func (o *V1SafesSafeOperationsListParams) WithOrdering(ordering *string) *V1SafesSafeOperationsListParams { + o.SetOrdering(ordering) + return o +} + +// SetOrdering adds the ordering to the v1 safes safe operations list params +func (o *V1SafesSafeOperationsListParams) SetOrdering(ordering *string) { + o.Ordering = ordering +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SafesSafeOperationsListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Ordering != nil { + + // query param ordering + var qrOrdering string + + if o.Ordering != nil { + qrOrdering = *o.Ordering + } + qOrdering := qrOrdering + if qOrdering != "" { + + if err := r.SetQueryParam("ordering", qOrdering); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/nr4337/v1_safes_safe_operations_list_responses.go b/utils/safe_api/client/nr4337/v1_safes_safe_operations_list_responses.go new file mode 100644 index 0000000..5bbe77e --- /dev/null +++ b/utils/safe_api/client/nr4337/v1_safes_safe_operations_list_responses.go @@ -0,0 +1,277 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package nr4337 + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + models "omni-balance/utils/safe_api" +) + +// V1SafesSafeOperationsListReader is a Reader for the V1SafesSafeOperationsList structure. +type V1SafesSafeOperationsListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SafesSafeOperationsListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1SafesSafeOperationsListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[GET /v1/safes/{address}/safe-operations/] v1_safes_safe-operations_list", response, response.Code()) + } +} + +// NewV1SafesSafeOperationsListOK creates a V1SafesSafeOperationsListOK with default headers values +func NewV1SafesSafeOperationsListOK() *V1SafesSafeOperationsListOK { + return &V1SafesSafeOperationsListOK{} +} + +/* +V1SafesSafeOperationsListOK describes a response with status code 200, with default header values. + +V1SafesSafeOperationsListOK v1 safes safe operations list o k +*/ +type V1SafesSafeOperationsListOK struct { + Payload *V1SafesSafeOperationsListOKBody +} + +// IsSuccess returns true when this v1 safes safe operations list o k response has a 2xx status code +func (o *V1SafesSafeOperationsListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 safes safe operations list o k response has a 3xx status code +func (o *V1SafesSafeOperationsListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes safe operations list o k response has a 4xx status code +func (o *V1SafesSafeOperationsListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 safes safe operations list o k response has a 5xx status code +func (o *V1SafesSafeOperationsListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes safe operations list o k response a status code equal to that given +func (o *V1SafesSafeOperationsListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 safes safe operations list o k response +func (o *V1SafesSafeOperationsListOK) Code() int { + return 200 +} + +func (o *V1SafesSafeOperationsListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/safe-operations/][%d] v1SafesSafeOperationsListOK %s", 200, payload) +} + +func (o *V1SafesSafeOperationsListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/safe-operations/][%d] v1SafesSafeOperationsListOK %s", 200, payload) +} + +func (o *V1SafesSafeOperationsListOK) GetPayload() *V1SafesSafeOperationsListOKBody { + return o.Payload +} + +func (o *V1SafesSafeOperationsListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(V1SafesSafeOperationsListOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +V1SafesSafeOperationsListOKBody v1 safes safe operations list o k body +swagger:model V1SafesSafeOperationsListOKBody +*/ +type V1SafesSafeOperationsListOKBody struct { + + // count + // Required: true + Count *int64 `json:"count"` + + // next + // Format: uri + Next *strfmt.URI `json:"next,omitempty"` + + // previous + // Format: uri + Previous *strfmt.URI `json:"previous,omitempty"` + + // results + // Required: true + Results []*models.SafeOperationWithUserOperationResponse `json:"results"` +} + +// Validate validates this v1 safes safe operations list o k body +func (o *V1SafesSafeOperationsListOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateCount(formats); err != nil { + res = append(res, err) + } + + if err := o.validateNext(formats); err != nil { + res = append(res, err) + } + + if err := o.validatePrevious(formats); err != nil { + res = append(res, err) + } + + if err := o.validateResults(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V1SafesSafeOperationsListOKBody) validateCount(formats strfmt.Registry) error { + + if err := validate.Required("v1SafesSafeOperationsListOK"+"."+"count", "body", o.Count); err != nil { + return err + } + + return nil +} + +func (o *V1SafesSafeOperationsListOKBody) validateNext(formats strfmt.Registry) error { + if swag.IsZero(o.Next) { // not required + return nil + } + + if err := validate.FormatOf("v1SafesSafeOperationsListOK"+"."+"next", "body", "uri", o.Next.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V1SafesSafeOperationsListOKBody) validatePrevious(formats strfmt.Registry) error { + if swag.IsZero(o.Previous) { // not required + return nil + } + + if err := validate.FormatOf("v1SafesSafeOperationsListOK"+"."+"previous", "body", "uri", o.Previous.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V1SafesSafeOperationsListOKBody) validateResults(formats strfmt.Registry) error { + + if err := validate.Required("v1SafesSafeOperationsListOK"+"."+"results", "body", o.Results); err != nil { + return err + } + + for i := 0; i < len(o.Results); i++ { + if swag.IsZero(o.Results[i]) { // not required + continue + } + + if o.Results[i] != nil { + if err := o.Results[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v1SafesSafeOperationsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v1SafesSafeOperationsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this v1 safes safe operations list o k body based on the context it is used +func (o *V1SafesSafeOperationsListOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResults(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V1SafesSafeOperationsListOKBody) contextValidateResults(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Results); i++ { + + if o.Results[i] != nil { + + if swag.IsZero(o.Results[i]) { // not required + return nil + } + + if err := o.Results[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v1SafesSafeOperationsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v1SafesSafeOperationsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *V1SafesSafeOperationsListOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *V1SafesSafeOperationsListOKBody) UnmarshalBinary(b []byte) error { + var res V1SafesSafeOperationsListOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/utils/safe_api/client/nr4337/v1_safes_user_operations_list_parameters.go b/utils/safe_api/client/nr4337/v1_safes_user_operations_list_parameters.go new file mode 100644 index 0000000..f024e88 --- /dev/null +++ b/utils/safe_api/client/nr4337/v1_safes_user_operations_list_parameters.go @@ -0,0 +1,251 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package nr4337 + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewV1SafesUserOperationsListParams creates a new V1SafesUserOperationsListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SafesUserOperationsListParams() *V1SafesUserOperationsListParams { + return &V1SafesUserOperationsListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SafesUserOperationsListParamsWithTimeout creates a new V1SafesUserOperationsListParams object +// with the ability to set a timeout on a request. +func NewV1SafesUserOperationsListParamsWithTimeout(timeout time.Duration) *V1SafesUserOperationsListParams { + return &V1SafesUserOperationsListParams{ + timeout: timeout, + } +} + +// NewV1SafesUserOperationsListParamsWithContext creates a new V1SafesUserOperationsListParams object +// with the ability to set a context for a request. +func NewV1SafesUserOperationsListParamsWithContext(ctx context.Context) *V1SafesUserOperationsListParams { + return &V1SafesUserOperationsListParams{ + Context: ctx, + } +} + +// NewV1SafesUserOperationsListParamsWithHTTPClient creates a new V1SafesUserOperationsListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SafesUserOperationsListParamsWithHTTPClient(client *http.Client) *V1SafesUserOperationsListParams { + return &V1SafesUserOperationsListParams{ + HTTPClient: client, + } +} + +/* +V1SafesUserOperationsListParams contains all the parameters to send to the API endpoint + + for the v1 safes user operations list operation. + + Typically these are written to a http.Request. +*/ +type V1SafesUserOperationsListParams struct { + + // Address. + Address string + + /* Limit. + + Number of results to return per page. + */ + Limit *int64 + + /* Offset. + + The initial index from which to return the results. + */ + Offset *int64 + + /* Ordering. + + Which field to use when ordering the results. + */ + Ordering *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 safes user operations list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesUserOperationsListParams) WithDefaults() *V1SafesUserOperationsListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 safes user operations list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesUserOperationsListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 safes user operations list params +func (o *V1SafesUserOperationsListParams) WithTimeout(timeout time.Duration) *V1SafesUserOperationsListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 safes user operations list params +func (o *V1SafesUserOperationsListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 safes user operations list params +func (o *V1SafesUserOperationsListParams) WithContext(ctx context.Context) *V1SafesUserOperationsListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 safes user operations list params +func (o *V1SafesUserOperationsListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 safes user operations list params +func (o *V1SafesUserOperationsListParams) WithHTTPClient(client *http.Client) *V1SafesUserOperationsListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 safes user operations list params +func (o *V1SafesUserOperationsListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 safes user operations list params +func (o *V1SafesUserOperationsListParams) WithAddress(address string) *V1SafesUserOperationsListParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 safes user operations list params +func (o *V1SafesUserOperationsListParams) SetAddress(address string) { + o.Address = address +} + +// WithLimit adds the limit to the v1 safes user operations list params +func (o *V1SafesUserOperationsListParams) WithLimit(limit *int64) *V1SafesUserOperationsListParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the v1 safes user operations list params +func (o *V1SafesUserOperationsListParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the v1 safes user operations list params +func (o *V1SafesUserOperationsListParams) WithOffset(offset *int64) *V1SafesUserOperationsListParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the v1 safes user operations list params +func (o *V1SafesUserOperationsListParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithOrdering adds the ordering to the v1 safes user operations list params +func (o *V1SafesUserOperationsListParams) WithOrdering(ordering *string) *V1SafesUserOperationsListParams { + o.SetOrdering(ordering) + return o +} + +// SetOrdering adds the ordering to the v1 safes user operations list params +func (o *V1SafesUserOperationsListParams) SetOrdering(ordering *string) { + o.Ordering = ordering +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SafesUserOperationsListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Ordering != nil { + + // query param ordering + var qrOrdering string + + if o.Ordering != nil { + qrOrdering = *o.Ordering + } + qOrdering := qrOrdering + if qOrdering != "" { + + if err := r.SetQueryParam("ordering", qOrdering); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/nr4337/v1_safes_user_operations_list_responses.go b/utils/safe_api/client/nr4337/v1_safes_user_operations_list_responses.go new file mode 100644 index 0000000..0a7b5c0 --- /dev/null +++ b/utils/safe_api/client/nr4337/v1_safes_user_operations_list_responses.go @@ -0,0 +1,277 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package nr4337 + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + models "omni-balance/utils/safe_api" +) + +// V1SafesUserOperationsListReader is a Reader for the V1SafesUserOperationsList structure. +type V1SafesUserOperationsListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SafesUserOperationsListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1SafesUserOperationsListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[GET /v1/safes/{address}/user-operations/] v1_safes_user-operations_list", response, response.Code()) + } +} + +// NewV1SafesUserOperationsListOK creates a V1SafesUserOperationsListOK with default headers values +func NewV1SafesUserOperationsListOK() *V1SafesUserOperationsListOK { + return &V1SafesUserOperationsListOK{} +} + +/* +V1SafesUserOperationsListOK describes a response with status code 200, with default header values. + +V1SafesUserOperationsListOK v1 safes user operations list o k +*/ +type V1SafesUserOperationsListOK struct { + Payload *V1SafesUserOperationsListOKBody +} + +// IsSuccess returns true when this v1 safes user operations list o k response has a 2xx status code +func (o *V1SafesUserOperationsListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 safes user operations list o k response has a 3xx status code +func (o *V1SafesUserOperationsListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes user operations list o k response has a 4xx status code +func (o *V1SafesUserOperationsListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 safes user operations list o k response has a 5xx status code +func (o *V1SafesUserOperationsListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes user operations list o k response a status code equal to that given +func (o *V1SafesUserOperationsListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 safes user operations list o k response +func (o *V1SafesUserOperationsListOK) Code() int { + return 200 +} + +func (o *V1SafesUserOperationsListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/user-operations/][%d] v1SafesUserOperationsListOK %s", 200, payload) +} + +func (o *V1SafesUserOperationsListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/user-operations/][%d] v1SafesUserOperationsListOK %s", 200, payload) +} + +func (o *V1SafesUserOperationsListOK) GetPayload() *V1SafesUserOperationsListOKBody { + return o.Payload +} + +func (o *V1SafesUserOperationsListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(V1SafesUserOperationsListOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +V1SafesUserOperationsListOKBody v1 safes user operations list o k body +swagger:model V1SafesUserOperationsListOKBody +*/ +type V1SafesUserOperationsListOKBody struct { + + // count + // Required: true + Count *int64 `json:"count"` + + // next + // Format: uri + Next *strfmt.URI `json:"next,omitempty"` + + // previous + // Format: uri + Previous *strfmt.URI `json:"previous,omitempty"` + + // results + // Required: true + Results []*models.UserOperationWithSafeOperationResponse `json:"results"` +} + +// Validate validates this v1 safes user operations list o k body +func (o *V1SafesUserOperationsListOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateCount(formats); err != nil { + res = append(res, err) + } + + if err := o.validateNext(formats); err != nil { + res = append(res, err) + } + + if err := o.validatePrevious(formats); err != nil { + res = append(res, err) + } + + if err := o.validateResults(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V1SafesUserOperationsListOKBody) validateCount(formats strfmt.Registry) error { + + if err := validate.Required("v1SafesUserOperationsListOK"+"."+"count", "body", o.Count); err != nil { + return err + } + + return nil +} + +func (o *V1SafesUserOperationsListOKBody) validateNext(formats strfmt.Registry) error { + if swag.IsZero(o.Next) { // not required + return nil + } + + if err := validate.FormatOf("v1SafesUserOperationsListOK"+"."+"next", "body", "uri", o.Next.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V1SafesUserOperationsListOKBody) validatePrevious(formats strfmt.Registry) error { + if swag.IsZero(o.Previous) { // not required + return nil + } + + if err := validate.FormatOf("v1SafesUserOperationsListOK"+"."+"previous", "body", "uri", o.Previous.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V1SafesUserOperationsListOKBody) validateResults(formats strfmt.Registry) error { + + if err := validate.Required("v1SafesUserOperationsListOK"+"."+"results", "body", o.Results); err != nil { + return err + } + + for i := 0; i < len(o.Results); i++ { + if swag.IsZero(o.Results[i]) { // not required + continue + } + + if o.Results[i] != nil { + if err := o.Results[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v1SafesUserOperationsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v1SafesUserOperationsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this v1 safes user operations list o k body based on the context it is used +func (o *V1SafesUserOperationsListOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResults(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V1SafesUserOperationsListOKBody) contextValidateResults(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Results); i++ { + + if o.Results[i] != nil { + + if swag.IsZero(o.Results[i]) { // not required + return nil + } + + if err := o.Results[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v1SafesUserOperationsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v1SafesUserOperationsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *V1SafesUserOperationsListOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *V1SafesUserOperationsListOKBody) UnmarshalBinary(b []byte) error { + var res V1SafesUserOperationsListOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/utils/safe_api/client/nr4337/v1_user_operations_read_parameters.go b/utils/safe_api/client/nr4337/v1_user_operations_read_parameters.go new file mode 100644 index 0000000..c2191d0 --- /dev/null +++ b/utils/safe_api/client/nr4337/v1_user_operations_read_parameters.go @@ -0,0 +1,148 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package nr4337 + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1UserOperationsReadParams creates a new V1UserOperationsReadParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1UserOperationsReadParams() *V1UserOperationsReadParams { + return &V1UserOperationsReadParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1UserOperationsReadParamsWithTimeout creates a new V1UserOperationsReadParams object +// with the ability to set a timeout on a request. +func NewV1UserOperationsReadParamsWithTimeout(timeout time.Duration) *V1UserOperationsReadParams { + return &V1UserOperationsReadParams{ + timeout: timeout, + } +} + +// NewV1UserOperationsReadParamsWithContext creates a new V1UserOperationsReadParams object +// with the ability to set a context for a request. +func NewV1UserOperationsReadParamsWithContext(ctx context.Context) *V1UserOperationsReadParams { + return &V1UserOperationsReadParams{ + Context: ctx, + } +} + +// NewV1UserOperationsReadParamsWithHTTPClient creates a new V1UserOperationsReadParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1UserOperationsReadParamsWithHTTPClient(client *http.Client) *V1UserOperationsReadParams { + return &V1UserOperationsReadParams{ + HTTPClient: client, + } +} + +/* +V1UserOperationsReadParams contains all the parameters to send to the API endpoint + + for the v1 user operations read operation. + + Typically these are written to a http.Request. +*/ +type V1UserOperationsReadParams struct { + + // UserOperationHash. + UserOperationHash string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 user operations read params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1UserOperationsReadParams) WithDefaults() *V1UserOperationsReadParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 user operations read params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1UserOperationsReadParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 user operations read params +func (o *V1UserOperationsReadParams) WithTimeout(timeout time.Duration) *V1UserOperationsReadParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 user operations read params +func (o *V1UserOperationsReadParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 user operations read params +func (o *V1UserOperationsReadParams) WithContext(ctx context.Context) *V1UserOperationsReadParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 user operations read params +func (o *V1UserOperationsReadParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 user operations read params +func (o *V1UserOperationsReadParams) WithHTTPClient(client *http.Client) *V1UserOperationsReadParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 user operations read params +func (o *V1UserOperationsReadParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithUserOperationHash adds the userOperationHash to the v1 user operations read params +func (o *V1UserOperationsReadParams) WithUserOperationHash(userOperationHash string) *V1UserOperationsReadParams { + o.SetUserOperationHash(userOperationHash) + return o +} + +// SetUserOperationHash adds the userOperationHash to the v1 user operations read params +func (o *V1UserOperationsReadParams) SetUserOperationHash(userOperationHash string) { + o.UserOperationHash = userOperationHash +} + +// WriteToRequest writes these params to a swagger request +func (o *V1UserOperationsReadParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param user_operation_hash + if err := r.SetPathParam("user_operation_hash", o.UserOperationHash); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/nr4337/v1_user_operations_read_responses.go b/utils/safe_api/client/nr4337/v1_user_operations_read_responses.go new file mode 100644 index 0000000..319cde9 --- /dev/null +++ b/utils/safe_api/client/nr4337/v1_user_operations_read_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package nr4337 + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1UserOperationsReadReader is a Reader for the V1UserOperationsRead structure. +type V1UserOperationsReadReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1UserOperationsReadReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1UserOperationsReadOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[GET /v1/user-operations/{user_operation_hash}/] v1_user-operations_read", response, response.Code()) + } +} + +// NewV1UserOperationsReadOK creates a V1UserOperationsReadOK with default headers values +func NewV1UserOperationsReadOK() *V1UserOperationsReadOK { + return &V1UserOperationsReadOK{} +} + +/* +V1UserOperationsReadOK describes a response with status code 200, with default header values. + +V1UserOperationsReadOK v1 user operations read o k +*/ +type V1UserOperationsReadOK struct { + Payload *models.UserOperationWithSafeOperationResponse +} + +// IsSuccess returns true when this v1 user operations read o k response has a 2xx status code +func (o *V1UserOperationsReadOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 user operations read o k response has a 3xx status code +func (o *V1UserOperationsReadOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 user operations read o k response has a 4xx status code +func (o *V1UserOperationsReadOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 user operations read o k response has a 5xx status code +func (o *V1UserOperationsReadOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 user operations read o k response a status code equal to that given +func (o *V1UserOperationsReadOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 user operations read o k response +func (o *V1UserOperationsReadOK) Code() int { + return 200 +} + +func (o *V1UserOperationsReadOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/user-operations/{user_operation_hash}/][%d] v1UserOperationsReadOK %s", 200, payload) +} + +func (o *V1UserOperationsReadOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/user-operations/{user_operation_hash}/][%d] v1UserOperationsReadOK %s", 200, payload) +} + +func (o *V1UserOperationsReadOK) GetPayload() *models.UserOperationWithSafeOperationResponse { + return o.Payload +} + +func (o *V1UserOperationsReadOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.UserOperationWithSafeOperationResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/utils/safe_api/client/owners/owners_client.go b/utils/safe_api/client/owners/owners_client.go new file mode 100644 index 0000000..c750c80 --- /dev/null +++ b/utils/safe_api/client/owners/owners_client.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package owners + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// New creates a new owners API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +// New creates a new owners API client with basic auth credentials. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - user: user for basic authentication header. +// - password: password for basic authentication header. +func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BasicAuth(user, password) + return &Client{transport: transport, formats: strfmt.Default} +} + +// New creates a new owners API client with a bearer token for authentication. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - bearerToken: bearer token for Bearer authentication header. +func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) + return &Client{transport: transport, formats: strfmt.Default} +} + +/* +Client for owners API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption may be used to customize the behavior of Client methods. +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + V1OwnersSafesList(params *V1OwnersSafesListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1OwnersSafesListOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +V1OwnersSafesList Return Safes where the address provided is an owner +*/ +func (a *Client) V1OwnersSafesList(params *V1OwnersSafesListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1OwnersSafesListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1OwnersSafesListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_owners_safes_list", + Method: "GET", + PathPattern: "/v1/owners/{address}/safes/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1OwnersSafesListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1OwnersSafesListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_owners_safes_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/utils/safe_api/client/owners/v1_owners_safes_list_parameters.go b/utils/safe_api/client/owners/v1_owners_safes_list_parameters.go new file mode 100644 index 0000000..f60aec6 --- /dev/null +++ b/utils/safe_api/client/owners/v1_owners_safes_list_parameters.go @@ -0,0 +1,148 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package owners + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1OwnersSafesListParams creates a new V1OwnersSafesListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1OwnersSafesListParams() *V1OwnersSafesListParams { + return &V1OwnersSafesListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1OwnersSafesListParamsWithTimeout creates a new V1OwnersSafesListParams object +// with the ability to set a timeout on a request. +func NewV1OwnersSafesListParamsWithTimeout(timeout time.Duration) *V1OwnersSafesListParams { + return &V1OwnersSafesListParams{ + timeout: timeout, + } +} + +// NewV1OwnersSafesListParamsWithContext creates a new V1OwnersSafesListParams object +// with the ability to set a context for a request. +func NewV1OwnersSafesListParamsWithContext(ctx context.Context) *V1OwnersSafesListParams { + return &V1OwnersSafesListParams{ + Context: ctx, + } +} + +// NewV1OwnersSafesListParamsWithHTTPClient creates a new V1OwnersSafesListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1OwnersSafesListParamsWithHTTPClient(client *http.Client) *V1OwnersSafesListParams { + return &V1OwnersSafesListParams{ + HTTPClient: client, + } +} + +/* +V1OwnersSafesListParams contains all the parameters to send to the API endpoint + + for the v1 owners safes list operation. + + Typically these are written to a http.Request. +*/ +type V1OwnersSafesListParams struct { + + // Address. + Address string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 owners safes list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1OwnersSafesListParams) WithDefaults() *V1OwnersSafesListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 owners safes list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1OwnersSafesListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 owners safes list params +func (o *V1OwnersSafesListParams) WithTimeout(timeout time.Duration) *V1OwnersSafesListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 owners safes list params +func (o *V1OwnersSafesListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 owners safes list params +func (o *V1OwnersSafesListParams) WithContext(ctx context.Context) *V1OwnersSafesListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 owners safes list params +func (o *V1OwnersSafesListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 owners safes list params +func (o *V1OwnersSafesListParams) WithHTTPClient(client *http.Client) *V1OwnersSafesListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 owners safes list params +func (o *V1OwnersSafesListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 owners safes list params +func (o *V1OwnersSafesListParams) WithAddress(address string) *V1OwnersSafesListParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 owners safes list params +func (o *V1OwnersSafesListParams) SetAddress(address string) { + o.Address = address +} + +// WriteToRequest writes these params to a swagger request +func (o *V1OwnersSafesListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/owners/v1_owners_safes_list_responses.go b/utils/safe_api/client/owners/v1_owners_safes_list_responses.go new file mode 100644 index 0000000..6a17dd1 --- /dev/null +++ b/utils/safe_api/client/owners/v1_owners_safes_list_responses.go @@ -0,0 +1,168 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package owners + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1OwnersSafesListReader is a Reader for the V1OwnersSafesList structure. +type V1OwnersSafesListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1OwnersSafesListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1OwnersSafesListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 422: + result := NewV1OwnersSafesListUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/owners/{address}/safes/] v1_owners_safes_list", response, response.Code()) + } +} + +// NewV1OwnersSafesListOK creates a V1OwnersSafesListOK with default headers values +func NewV1OwnersSafesListOK() *V1OwnersSafesListOK { + return &V1OwnersSafesListOK{} +} + +/* +V1OwnersSafesListOK describes a response with status code 200, with default header values. + +V1OwnersSafesListOK v1 owners safes list o k +*/ +type V1OwnersSafesListOK struct { + Payload *models.OwnerResponse +} + +// IsSuccess returns true when this v1 owners safes list o k response has a 2xx status code +func (o *V1OwnersSafesListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 owners safes list o k response has a 3xx status code +func (o *V1OwnersSafesListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 owners safes list o k response has a 4xx status code +func (o *V1OwnersSafesListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 owners safes list o k response has a 5xx status code +func (o *V1OwnersSafesListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 owners safes list o k response a status code equal to that given +func (o *V1OwnersSafesListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 owners safes list o k response +func (o *V1OwnersSafesListOK) Code() int { + return 200 +} + +func (o *V1OwnersSafesListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/owners/{address}/safes/][%d] v1OwnersSafesListOK %s", 200, payload) +} + +func (o *V1OwnersSafesListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/owners/{address}/safes/][%d] v1OwnersSafesListOK %s", 200, payload) +} + +func (o *V1OwnersSafesListOK) GetPayload() *models.OwnerResponse { + return o.Payload +} + +func (o *V1OwnersSafesListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.OwnerResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1OwnersSafesListUnprocessableEntity creates a V1OwnersSafesListUnprocessableEntity with default headers values +func NewV1OwnersSafesListUnprocessableEntity() *V1OwnersSafesListUnprocessableEntity { + return &V1OwnersSafesListUnprocessableEntity{} +} + +/* +V1OwnersSafesListUnprocessableEntity describes a response with status code 422, with default header values. + +Owner address checksum not valid +*/ +type V1OwnersSafesListUnprocessableEntity struct { +} + +// IsSuccess returns true when this v1 owners safes list unprocessable entity response has a 2xx status code +func (o *V1OwnersSafesListUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 owners safes list unprocessable entity response has a 3xx status code +func (o *V1OwnersSafesListUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 owners safes list unprocessable entity response has a 4xx status code +func (o *V1OwnersSafesListUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 owners safes list unprocessable entity response has a 5xx status code +func (o *V1OwnersSafesListUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 owners safes list unprocessable entity response a status code equal to that given +func (o *V1OwnersSafesListUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 owners safes list unprocessable entity response +func (o *V1OwnersSafesListUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1OwnersSafesListUnprocessableEntity) Error() string { + return fmt.Sprintf("[GET /v1/owners/{address}/safes/][%d] v1OwnersSafesListUnprocessableEntity", 422) +} + +func (o *V1OwnersSafesListUnprocessableEntity) String() string { + return fmt.Sprintf("[GET /v1/owners/{address}/safes/][%d] v1OwnersSafesListUnprocessableEntity", 422) +} + +func (o *V1OwnersSafesListUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/safe_transaction_service_api_client.go b/utils/safe_api/client/safe_transaction_service_api_client.go new file mode 100644 index 0000000..cc77e69 --- /dev/null +++ b/utils/safe_api/client/safe_transaction_service_api_client.go @@ -0,0 +1,172 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package client + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "omni-balance/utils/safe_api/client/about" + "omni-balance/utils/safe_api/client/contracts" + "omni-balance/utils/safe_api/client/data_decoder" + "omni-balance/utils/safe_api/client/delegates" + "omni-balance/utils/safe_api/client/messages" + "omni-balance/utils/safe_api/client/modules" + "omni-balance/utils/safe_api/client/notifications" + "omni-balance/utils/safe_api/client/nr4337" + "omni-balance/utils/safe_api/client/owners" + "omni-balance/utils/safe_api/client/safes" + "omni-balance/utils/safe_api/client/tokens" + "omni-balance/utils/safe_api/client/transactions" + "omni-balance/utils/safe_api/client/transfer" +) + +// Default safe transaction service API HTTP client. +var Default = NewHTTPClient(nil) + +const ( + // DefaultHost is the default Host + // found in Meta (info) section of spec file + DefaultHost string = "safe-transaction-sepolia.safe.global" + // DefaultBasePath is the default BasePath + // found in Meta (info) section of spec file + DefaultBasePath string = "/api" +) + +// DefaultSchemes are the default schemes found in Meta (info) section of spec file +var DefaultSchemes = []string{"https"} + +// NewHTTPClient creates a new safe transaction service API HTTP client. +func NewHTTPClient(formats strfmt.Registry) *SafeTransactionServiceAPI { + return NewHTTPClientWithConfig(formats, nil) +} + +// NewHTTPClientWithConfig creates a new safe transaction service API HTTP client, +// using a customizable transport config. +func NewHTTPClientWithConfig(formats strfmt.Registry, cfg *TransportConfig) *SafeTransactionServiceAPI { + // ensure nullable parameters have default + if cfg == nil { + cfg = DefaultTransportConfig() + } + + // create transport and client + transport := httptransport.New(cfg.Host, cfg.BasePath, cfg.Schemes) + return New(transport, formats) +} + +// New creates a new safe transaction service API client +func New(transport runtime.ClientTransport, formats strfmt.Registry) *SafeTransactionServiceAPI { + // ensure nullable parameters have default + if formats == nil { + formats = strfmt.Default + } + + cli := new(SafeTransactionServiceAPI) + cli.Transport = transport + cli.About = about.New(transport, formats) + cli.Contracts = contracts.New(transport, formats) + cli.DataDecoder = data_decoder.New(transport, formats) + cli.Delegates = delegates.New(transport, formats) + cli.Messages = messages.New(transport, formats) + cli.Modules = modules.New(transport, formats) + cli.Notifications = notifications.New(transport, formats) + cli.Nr4337 = nr4337.New(transport, formats) + cli.Owners = owners.New(transport, formats) + cli.Safes = safes.New(transport, formats) + cli.Tokens = tokens.New(transport, formats) + cli.Transactions = transactions.New(transport, formats) + cli.Transfer = transfer.New(transport, formats) + return cli +} + +// DefaultTransportConfig creates a TransportConfig with the +// default settings taken from the meta section of the spec file. +func DefaultTransportConfig() *TransportConfig { + return &TransportConfig{ + Host: DefaultHost, + BasePath: DefaultBasePath, + Schemes: DefaultSchemes, + } +} + +// TransportConfig contains the transport related info, +// found in the meta section of the spec file. +type TransportConfig struct { + Host string + BasePath string + Schemes []string +} + +// WithHost overrides the default host, +// provided by the meta section of the spec file. +func (cfg *TransportConfig) WithHost(host string) *TransportConfig { + cfg.Host = host + return cfg +} + +// WithBasePath overrides the default basePath, +// provided by the meta section of the spec file. +func (cfg *TransportConfig) WithBasePath(basePath string) *TransportConfig { + cfg.BasePath = basePath + return cfg +} + +// WithSchemes overrides the default schemes, +// provided by the meta section of the spec file. +func (cfg *TransportConfig) WithSchemes(schemes []string) *TransportConfig { + cfg.Schemes = schemes + return cfg +} + +// SafeTransactionServiceAPI is a client for safe transaction service API +type SafeTransactionServiceAPI struct { + About about.ClientService + + Contracts contracts.ClientService + + DataDecoder data_decoder.ClientService + + Delegates delegates.ClientService + + Messages messages.ClientService + + Modules modules.ClientService + + Notifications notifications.ClientService + + Nr4337 nr4337.ClientService + + Owners owners.ClientService + + Safes safes.ClientService + + Tokens tokens.ClientService + + Transactions transactions.ClientService + + Transfer transfer.ClientService + + Transport runtime.ClientTransport +} + +// SetTransport changes the transport on the client and all its subresources +func (c *SafeTransactionServiceAPI) SetTransport(transport runtime.ClientTransport) { + c.Transport = transport + c.About.SetTransport(transport) + c.Contracts.SetTransport(transport) + c.DataDecoder.SetTransport(transport) + c.Delegates.SetTransport(transport) + c.Messages.SetTransport(transport) + c.Modules.SetTransport(transport) + c.Notifications.SetTransport(transport) + c.Nr4337.SetTransport(transport) + c.Owners.SetTransport(transport) + c.Safes.SetTransport(transport) + c.Tokens.SetTransport(transport) + c.Transactions.SetTransport(transport) + c.Transfer.SetTransport(transport) +} diff --git a/utils/safe_api/client/safes/safes_client.go b/utils/safe_api/client/safes/safes_client.go new file mode 100644 index 0000000..6157609 --- /dev/null +++ b/utils/safe_api/client/safes/safes_client.go @@ -0,0 +1,272 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// New creates a new safes API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +// New creates a new safes API client with basic auth credentials. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - user: user for basic authentication header. +// - password: password for basic authentication header. +func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BasicAuth(user, password) + return &Client{transport: transport, formats: strfmt.Default} +} + +// New creates a new safes API client with a bearer token for authentication. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - bearerToken: bearer token for Bearer authentication header. +func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) + return &Client{transport: transport, formats: strfmt.Default} +} + +/* +Client for safes API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption may be used to customize the behavior of Client methods. +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + V1SafesBalancesList(params *V1SafesBalancesListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesBalancesListOK, error) + + V1SafesCreationList(params *V1SafesCreationListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesCreationListOK, error) + + V1SafesDelegatesDelete(params *V1SafesDelegatesDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesDelegatesDeleteNoContent, error) + + V1SafesRead(params *V1SafesReadParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesReadOK, error) + + V2SafesCollectiblesList(params *V2SafesCollectiblesListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V2SafesCollectiblesListOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +V1SafesBalancesList Get balance for Ether and ERC20 tokens +*/ +func (a *Client) V1SafesBalancesList(params *V1SafesBalancesListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesBalancesListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SafesBalancesListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_safes_balances_list", + Method: "GET", + PathPattern: "/v1/safes/{address}/balances/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1SafesBalancesListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SafesBalancesListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_safes_balances_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1SafesCreationList Get status of the safe +*/ +func (a *Client) V1SafesCreationList(params *V1SafesCreationListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesCreationListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SafesCreationListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_safes_creation_list", + Method: "GET", + PathPattern: "/v1/safes/{address}/creation/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1SafesCreationListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SafesCreationListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_safes_creation_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* + V1SafesDelegatesDelete Delete a delegate for a Safe. Signature is built the same way that for adding a delegate. + +Check `POST /delegates/` +*/ +func (a *Client) V1SafesDelegatesDelete(params *V1SafesDelegatesDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesDelegatesDeleteNoContent, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SafesDelegatesDeleteParams() + } + op := &runtime.ClientOperation{ + ID: "v1_safes_delegates_delete", + Method: "DELETE", + PathPattern: "/v1/safes/{address}/delegates/{delegate_address}/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1SafesDelegatesDeleteReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SafesDelegatesDeleteNoContent) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_safes_delegates_delete: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1SafesRead Get status of the safe +*/ +func (a *Client) V1SafesRead(params *V1SafesReadParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesReadOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SafesReadParams() + } + op := &runtime.ClientOperation{ + ID: "v1_safes_read", + Method: "GET", + PathPattern: "/v1/safes/{address}/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1SafesReadReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SafesReadOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_safes_read: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V2SafesCollectiblesList Get collectibles (ERC721 tokens) and information about them +*/ +func (a *Client) V2SafesCollectiblesList(params *V2SafesCollectiblesListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V2SafesCollectiblesListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV2SafesCollectiblesListParams() + } + op := &runtime.ClientOperation{ + ID: "v2_safes_collectibles_list", + Method: "GET", + PathPattern: "/v2/safes/{address}/collectibles/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V2SafesCollectiblesListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V2SafesCollectiblesListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v2_safes_collectibles_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/utils/safe_api/client/safes/v1_safes_balances_list_parameters.go b/utils/safe_api/client/safes/v1_safes_balances_list_parameters.go new file mode 100644 index 0000000..ff7a661 --- /dev/null +++ b/utils/safe_api/client/safes/v1_safes_balances_list_parameters.go @@ -0,0 +1,231 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewV1SafesBalancesListParams creates a new V1SafesBalancesListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SafesBalancesListParams() *V1SafesBalancesListParams { + return &V1SafesBalancesListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SafesBalancesListParamsWithTimeout creates a new V1SafesBalancesListParams object +// with the ability to set a timeout on a request. +func NewV1SafesBalancesListParamsWithTimeout(timeout time.Duration) *V1SafesBalancesListParams { + return &V1SafesBalancesListParams{ + timeout: timeout, + } +} + +// NewV1SafesBalancesListParamsWithContext creates a new V1SafesBalancesListParams object +// with the ability to set a context for a request. +func NewV1SafesBalancesListParamsWithContext(ctx context.Context) *V1SafesBalancesListParams { + return &V1SafesBalancesListParams{ + Context: ctx, + } +} + +// NewV1SafesBalancesListParamsWithHTTPClient creates a new V1SafesBalancesListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SafesBalancesListParamsWithHTTPClient(client *http.Client) *V1SafesBalancesListParams { + return &V1SafesBalancesListParams{ + HTTPClient: client, + } +} + +/* +V1SafesBalancesListParams contains all the parameters to send to the API endpoint + + for the v1 safes balances list operation. + + Typically these are written to a http.Request. +*/ +type V1SafesBalancesListParams struct { + + // Address. + Address string + + /* ExcludeSpam. + + If `True` spam tokens will not be returned + */ + ExcludeSpam *bool + + /* Trusted. + + If `True` just trusted tokens will be returned + */ + Trusted *bool + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 safes balances list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesBalancesListParams) WithDefaults() *V1SafesBalancesListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 safes balances list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesBalancesListParams) SetDefaults() { + var ( + excludeSpamDefault = bool(false) + + trustedDefault = bool(false) + ) + + val := V1SafesBalancesListParams{ + ExcludeSpam: &excludeSpamDefault, + Trusted: &trustedDefault, + } + + val.timeout = o.timeout + val.Context = o.Context + val.HTTPClient = o.HTTPClient + *o = val +} + +// WithTimeout adds the timeout to the v1 safes balances list params +func (o *V1SafesBalancesListParams) WithTimeout(timeout time.Duration) *V1SafesBalancesListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 safes balances list params +func (o *V1SafesBalancesListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 safes balances list params +func (o *V1SafesBalancesListParams) WithContext(ctx context.Context) *V1SafesBalancesListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 safes balances list params +func (o *V1SafesBalancesListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 safes balances list params +func (o *V1SafesBalancesListParams) WithHTTPClient(client *http.Client) *V1SafesBalancesListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 safes balances list params +func (o *V1SafesBalancesListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 safes balances list params +func (o *V1SafesBalancesListParams) WithAddress(address string) *V1SafesBalancesListParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 safes balances list params +func (o *V1SafesBalancesListParams) SetAddress(address string) { + o.Address = address +} + +// WithExcludeSpam adds the excludeSpam to the v1 safes balances list params +func (o *V1SafesBalancesListParams) WithExcludeSpam(excludeSpam *bool) *V1SafesBalancesListParams { + o.SetExcludeSpam(excludeSpam) + return o +} + +// SetExcludeSpam adds the excludeSpam to the v1 safes balances list params +func (o *V1SafesBalancesListParams) SetExcludeSpam(excludeSpam *bool) { + o.ExcludeSpam = excludeSpam +} + +// WithTrusted adds the trusted to the v1 safes balances list params +func (o *V1SafesBalancesListParams) WithTrusted(trusted *bool) *V1SafesBalancesListParams { + o.SetTrusted(trusted) + return o +} + +// SetTrusted adds the trusted to the v1 safes balances list params +func (o *V1SafesBalancesListParams) SetTrusted(trusted *bool) { + o.Trusted = trusted +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SafesBalancesListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + + if o.ExcludeSpam != nil { + + // query param exclude_spam + var qrExcludeSpam bool + + if o.ExcludeSpam != nil { + qrExcludeSpam = *o.ExcludeSpam + } + qExcludeSpam := swag.FormatBool(qrExcludeSpam) + if qExcludeSpam != "" { + + if err := r.SetQueryParam("exclude_spam", qExcludeSpam); err != nil { + return err + } + } + } + + if o.Trusted != nil { + + // query param trusted + var qrTrusted bool + + if o.Trusted != nil { + qrTrusted = *o.Trusted + } + qTrusted := swag.FormatBool(qrTrusted) + if qTrusted != "" { + + if err := r.SetQueryParam("trusted", qTrusted); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/safes/v1_safes_balances_list_responses.go b/utils/safe_api/client/safes/v1_safes_balances_list_responses.go new file mode 100644 index 0000000..d1fed82 --- /dev/null +++ b/utils/safe_api/client/safes/v1_safes_balances_list_responses.go @@ -0,0 +1,228 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1SafesBalancesListReader is a Reader for the V1SafesBalancesList structure. +type V1SafesBalancesListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SafesBalancesListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1SafesBalancesListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewV1SafesBalancesListNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 422: + result := NewV1SafesBalancesListUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/safes/{address}/balances/] v1_safes_balances_list", response, response.Code()) + } +} + +// NewV1SafesBalancesListOK creates a V1SafesBalancesListOK with default headers values +func NewV1SafesBalancesListOK() *V1SafesBalancesListOK { + return &V1SafesBalancesListOK{} +} + +/* +V1SafesBalancesListOK describes a response with status code 200, with default header values. + +V1SafesBalancesListOK v1 safes balances list o k +*/ +type V1SafesBalancesListOK struct { + Payload []*models.SafeBalanceResponse +} + +// IsSuccess returns true when this v1 safes balances list o k response has a 2xx status code +func (o *V1SafesBalancesListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 safes balances list o k response has a 3xx status code +func (o *V1SafesBalancesListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes balances list o k response has a 4xx status code +func (o *V1SafesBalancesListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 safes balances list o k response has a 5xx status code +func (o *V1SafesBalancesListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes balances list o k response a status code equal to that given +func (o *V1SafesBalancesListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 safes balances list o k response +func (o *V1SafesBalancesListOK) Code() int { + return 200 +} + +func (o *V1SafesBalancesListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/balances/][%d] v1SafesBalancesListOK %s", 200, payload) +} + +func (o *V1SafesBalancesListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/balances/][%d] v1SafesBalancesListOK %s", 200, payload) +} + +func (o *V1SafesBalancesListOK) GetPayload() []*models.SafeBalanceResponse { + return o.Payload +} + +func (o *V1SafesBalancesListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SafesBalancesListNotFound creates a V1SafesBalancesListNotFound with default headers values +func NewV1SafesBalancesListNotFound() *V1SafesBalancesListNotFound { + return &V1SafesBalancesListNotFound{} +} + +/* +V1SafesBalancesListNotFound describes a response with status code 404, with default header values. + +Safe not found +*/ +type V1SafesBalancesListNotFound struct { +} + +// IsSuccess returns true when this v1 safes balances list not found response has a 2xx status code +func (o *V1SafesBalancesListNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes balances list not found response has a 3xx status code +func (o *V1SafesBalancesListNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes balances list not found response has a 4xx status code +func (o *V1SafesBalancesListNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes balances list not found response has a 5xx status code +func (o *V1SafesBalancesListNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes balances list not found response a status code equal to that given +func (o *V1SafesBalancesListNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 safes balances list not found response +func (o *V1SafesBalancesListNotFound) Code() int { + return 404 +} + +func (o *V1SafesBalancesListNotFound) Error() string { + return fmt.Sprintf("[GET /v1/safes/{address}/balances/][%d] v1SafesBalancesListNotFound", 404) +} + +func (o *V1SafesBalancesListNotFound) String() string { + return fmt.Sprintf("[GET /v1/safes/{address}/balances/][%d] v1SafesBalancesListNotFound", 404) +} + +func (o *V1SafesBalancesListNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1SafesBalancesListUnprocessableEntity creates a V1SafesBalancesListUnprocessableEntity with default headers values +func NewV1SafesBalancesListUnprocessableEntity() *V1SafesBalancesListUnprocessableEntity { + return &V1SafesBalancesListUnprocessableEntity{} +} + +/* +V1SafesBalancesListUnprocessableEntity describes a response with status code 422, with default header values. + +Safe address checksum not valid +*/ +type V1SafesBalancesListUnprocessableEntity struct { +} + +// IsSuccess returns true when this v1 safes balances list unprocessable entity response has a 2xx status code +func (o *V1SafesBalancesListUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes balances list unprocessable entity response has a 3xx status code +func (o *V1SafesBalancesListUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes balances list unprocessable entity response has a 4xx status code +func (o *V1SafesBalancesListUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes balances list unprocessable entity response has a 5xx status code +func (o *V1SafesBalancesListUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes balances list unprocessable entity response a status code equal to that given +func (o *V1SafesBalancesListUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 safes balances list unprocessable entity response +func (o *V1SafesBalancesListUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1SafesBalancesListUnprocessableEntity) Error() string { + return fmt.Sprintf("[GET /v1/safes/{address}/balances/][%d] v1SafesBalancesListUnprocessableEntity", 422) +} + +func (o *V1SafesBalancesListUnprocessableEntity) String() string { + return fmt.Sprintf("[GET /v1/safes/{address}/balances/][%d] v1SafesBalancesListUnprocessableEntity", 422) +} + +func (o *V1SafesBalancesListUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/safes/v1_safes_creation_list_parameters.go b/utils/safe_api/client/safes/v1_safes_creation_list_parameters.go new file mode 100644 index 0000000..9c38d23 --- /dev/null +++ b/utils/safe_api/client/safes/v1_safes_creation_list_parameters.go @@ -0,0 +1,148 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1SafesCreationListParams creates a new V1SafesCreationListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SafesCreationListParams() *V1SafesCreationListParams { + return &V1SafesCreationListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SafesCreationListParamsWithTimeout creates a new V1SafesCreationListParams object +// with the ability to set a timeout on a request. +func NewV1SafesCreationListParamsWithTimeout(timeout time.Duration) *V1SafesCreationListParams { + return &V1SafesCreationListParams{ + timeout: timeout, + } +} + +// NewV1SafesCreationListParamsWithContext creates a new V1SafesCreationListParams object +// with the ability to set a context for a request. +func NewV1SafesCreationListParamsWithContext(ctx context.Context) *V1SafesCreationListParams { + return &V1SafesCreationListParams{ + Context: ctx, + } +} + +// NewV1SafesCreationListParamsWithHTTPClient creates a new V1SafesCreationListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SafesCreationListParamsWithHTTPClient(client *http.Client) *V1SafesCreationListParams { + return &V1SafesCreationListParams{ + HTTPClient: client, + } +} + +/* +V1SafesCreationListParams contains all the parameters to send to the API endpoint + + for the v1 safes creation list operation. + + Typically these are written to a http.Request. +*/ +type V1SafesCreationListParams struct { + + // Address. + Address string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 safes creation list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesCreationListParams) WithDefaults() *V1SafesCreationListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 safes creation list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesCreationListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 safes creation list params +func (o *V1SafesCreationListParams) WithTimeout(timeout time.Duration) *V1SafesCreationListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 safes creation list params +func (o *V1SafesCreationListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 safes creation list params +func (o *V1SafesCreationListParams) WithContext(ctx context.Context) *V1SafesCreationListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 safes creation list params +func (o *V1SafesCreationListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 safes creation list params +func (o *V1SafesCreationListParams) WithHTTPClient(client *http.Client) *V1SafesCreationListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 safes creation list params +func (o *V1SafesCreationListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 safes creation list params +func (o *V1SafesCreationListParams) WithAddress(address string) *V1SafesCreationListParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 safes creation list params +func (o *V1SafesCreationListParams) SetAddress(address string) { + o.Address = address +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SafesCreationListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/safes/v1_safes_creation_list_responses.go b/utils/safe_api/client/safes/v1_safes_creation_list_responses.go new file mode 100644 index 0000000..1259ded --- /dev/null +++ b/utils/safe_api/client/safes/v1_safes_creation_list_responses.go @@ -0,0 +1,292 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1SafesCreationListReader is a Reader for the V1SafesCreationList structure. +type V1SafesCreationListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SafesCreationListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1SafesCreationListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewV1SafesCreationListNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 422: + result := NewV1SafesCreationListUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewV1SafesCreationListServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/safes/{address}/creation/] v1_safes_creation_list", response, response.Code()) + } +} + +// NewV1SafesCreationListOK creates a V1SafesCreationListOK with default headers values +func NewV1SafesCreationListOK() *V1SafesCreationListOK { + return &V1SafesCreationListOK{} +} + +/* +V1SafesCreationListOK describes a response with status code 200, with default header values. + +V1SafesCreationListOK v1 safes creation list o k +*/ +type V1SafesCreationListOK struct { + Payload *models.SafeCreationInfoResponse +} + +// IsSuccess returns true when this v1 safes creation list o k response has a 2xx status code +func (o *V1SafesCreationListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 safes creation list o k response has a 3xx status code +func (o *V1SafesCreationListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes creation list o k response has a 4xx status code +func (o *V1SafesCreationListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 safes creation list o k response has a 5xx status code +func (o *V1SafesCreationListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes creation list o k response a status code equal to that given +func (o *V1SafesCreationListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 safes creation list o k response +func (o *V1SafesCreationListOK) Code() int { + return 200 +} + +func (o *V1SafesCreationListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/creation/][%d] v1SafesCreationListOK %s", 200, payload) +} + +func (o *V1SafesCreationListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/creation/][%d] v1SafesCreationListOK %s", 200, payload) +} + +func (o *V1SafesCreationListOK) GetPayload() *models.SafeCreationInfoResponse { + return o.Payload +} + +func (o *V1SafesCreationListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.SafeCreationInfoResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SafesCreationListNotFound creates a V1SafesCreationListNotFound with default headers values +func NewV1SafesCreationListNotFound() *V1SafesCreationListNotFound { + return &V1SafesCreationListNotFound{} +} + +/* +V1SafesCreationListNotFound describes a response with status code 404, with default header values. + +Safe creation not found +*/ +type V1SafesCreationListNotFound struct { +} + +// IsSuccess returns true when this v1 safes creation list not found response has a 2xx status code +func (o *V1SafesCreationListNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes creation list not found response has a 3xx status code +func (o *V1SafesCreationListNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes creation list not found response has a 4xx status code +func (o *V1SafesCreationListNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes creation list not found response has a 5xx status code +func (o *V1SafesCreationListNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes creation list not found response a status code equal to that given +func (o *V1SafesCreationListNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 safes creation list not found response +func (o *V1SafesCreationListNotFound) Code() int { + return 404 +} + +func (o *V1SafesCreationListNotFound) Error() string { + return fmt.Sprintf("[GET /v1/safes/{address}/creation/][%d] v1SafesCreationListNotFound", 404) +} + +func (o *V1SafesCreationListNotFound) String() string { + return fmt.Sprintf("[GET /v1/safes/{address}/creation/][%d] v1SafesCreationListNotFound", 404) +} + +func (o *V1SafesCreationListNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1SafesCreationListUnprocessableEntity creates a V1SafesCreationListUnprocessableEntity with default headers values +func NewV1SafesCreationListUnprocessableEntity() *V1SafesCreationListUnprocessableEntity { + return &V1SafesCreationListUnprocessableEntity{} +} + +/* +V1SafesCreationListUnprocessableEntity describes a response with status code 422, with default header values. + +Owner address checksum not valid +*/ +type V1SafesCreationListUnprocessableEntity struct { +} + +// IsSuccess returns true when this v1 safes creation list unprocessable entity response has a 2xx status code +func (o *V1SafesCreationListUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes creation list unprocessable entity response has a 3xx status code +func (o *V1SafesCreationListUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes creation list unprocessable entity response has a 4xx status code +func (o *V1SafesCreationListUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes creation list unprocessable entity response has a 5xx status code +func (o *V1SafesCreationListUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes creation list unprocessable entity response a status code equal to that given +func (o *V1SafesCreationListUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 safes creation list unprocessable entity response +func (o *V1SafesCreationListUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1SafesCreationListUnprocessableEntity) Error() string { + return fmt.Sprintf("[GET /v1/safes/{address}/creation/][%d] v1SafesCreationListUnprocessableEntity", 422) +} + +func (o *V1SafesCreationListUnprocessableEntity) String() string { + return fmt.Sprintf("[GET /v1/safes/{address}/creation/][%d] v1SafesCreationListUnprocessableEntity", 422) +} + +func (o *V1SafesCreationListUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1SafesCreationListServiceUnavailable creates a V1SafesCreationListServiceUnavailable with default headers values +func NewV1SafesCreationListServiceUnavailable() *V1SafesCreationListServiceUnavailable { + return &V1SafesCreationListServiceUnavailable{} +} + +/* +V1SafesCreationListServiceUnavailable describes a response with status code 503, with default header values. + +Problem connecting to Ethereum network +*/ +type V1SafesCreationListServiceUnavailable struct { +} + +// IsSuccess returns true when this v1 safes creation list service unavailable response has a 2xx status code +func (o *V1SafesCreationListServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes creation list service unavailable response has a 3xx status code +func (o *V1SafesCreationListServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes creation list service unavailable response has a 4xx status code +func (o *V1SafesCreationListServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 safes creation list service unavailable response has a 5xx status code +func (o *V1SafesCreationListServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this v1 safes creation list service unavailable response a status code equal to that given +func (o *V1SafesCreationListServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the v1 safes creation list service unavailable response +func (o *V1SafesCreationListServiceUnavailable) Code() int { + return 503 +} + +func (o *V1SafesCreationListServiceUnavailable) Error() string { + return fmt.Sprintf("[GET /v1/safes/{address}/creation/][%d] v1SafesCreationListServiceUnavailable", 503) +} + +func (o *V1SafesCreationListServiceUnavailable) String() string { + return fmt.Sprintf("[GET /v1/safes/{address}/creation/][%d] v1SafesCreationListServiceUnavailable", 503) +} + +func (o *V1SafesCreationListServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/safes/v1_safes_delegates_delete_parameters.go b/utils/safe_api/client/safes/v1_safes_delegates_delete_parameters.go new file mode 100644 index 0000000..e7b0f74 --- /dev/null +++ b/utils/safe_api/client/safes/v1_safes_delegates_delete_parameters.go @@ -0,0 +1,188 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// NewV1SafesDelegatesDeleteParams creates a new V1SafesDelegatesDeleteParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SafesDelegatesDeleteParams() *V1SafesDelegatesDeleteParams { + return &V1SafesDelegatesDeleteParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SafesDelegatesDeleteParamsWithTimeout creates a new V1SafesDelegatesDeleteParams object +// with the ability to set a timeout on a request. +func NewV1SafesDelegatesDeleteParamsWithTimeout(timeout time.Duration) *V1SafesDelegatesDeleteParams { + return &V1SafesDelegatesDeleteParams{ + timeout: timeout, + } +} + +// NewV1SafesDelegatesDeleteParamsWithContext creates a new V1SafesDelegatesDeleteParams object +// with the ability to set a context for a request. +func NewV1SafesDelegatesDeleteParamsWithContext(ctx context.Context) *V1SafesDelegatesDeleteParams { + return &V1SafesDelegatesDeleteParams{ + Context: ctx, + } +} + +// NewV1SafesDelegatesDeleteParamsWithHTTPClient creates a new V1SafesDelegatesDeleteParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SafesDelegatesDeleteParamsWithHTTPClient(client *http.Client) *V1SafesDelegatesDeleteParams { + return &V1SafesDelegatesDeleteParams{ + HTTPClient: client, + } +} + +/* +V1SafesDelegatesDeleteParams contains all the parameters to send to the API endpoint + + for the v1 safes delegates delete operation. + + Typically these are written to a http.Request. +*/ +type V1SafesDelegatesDeleteParams struct { + + // Address. + Address string + + // Data. + Data *models.SafeDelegateDelete + + // DelegateAddress. + DelegateAddress string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 safes delegates delete params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesDelegatesDeleteParams) WithDefaults() *V1SafesDelegatesDeleteParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 safes delegates delete params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesDelegatesDeleteParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 safes delegates delete params +func (o *V1SafesDelegatesDeleteParams) WithTimeout(timeout time.Duration) *V1SafesDelegatesDeleteParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 safes delegates delete params +func (o *V1SafesDelegatesDeleteParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 safes delegates delete params +func (o *V1SafesDelegatesDeleteParams) WithContext(ctx context.Context) *V1SafesDelegatesDeleteParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 safes delegates delete params +func (o *V1SafesDelegatesDeleteParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 safes delegates delete params +func (o *V1SafesDelegatesDeleteParams) WithHTTPClient(client *http.Client) *V1SafesDelegatesDeleteParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 safes delegates delete params +func (o *V1SafesDelegatesDeleteParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 safes delegates delete params +func (o *V1SafesDelegatesDeleteParams) WithAddress(address string) *V1SafesDelegatesDeleteParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 safes delegates delete params +func (o *V1SafesDelegatesDeleteParams) SetAddress(address string) { + o.Address = address +} + +// WithData adds the data to the v1 safes delegates delete params +func (o *V1SafesDelegatesDeleteParams) WithData(data *models.SafeDelegateDelete) *V1SafesDelegatesDeleteParams { + o.SetData(data) + return o +} + +// SetData adds the data to the v1 safes delegates delete params +func (o *V1SafesDelegatesDeleteParams) SetData(data *models.SafeDelegateDelete) { + o.Data = data +} + +// WithDelegateAddress adds the delegateAddress to the v1 safes delegates delete params +func (o *V1SafesDelegatesDeleteParams) WithDelegateAddress(delegateAddress string) *V1SafesDelegatesDeleteParams { + o.SetDelegateAddress(delegateAddress) + return o +} + +// SetDelegateAddress adds the delegateAddress to the v1 safes delegates delete params +func (o *V1SafesDelegatesDeleteParams) SetDelegateAddress(delegateAddress string) { + o.DelegateAddress = delegateAddress +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SafesDelegatesDeleteParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + // path param delegate_address + if err := r.SetPathParam("delegate_address", o.DelegateAddress); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/safes/v1_safes_delegates_delete_responses.go b/utils/safe_api/client/safes/v1_safes_delegates_delete_responses.go new file mode 100644 index 0000000..e746d49 --- /dev/null +++ b/utils/safe_api/client/safes/v1_safes_delegates_delete_responses.go @@ -0,0 +1,274 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// V1SafesDelegatesDeleteReader is a Reader for the V1SafesDelegatesDelete structure. +type V1SafesDelegatesDeleteReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SafesDelegatesDeleteReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 204: + result := NewV1SafesDelegatesDeleteNoContent() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1SafesDelegatesDeleteBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewV1SafesDelegatesDeleteNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 422: + result := NewV1SafesDelegatesDeleteUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /v1/safes/{address}/delegates/{delegate_address}/] v1_safes_delegates_delete", response, response.Code()) + } +} + +// NewV1SafesDelegatesDeleteNoContent creates a V1SafesDelegatesDeleteNoContent with default headers values +func NewV1SafesDelegatesDeleteNoContent() *V1SafesDelegatesDeleteNoContent { + return &V1SafesDelegatesDeleteNoContent{} +} + +/* +V1SafesDelegatesDeleteNoContent describes a response with status code 204, with default header values. + +Deleted +*/ +type V1SafesDelegatesDeleteNoContent struct { +} + +// IsSuccess returns true when this v1 safes delegates delete no content response has a 2xx status code +func (o *V1SafesDelegatesDeleteNoContent) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 safes delegates delete no content response has a 3xx status code +func (o *V1SafesDelegatesDeleteNoContent) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes delegates delete no content response has a 4xx status code +func (o *V1SafesDelegatesDeleteNoContent) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 safes delegates delete no content response has a 5xx status code +func (o *V1SafesDelegatesDeleteNoContent) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes delegates delete no content response a status code equal to that given +func (o *V1SafesDelegatesDeleteNoContent) IsCode(code int) bool { + return code == 204 +} + +// Code gets the status code for the v1 safes delegates delete no content response +func (o *V1SafesDelegatesDeleteNoContent) Code() int { + return 204 +} + +func (o *V1SafesDelegatesDeleteNoContent) Error() string { + return fmt.Sprintf("[DELETE /v1/safes/{address}/delegates/{delegate_address}/][%d] v1SafesDelegatesDeleteNoContent", 204) +} + +func (o *V1SafesDelegatesDeleteNoContent) String() string { + return fmt.Sprintf("[DELETE /v1/safes/{address}/delegates/{delegate_address}/][%d] v1SafesDelegatesDeleteNoContent", 204) +} + +func (o *V1SafesDelegatesDeleteNoContent) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1SafesDelegatesDeleteBadRequest creates a V1SafesDelegatesDeleteBadRequest with default headers values +func NewV1SafesDelegatesDeleteBadRequest() *V1SafesDelegatesDeleteBadRequest { + return &V1SafesDelegatesDeleteBadRequest{} +} + +/* +V1SafesDelegatesDeleteBadRequest describes a response with status code 400, with default header values. + +Malformed data +*/ +type V1SafesDelegatesDeleteBadRequest struct { +} + +// IsSuccess returns true when this v1 safes delegates delete bad request response has a 2xx status code +func (o *V1SafesDelegatesDeleteBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes delegates delete bad request response has a 3xx status code +func (o *V1SafesDelegatesDeleteBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes delegates delete bad request response has a 4xx status code +func (o *V1SafesDelegatesDeleteBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes delegates delete bad request response has a 5xx status code +func (o *V1SafesDelegatesDeleteBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes delegates delete bad request response a status code equal to that given +func (o *V1SafesDelegatesDeleteBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 safes delegates delete bad request response +func (o *V1SafesDelegatesDeleteBadRequest) Code() int { + return 400 +} + +func (o *V1SafesDelegatesDeleteBadRequest) Error() string { + return fmt.Sprintf("[DELETE /v1/safes/{address}/delegates/{delegate_address}/][%d] v1SafesDelegatesDeleteBadRequest", 400) +} + +func (o *V1SafesDelegatesDeleteBadRequest) String() string { + return fmt.Sprintf("[DELETE /v1/safes/{address}/delegates/{delegate_address}/][%d] v1SafesDelegatesDeleteBadRequest", 400) +} + +func (o *V1SafesDelegatesDeleteBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1SafesDelegatesDeleteNotFound creates a V1SafesDelegatesDeleteNotFound with default headers values +func NewV1SafesDelegatesDeleteNotFound() *V1SafesDelegatesDeleteNotFound { + return &V1SafesDelegatesDeleteNotFound{} +} + +/* +V1SafesDelegatesDeleteNotFound describes a response with status code 404, with default header values. + +Delegate not found +*/ +type V1SafesDelegatesDeleteNotFound struct { +} + +// IsSuccess returns true when this v1 safes delegates delete not found response has a 2xx status code +func (o *V1SafesDelegatesDeleteNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes delegates delete not found response has a 3xx status code +func (o *V1SafesDelegatesDeleteNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes delegates delete not found response has a 4xx status code +func (o *V1SafesDelegatesDeleteNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes delegates delete not found response has a 5xx status code +func (o *V1SafesDelegatesDeleteNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes delegates delete not found response a status code equal to that given +func (o *V1SafesDelegatesDeleteNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 safes delegates delete not found response +func (o *V1SafesDelegatesDeleteNotFound) Code() int { + return 404 +} + +func (o *V1SafesDelegatesDeleteNotFound) Error() string { + return fmt.Sprintf("[DELETE /v1/safes/{address}/delegates/{delegate_address}/][%d] v1SafesDelegatesDeleteNotFound", 404) +} + +func (o *V1SafesDelegatesDeleteNotFound) String() string { + return fmt.Sprintf("[DELETE /v1/safes/{address}/delegates/{delegate_address}/][%d] v1SafesDelegatesDeleteNotFound", 404) +} + +func (o *V1SafesDelegatesDeleteNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1SafesDelegatesDeleteUnprocessableEntity creates a V1SafesDelegatesDeleteUnprocessableEntity with default headers values +func NewV1SafesDelegatesDeleteUnprocessableEntity() *V1SafesDelegatesDeleteUnprocessableEntity { + return &V1SafesDelegatesDeleteUnprocessableEntity{} +} + +/* +V1SafesDelegatesDeleteUnprocessableEntity describes a response with status code 422, with default header values. + +Invalid Ethereum address/Error processing data +*/ +type V1SafesDelegatesDeleteUnprocessableEntity struct { +} + +// IsSuccess returns true when this v1 safes delegates delete unprocessable entity response has a 2xx status code +func (o *V1SafesDelegatesDeleteUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes delegates delete unprocessable entity response has a 3xx status code +func (o *V1SafesDelegatesDeleteUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes delegates delete unprocessable entity response has a 4xx status code +func (o *V1SafesDelegatesDeleteUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes delegates delete unprocessable entity response has a 5xx status code +func (o *V1SafesDelegatesDeleteUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes delegates delete unprocessable entity response a status code equal to that given +func (o *V1SafesDelegatesDeleteUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 safes delegates delete unprocessable entity response +func (o *V1SafesDelegatesDeleteUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1SafesDelegatesDeleteUnprocessableEntity) Error() string { + return fmt.Sprintf("[DELETE /v1/safes/{address}/delegates/{delegate_address}/][%d] v1SafesDelegatesDeleteUnprocessableEntity", 422) +} + +func (o *V1SafesDelegatesDeleteUnprocessableEntity) String() string { + return fmt.Sprintf("[DELETE /v1/safes/{address}/delegates/{delegate_address}/][%d] v1SafesDelegatesDeleteUnprocessableEntity", 422) +} + +func (o *V1SafesDelegatesDeleteUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/safes/v1_safes_read_parameters.go b/utils/safe_api/client/safes/v1_safes_read_parameters.go new file mode 100644 index 0000000..fe50300 --- /dev/null +++ b/utils/safe_api/client/safes/v1_safes_read_parameters.go @@ -0,0 +1,148 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1SafesReadParams creates a new V1SafesReadParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SafesReadParams() *V1SafesReadParams { + return &V1SafesReadParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SafesReadParamsWithTimeout creates a new V1SafesReadParams object +// with the ability to set a timeout on a request. +func NewV1SafesReadParamsWithTimeout(timeout time.Duration) *V1SafesReadParams { + return &V1SafesReadParams{ + timeout: timeout, + } +} + +// NewV1SafesReadParamsWithContext creates a new V1SafesReadParams object +// with the ability to set a context for a request. +func NewV1SafesReadParamsWithContext(ctx context.Context) *V1SafesReadParams { + return &V1SafesReadParams{ + Context: ctx, + } +} + +// NewV1SafesReadParamsWithHTTPClient creates a new V1SafesReadParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SafesReadParamsWithHTTPClient(client *http.Client) *V1SafesReadParams { + return &V1SafesReadParams{ + HTTPClient: client, + } +} + +/* +V1SafesReadParams contains all the parameters to send to the API endpoint + + for the v1 safes read operation. + + Typically these are written to a http.Request. +*/ +type V1SafesReadParams struct { + + // Address. + Address string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 safes read params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesReadParams) WithDefaults() *V1SafesReadParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 safes read params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesReadParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 safes read params +func (o *V1SafesReadParams) WithTimeout(timeout time.Duration) *V1SafesReadParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 safes read params +func (o *V1SafesReadParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 safes read params +func (o *V1SafesReadParams) WithContext(ctx context.Context) *V1SafesReadParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 safes read params +func (o *V1SafesReadParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 safes read params +func (o *V1SafesReadParams) WithHTTPClient(client *http.Client) *V1SafesReadParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 safes read params +func (o *V1SafesReadParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 safes read params +func (o *V1SafesReadParams) WithAddress(address string) *V1SafesReadParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 safes read params +func (o *V1SafesReadParams) SetAddress(address string) { + o.Address = address +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SafesReadParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/safes/v1_safes_read_responses.go b/utils/safe_api/client/safes/v1_safes_read_responses.go new file mode 100644 index 0000000..7ac6a09 --- /dev/null +++ b/utils/safe_api/client/safes/v1_safes_read_responses.go @@ -0,0 +1,232 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1SafesReadReader is a Reader for the V1SafesRead structure. +type V1SafesReadReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SafesReadReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1SafesReadOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewV1SafesReadNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 422: + result := NewV1SafesReadUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/safes/{address}/] v1_safes_read", response, response.Code()) + } +} + +// NewV1SafesReadOK creates a V1SafesReadOK with default headers values +func NewV1SafesReadOK() *V1SafesReadOK { + return &V1SafesReadOK{} +} + +/* +V1SafesReadOK describes a response with status code 200, with default header values. + +V1SafesReadOK v1 safes read o k +*/ +type V1SafesReadOK struct { + Payload *models.SafeInfoResponse +} + +// IsSuccess returns true when this v1 safes read o k response has a 2xx status code +func (o *V1SafesReadOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 safes read o k response has a 3xx status code +func (o *V1SafesReadOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes read o k response has a 4xx status code +func (o *V1SafesReadOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 safes read o k response has a 5xx status code +func (o *V1SafesReadOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes read o k response a status code equal to that given +func (o *V1SafesReadOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 safes read o k response +func (o *V1SafesReadOK) Code() int { + return 200 +} + +func (o *V1SafesReadOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/][%d] v1SafesReadOK %s", 200, payload) +} + +func (o *V1SafesReadOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/][%d] v1SafesReadOK %s", 200, payload) +} + +func (o *V1SafesReadOK) GetPayload() *models.SafeInfoResponse { + return o.Payload +} + +func (o *V1SafesReadOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.SafeInfoResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SafesReadNotFound creates a V1SafesReadNotFound with default headers values +func NewV1SafesReadNotFound() *V1SafesReadNotFound { + return &V1SafesReadNotFound{} +} + +/* +V1SafesReadNotFound describes a response with status code 404, with default header values. + +Safe not found +*/ +type V1SafesReadNotFound struct { +} + +// IsSuccess returns true when this v1 safes read not found response has a 2xx status code +func (o *V1SafesReadNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes read not found response has a 3xx status code +func (o *V1SafesReadNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes read not found response has a 4xx status code +func (o *V1SafesReadNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes read not found response has a 5xx status code +func (o *V1SafesReadNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes read not found response a status code equal to that given +func (o *V1SafesReadNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 safes read not found response +func (o *V1SafesReadNotFound) Code() int { + return 404 +} + +func (o *V1SafesReadNotFound) Error() string { + return fmt.Sprintf("[GET /v1/safes/{address}/][%d] v1SafesReadNotFound", 404) +} + +func (o *V1SafesReadNotFound) String() string { + return fmt.Sprintf("[GET /v1/safes/{address}/][%d] v1SafesReadNotFound", 404) +} + +func (o *V1SafesReadNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1SafesReadUnprocessableEntity creates a V1SafesReadUnprocessableEntity with default headers values +func NewV1SafesReadUnprocessableEntity() *V1SafesReadUnprocessableEntity { + return &V1SafesReadUnprocessableEntity{} +} + +/* + V1SafesReadUnprocessableEntity describes a response with status code 422, with default header values. + + code = 1: Checksum address validation failed + +code = 50: Cannot get Safe info +*/ +type V1SafesReadUnprocessableEntity struct { +} + +// IsSuccess returns true when this v1 safes read unprocessable entity response has a 2xx status code +func (o *V1SafesReadUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes read unprocessable entity response has a 3xx status code +func (o *V1SafesReadUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes read unprocessable entity response has a 4xx status code +func (o *V1SafesReadUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes read unprocessable entity response has a 5xx status code +func (o *V1SafesReadUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes read unprocessable entity response a status code equal to that given +func (o *V1SafesReadUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 safes read unprocessable entity response +func (o *V1SafesReadUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1SafesReadUnprocessableEntity) Error() string { + return fmt.Sprintf("[GET /v1/safes/{address}/][%d] v1SafesReadUnprocessableEntity", 422) +} + +func (o *V1SafesReadUnprocessableEntity) String() string { + return fmt.Sprintf("[GET /v1/safes/{address}/][%d] v1SafesReadUnprocessableEntity", 422) +} + +func (o *V1SafesReadUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/safes/v2_safes_collectibles_list_parameters.go b/utils/safe_api/client/safes/v2_safes_collectibles_list_parameters.go new file mode 100644 index 0000000..272f9ec --- /dev/null +++ b/utils/safe_api/client/safes/v2_safes_collectibles_list_parameters.go @@ -0,0 +1,299 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewV2SafesCollectiblesListParams creates a new V2SafesCollectiblesListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV2SafesCollectiblesListParams() *V2SafesCollectiblesListParams { + return &V2SafesCollectiblesListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV2SafesCollectiblesListParamsWithTimeout creates a new V2SafesCollectiblesListParams object +// with the ability to set a timeout on a request. +func NewV2SafesCollectiblesListParamsWithTimeout(timeout time.Duration) *V2SafesCollectiblesListParams { + return &V2SafesCollectiblesListParams{ + timeout: timeout, + } +} + +// NewV2SafesCollectiblesListParamsWithContext creates a new V2SafesCollectiblesListParams object +// with the ability to set a context for a request. +func NewV2SafesCollectiblesListParamsWithContext(ctx context.Context) *V2SafesCollectiblesListParams { + return &V2SafesCollectiblesListParams{ + Context: ctx, + } +} + +// NewV2SafesCollectiblesListParamsWithHTTPClient creates a new V2SafesCollectiblesListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV2SafesCollectiblesListParamsWithHTTPClient(client *http.Client) *V2SafesCollectiblesListParams { + return &V2SafesCollectiblesListParams{ + HTTPClient: client, + } +} + +/* +V2SafesCollectiblesListParams contains all the parameters to send to the API endpoint + + for the v2 safes collectibles list operation. + + Typically these are written to a http.Request. +*/ +type V2SafesCollectiblesListParams struct { + + // Address. + Address string + + /* ExcludeSpam. + + If `True` spam tokens will not be returned + */ + ExcludeSpam *bool + + /* Limit. + + Number of results to return per page. + */ + Limit *int64 + + /* Offset. + + The initial index from which to return the results. + */ + Offset *int64 + + /* Trusted. + + If `True` just trusted tokens will be returned + */ + Trusted *bool + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v2 safes collectibles list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V2SafesCollectiblesListParams) WithDefaults() *V2SafesCollectiblesListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v2 safes collectibles list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V2SafesCollectiblesListParams) SetDefaults() { + var ( + excludeSpamDefault = bool(false) + + trustedDefault = bool(false) + ) + + val := V2SafesCollectiblesListParams{ + ExcludeSpam: &excludeSpamDefault, + Trusted: &trustedDefault, + } + + val.timeout = o.timeout + val.Context = o.Context + val.HTTPClient = o.HTTPClient + *o = val +} + +// WithTimeout adds the timeout to the v2 safes collectibles list params +func (o *V2SafesCollectiblesListParams) WithTimeout(timeout time.Duration) *V2SafesCollectiblesListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v2 safes collectibles list params +func (o *V2SafesCollectiblesListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v2 safes collectibles list params +func (o *V2SafesCollectiblesListParams) WithContext(ctx context.Context) *V2SafesCollectiblesListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v2 safes collectibles list params +func (o *V2SafesCollectiblesListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v2 safes collectibles list params +func (o *V2SafesCollectiblesListParams) WithHTTPClient(client *http.Client) *V2SafesCollectiblesListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v2 safes collectibles list params +func (o *V2SafesCollectiblesListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v2 safes collectibles list params +func (o *V2SafesCollectiblesListParams) WithAddress(address string) *V2SafesCollectiblesListParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v2 safes collectibles list params +func (o *V2SafesCollectiblesListParams) SetAddress(address string) { + o.Address = address +} + +// WithExcludeSpam adds the excludeSpam to the v2 safes collectibles list params +func (o *V2SafesCollectiblesListParams) WithExcludeSpam(excludeSpam *bool) *V2SafesCollectiblesListParams { + o.SetExcludeSpam(excludeSpam) + return o +} + +// SetExcludeSpam adds the excludeSpam to the v2 safes collectibles list params +func (o *V2SafesCollectiblesListParams) SetExcludeSpam(excludeSpam *bool) { + o.ExcludeSpam = excludeSpam +} + +// WithLimit adds the limit to the v2 safes collectibles list params +func (o *V2SafesCollectiblesListParams) WithLimit(limit *int64) *V2SafesCollectiblesListParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the v2 safes collectibles list params +func (o *V2SafesCollectiblesListParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the v2 safes collectibles list params +func (o *V2SafesCollectiblesListParams) WithOffset(offset *int64) *V2SafesCollectiblesListParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the v2 safes collectibles list params +func (o *V2SafesCollectiblesListParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithTrusted adds the trusted to the v2 safes collectibles list params +func (o *V2SafesCollectiblesListParams) WithTrusted(trusted *bool) *V2SafesCollectiblesListParams { + o.SetTrusted(trusted) + return o +} + +// SetTrusted adds the trusted to the v2 safes collectibles list params +func (o *V2SafesCollectiblesListParams) SetTrusted(trusted *bool) { + o.Trusted = trusted +} + +// WriteToRequest writes these params to a swagger request +func (o *V2SafesCollectiblesListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + + if o.ExcludeSpam != nil { + + // query param exclude_spam + var qrExcludeSpam bool + + if o.ExcludeSpam != nil { + qrExcludeSpam = *o.ExcludeSpam + } + qExcludeSpam := swag.FormatBool(qrExcludeSpam) + if qExcludeSpam != "" { + + if err := r.SetQueryParam("exclude_spam", qExcludeSpam); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Trusted != nil { + + // query param trusted + var qrTrusted bool + + if o.Trusted != nil { + qrTrusted = *o.Trusted + } + qTrusted := swag.FormatBool(qrTrusted) + if qTrusted != "" { + + if err := r.SetQueryParam("trusted", qTrusted); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/safes/v2_safes_collectibles_list_responses.go b/utils/safe_api/client/safes/v2_safes_collectibles_list_responses.go new file mode 100644 index 0000000..52dd3f6 --- /dev/null +++ b/utils/safe_api/client/safes/v2_safes_collectibles_list_responses.go @@ -0,0 +1,228 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safes + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V2SafesCollectiblesListReader is a Reader for the V2SafesCollectiblesList structure. +type V2SafesCollectiblesListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V2SafesCollectiblesListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV2SafesCollectiblesListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewV2SafesCollectiblesListNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 422: + result := NewV2SafesCollectiblesListUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v2/safes/{address}/collectibles/] v2_safes_collectibles_list", response, response.Code()) + } +} + +// NewV2SafesCollectiblesListOK creates a V2SafesCollectiblesListOK with default headers values +func NewV2SafesCollectiblesListOK() *V2SafesCollectiblesListOK { + return &V2SafesCollectiblesListOK{} +} + +/* +V2SafesCollectiblesListOK describes a response with status code 200, with default header values. + +V2SafesCollectiblesListOK v2 safes collectibles list o k +*/ +type V2SafesCollectiblesListOK struct { + Payload []*models.SafeCollectibleResponse +} + +// IsSuccess returns true when this v2 safes collectibles list o k response has a 2xx status code +func (o *V2SafesCollectiblesListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v2 safes collectibles list o k response has a 3xx status code +func (o *V2SafesCollectiblesListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v2 safes collectibles list o k response has a 4xx status code +func (o *V2SafesCollectiblesListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v2 safes collectibles list o k response has a 5xx status code +func (o *V2SafesCollectiblesListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v2 safes collectibles list o k response a status code equal to that given +func (o *V2SafesCollectiblesListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v2 safes collectibles list o k response +func (o *V2SafesCollectiblesListOK) Code() int { + return 200 +} + +func (o *V2SafesCollectiblesListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v2/safes/{address}/collectibles/][%d] v2SafesCollectiblesListOK %s", 200, payload) +} + +func (o *V2SafesCollectiblesListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v2/safes/{address}/collectibles/][%d] v2SafesCollectiblesListOK %s", 200, payload) +} + +func (o *V2SafesCollectiblesListOK) GetPayload() []*models.SafeCollectibleResponse { + return o.Payload +} + +func (o *V2SafesCollectiblesListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV2SafesCollectiblesListNotFound creates a V2SafesCollectiblesListNotFound with default headers values +func NewV2SafesCollectiblesListNotFound() *V2SafesCollectiblesListNotFound { + return &V2SafesCollectiblesListNotFound{} +} + +/* +V2SafesCollectiblesListNotFound describes a response with status code 404, with default header values. + +Safe not found +*/ +type V2SafesCollectiblesListNotFound struct { +} + +// IsSuccess returns true when this v2 safes collectibles list not found response has a 2xx status code +func (o *V2SafesCollectiblesListNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v2 safes collectibles list not found response has a 3xx status code +func (o *V2SafesCollectiblesListNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v2 safes collectibles list not found response has a 4xx status code +func (o *V2SafesCollectiblesListNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v2 safes collectibles list not found response has a 5xx status code +func (o *V2SafesCollectiblesListNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v2 safes collectibles list not found response a status code equal to that given +func (o *V2SafesCollectiblesListNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v2 safes collectibles list not found response +func (o *V2SafesCollectiblesListNotFound) Code() int { + return 404 +} + +func (o *V2SafesCollectiblesListNotFound) Error() string { + return fmt.Sprintf("[GET /v2/safes/{address}/collectibles/][%d] v2SafesCollectiblesListNotFound", 404) +} + +func (o *V2SafesCollectiblesListNotFound) String() string { + return fmt.Sprintf("[GET /v2/safes/{address}/collectibles/][%d] v2SafesCollectiblesListNotFound", 404) +} + +func (o *V2SafesCollectiblesListNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV2SafesCollectiblesListUnprocessableEntity creates a V2SafesCollectiblesListUnprocessableEntity with default headers values +func NewV2SafesCollectiblesListUnprocessableEntity() *V2SafesCollectiblesListUnprocessableEntity { + return &V2SafesCollectiblesListUnprocessableEntity{} +} + +/* +V2SafesCollectiblesListUnprocessableEntity describes a response with status code 422, with default header values. + +Safe address checksum not valid +*/ +type V2SafesCollectiblesListUnprocessableEntity struct { +} + +// IsSuccess returns true when this v2 safes collectibles list unprocessable entity response has a 2xx status code +func (o *V2SafesCollectiblesListUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v2 safes collectibles list unprocessable entity response has a 3xx status code +func (o *V2SafesCollectiblesListUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v2 safes collectibles list unprocessable entity response has a 4xx status code +func (o *V2SafesCollectiblesListUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v2 safes collectibles list unprocessable entity response has a 5xx status code +func (o *V2SafesCollectiblesListUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v2 safes collectibles list unprocessable entity response a status code equal to that given +func (o *V2SafesCollectiblesListUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v2 safes collectibles list unprocessable entity response +func (o *V2SafesCollectiblesListUnprocessableEntity) Code() int { + return 422 +} + +func (o *V2SafesCollectiblesListUnprocessableEntity) Error() string { + return fmt.Sprintf("[GET /v2/safes/{address}/collectibles/][%d] v2SafesCollectiblesListUnprocessableEntity", 422) +} + +func (o *V2SafesCollectiblesListUnprocessableEntity) String() string { + return fmt.Sprintf("[GET /v2/safes/{address}/collectibles/][%d] v2SafesCollectiblesListUnprocessableEntity", 422) +} + +func (o *V2SafesCollectiblesListUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/tokens/tokens_client.go b/utils/safe_api/client/tokens/tokens_client.go new file mode 100644 index 0000000..7ee8cbc --- /dev/null +++ b/utils/safe_api/client/tokens/tokens_client.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package tokens + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// New creates a new tokens API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +// New creates a new tokens API client with basic auth credentials. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - user: user for basic authentication header. +// - password: password for basic authentication header. +func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BasicAuth(user, password) + return &Client{transport: transport, formats: strfmt.Default} +} + +// New creates a new tokens API client with a bearer token for authentication. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - bearerToken: bearer token for Bearer authentication header. +func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) + return &Client{transport: transport, formats: strfmt.Default} +} + +/* +Client for tokens API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption may be used to customize the behavior of Client methods. +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + V1TokensList(params *V1TokensListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1TokensListOK, error) + + V1TokensRead(params *V1TokensReadParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1TokensReadOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +V1TokensList v1 tokens list API +*/ +func (a *Client) V1TokensList(params *V1TokensListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1TokensListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1TokensListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_tokens_list", + Method: "GET", + PathPattern: "/v1/tokens/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1TokensListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1TokensListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_tokens_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1TokensRead v1 tokens read API +*/ +func (a *Client) V1TokensRead(params *V1TokensReadParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1TokensReadOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1TokensReadParams() + } + op := &runtime.ClientOperation{ + ID: "v1_tokens_read", + Method: "GET", + PathPattern: "/v1/tokens/{address}/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1TokensReadReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1TokensReadOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_tokens_read: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/utils/safe_api/client/tokens/v1_tokens_list_parameters.go b/utils/safe_api/client/tokens/v1_tokens_list_parameters.go new file mode 100644 index 0000000..fbca060 --- /dev/null +++ b/utils/safe_api/client/tokens/v1_tokens_list_parameters.go @@ -0,0 +1,470 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package tokens + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewV1TokensListParams creates a new V1TokensListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1TokensListParams() *V1TokensListParams { + return &V1TokensListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1TokensListParamsWithTimeout creates a new V1TokensListParams object +// with the ability to set a timeout on a request. +func NewV1TokensListParamsWithTimeout(timeout time.Duration) *V1TokensListParams { + return &V1TokensListParams{ + timeout: timeout, + } +} + +// NewV1TokensListParamsWithContext creates a new V1TokensListParams object +// with the ability to set a context for a request. +func NewV1TokensListParamsWithContext(ctx context.Context) *V1TokensListParams { + return &V1TokensListParams{ + Context: ctx, + } +} + +// NewV1TokensListParamsWithHTTPClient creates a new V1TokensListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1TokensListParamsWithHTTPClient(client *http.Client) *V1TokensListParams { + return &V1TokensListParams{ + HTTPClient: client, + } +} + +/* +V1TokensListParams contains all the parameters to send to the API endpoint + + for the v1 tokens list operation. + + Typically these are written to a http.Request. +*/ +type V1TokensListParams struct { + + /* Address. + + address + */ + Address *string + + /* Decimals. + + decimals + */ + Decimals *string + + /* DecimalsGt. + + decimals__gt + */ + DecimalsGt *string + + /* DecimalsLt. + + decimals__lt + */ + DecimalsLt *string + + /* Limit. + + Number of results to return per page. + */ + Limit *int64 + + /* Name. + + name + */ + Name *string + + /* Offset. + + The initial index from which to return the results. + */ + Offset *int64 + + /* Ordering. + + Which field to use when ordering the results. + */ + Ordering *string + + /* Search. + + A search term. + */ + Search *string + + /* Symbol. + + symbol + */ + Symbol *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 tokens list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1TokensListParams) WithDefaults() *V1TokensListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 tokens list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1TokensListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 tokens list params +func (o *V1TokensListParams) WithTimeout(timeout time.Duration) *V1TokensListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 tokens list params +func (o *V1TokensListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 tokens list params +func (o *V1TokensListParams) WithContext(ctx context.Context) *V1TokensListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 tokens list params +func (o *V1TokensListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 tokens list params +func (o *V1TokensListParams) WithHTTPClient(client *http.Client) *V1TokensListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 tokens list params +func (o *V1TokensListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 tokens list params +func (o *V1TokensListParams) WithAddress(address *string) *V1TokensListParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 tokens list params +func (o *V1TokensListParams) SetAddress(address *string) { + o.Address = address +} + +// WithDecimals adds the decimals to the v1 tokens list params +func (o *V1TokensListParams) WithDecimals(decimals *string) *V1TokensListParams { + o.SetDecimals(decimals) + return o +} + +// SetDecimals adds the decimals to the v1 tokens list params +func (o *V1TokensListParams) SetDecimals(decimals *string) { + o.Decimals = decimals +} + +// WithDecimalsGt adds the decimalsGt to the v1 tokens list params +func (o *V1TokensListParams) WithDecimalsGt(decimalsGt *string) *V1TokensListParams { + o.SetDecimalsGt(decimalsGt) + return o +} + +// SetDecimalsGt adds the decimalsGt to the v1 tokens list params +func (o *V1TokensListParams) SetDecimalsGt(decimalsGt *string) { + o.DecimalsGt = decimalsGt +} + +// WithDecimalsLt adds the decimalsLt to the v1 tokens list params +func (o *V1TokensListParams) WithDecimalsLt(decimalsLt *string) *V1TokensListParams { + o.SetDecimalsLt(decimalsLt) + return o +} + +// SetDecimalsLt adds the decimalsLt to the v1 tokens list params +func (o *V1TokensListParams) SetDecimalsLt(decimalsLt *string) { + o.DecimalsLt = decimalsLt +} + +// WithLimit adds the limit to the v1 tokens list params +func (o *V1TokensListParams) WithLimit(limit *int64) *V1TokensListParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the v1 tokens list params +func (o *V1TokensListParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithName adds the name to the v1 tokens list params +func (o *V1TokensListParams) WithName(name *string) *V1TokensListParams { + o.SetName(name) + return o +} + +// SetName adds the name to the v1 tokens list params +func (o *V1TokensListParams) SetName(name *string) { + o.Name = name +} + +// WithOffset adds the offset to the v1 tokens list params +func (o *V1TokensListParams) WithOffset(offset *int64) *V1TokensListParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the v1 tokens list params +func (o *V1TokensListParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithOrdering adds the ordering to the v1 tokens list params +func (o *V1TokensListParams) WithOrdering(ordering *string) *V1TokensListParams { + o.SetOrdering(ordering) + return o +} + +// SetOrdering adds the ordering to the v1 tokens list params +func (o *V1TokensListParams) SetOrdering(ordering *string) { + o.Ordering = ordering +} + +// WithSearch adds the search to the v1 tokens list params +func (o *V1TokensListParams) WithSearch(search *string) *V1TokensListParams { + o.SetSearch(search) + return o +} + +// SetSearch adds the search to the v1 tokens list params +func (o *V1TokensListParams) SetSearch(search *string) { + o.Search = search +} + +// WithSymbol adds the symbol to the v1 tokens list params +func (o *V1TokensListParams) WithSymbol(symbol *string) *V1TokensListParams { + o.SetSymbol(symbol) + return o +} + +// SetSymbol adds the symbol to the v1 tokens list params +func (o *V1TokensListParams) SetSymbol(symbol *string) { + o.Symbol = symbol +} + +// WriteToRequest writes these params to a swagger request +func (o *V1TokensListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Address != nil { + + // query param address + var qrAddress string + + if o.Address != nil { + qrAddress = *o.Address + } + qAddress := qrAddress + if qAddress != "" { + + if err := r.SetQueryParam("address", qAddress); err != nil { + return err + } + } + } + + if o.Decimals != nil { + + // query param decimals + var qrDecimals string + + if o.Decimals != nil { + qrDecimals = *o.Decimals + } + qDecimals := qrDecimals + if qDecimals != "" { + + if err := r.SetQueryParam("decimals", qDecimals); err != nil { + return err + } + } + } + + if o.DecimalsGt != nil { + + // query param decimals__gt + var qrDecimalsGt string + + if o.DecimalsGt != nil { + qrDecimalsGt = *o.DecimalsGt + } + qDecimalsGt := qrDecimalsGt + if qDecimalsGt != "" { + + if err := r.SetQueryParam("decimals__gt", qDecimalsGt); err != nil { + return err + } + } + } + + if o.DecimalsLt != nil { + + // query param decimals__lt + var qrDecimalsLt string + + if o.DecimalsLt != nil { + qrDecimalsLt = *o.DecimalsLt + } + qDecimalsLt := qrDecimalsLt + if qDecimalsLt != "" { + + if err := r.SetQueryParam("decimals__lt", qDecimalsLt); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Ordering != nil { + + // query param ordering + var qrOrdering string + + if o.Ordering != nil { + qrOrdering = *o.Ordering + } + qOrdering := qrOrdering + if qOrdering != "" { + + if err := r.SetQueryParam("ordering", qOrdering); err != nil { + return err + } + } + } + + if o.Search != nil { + + // query param search + var qrSearch string + + if o.Search != nil { + qrSearch = *o.Search + } + qSearch := qrSearch + if qSearch != "" { + + if err := r.SetQueryParam("search", qSearch); err != nil { + return err + } + } + } + + if o.Symbol != nil { + + // query param symbol + var qrSymbol string + + if o.Symbol != nil { + qrSymbol = *o.Symbol + } + qSymbol := qrSymbol + if qSymbol != "" { + + if err := r.SetQueryParam("symbol", qSymbol); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/tokens/v1_tokens_list_responses.go b/utils/safe_api/client/tokens/v1_tokens_list_responses.go new file mode 100644 index 0000000..5d42471 --- /dev/null +++ b/utils/safe_api/client/tokens/v1_tokens_list_responses.go @@ -0,0 +1,277 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package tokens + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + models "omni-balance/utils/safe_api" +) + +// V1TokensListReader is a Reader for the V1TokensList structure. +type V1TokensListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1TokensListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1TokensListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[GET /v1/tokens/] v1_tokens_list", response, response.Code()) + } +} + +// NewV1TokensListOK creates a V1TokensListOK with default headers values +func NewV1TokensListOK() *V1TokensListOK { + return &V1TokensListOK{} +} + +/* +V1TokensListOK describes a response with status code 200, with default header values. + +V1TokensListOK v1 tokens list o k +*/ +type V1TokensListOK struct { + Payload *V1TokensListOKBody +} + +// IsSuccess returns true when this v1 tokens list o k response has a 2xx status code +func (o *V1TokensListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 tokens list o k response has a 3xx status code +func (o *V1TokensListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 tokens list o k response has a 4xx status code +func (o *V1TokensListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 tokens list o k response has a 5xx status code +func (o *V1TokensListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 tokens list o k response a status code equal to that given +func (o *V1TokensListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 tokens list o k response +func (o *V1TokensListOK) Code() int { + return 200 +} + +func (o *V1TokensListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/tokens/][%d] v1TokensListOK %s", 200, payload) +} + +func (o *V1TokensListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/tokens/][%d] v1TokensListOK %s", 200, payload) +} + +func (o *V1TokensListOK) GetPayload() *V1TokensListOKBody { + return o.Payload +} + +func (o *V1TokensListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(V1TokensListOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +V1TokensListOKBody v1 tokens list o k body +swagger:model V1TokensListOKBody +*/ +type V1TokensListOKBody struct { + + // count + // Required: true + Count *int64 `json:"count"` + + // next + // Format: uri + Next *strfmt.URI `json:"next,omitempty"` + + // previous + // Format: uri + Previous *strfmt.URI `json:"previous,omitempty"` + + // results + // Required: true + Results []*models.TokenInfoResponse `json:"results"` +} + +// Validate validates this v1 tokens list o k body +func (o *V1TokensListOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateCount(formats); err != nil { + res = append(res, err) + } + + if err := o.validateNext(formats); err != nil { + res = append(res, err) + } + + if err := o.validatePrevious(formats); err != nil { + res = append(res, err) + } + + if err := o.validateResults(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V1TokensListOKBody) validateCount(formats strfmt.Registry) error { + + if err := validate.Required("v1TokensListOK"+"."+"count", "body", o.Count); err != nil { + return err + } + + return nil +} + +func (o *V1TokensListOKBody) validateNext(formats strfmt.Registry) error { + if swag.IsZero(o.Next) { // not required + return nil + } + + if err := validate.FormatOf("v1TokensListOK"+"."+"next", "body", "uri", o.Next.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V1TokensListOKBody) validatePrevious(formats strfmt.Registry) error { + if swag.IsZero(o.Previous) { // not required + return nil + } + + if err := validate.FormatOf("v1TokensListOK"+"."+"previous", "body", "uri", o.Previous.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V1TokensListOKBody) validateResults(formats strfmt.Registry) error { + + if err := validate.Required("v1TokensListOK"+"."+"results", "body", o.Results); err != nil { + return err + } + + for i := 0; i < len(o.Results); i++ { + if swag.IsZero(o.Results[i]) { // not required + continue + } + + if o.Results[i] != nil { + if err := o.Results[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v1TokensListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v1TokensListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this v1 tokens list o k body based on the context it is used +func (o *V1TokensListOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResults(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V1TokensListOKBody) contextValidateResults(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Results); i++ { + + if o.Results[i] != nil { + + if swag.IsZero(o.Results[i]) { // not required + return nil + } + + if err := o.Results[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v1TokensListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v1TokensListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *V1TokensListOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *V1TokensListOKBody) UnmarshalBinary(b []byte) error { + var res V1TokensListOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/utils/safe_api/client/tokens/v1_tokens_read_parameters.go b/utils/safe_api/client/tokens/v1_tokens_read_parameters.go new file mode 100644 index 0000000..cf553ac --- /dev/null +++ b/utils/safe_api/client/tokens/v1_tokens_read_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package tokens + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1TokensReadParams creates a new V1TokensReadParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1TokensReadParams() *V1TokensReadParams { + return &V1TokensReadParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1TokensReadParamsWithTimeout creates a new V1TokensReadParams object +// with the ability to set a timeout on a request. +func NewV1TokensReadParamsWithTimeout(timeout time.Duration) *V1TokensReadParams { + return &V1TokensReadParams{ + timeout: timeout, + } +} + +// NewV1TokensReadParamsWithContext creates a new V1TokensReadParams object +// with the ability to set a context for a request. +func NewV1TokensReadParamsWithContext(ctx context.Context) *V1TokensReadParams { + return &V1TokensReadParams{ + Context: ctx, + } +} + +// NewV1TokensReadParamsWithHTTPClient creates a new V1TokensReadParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1TokensReadParamsWithHTTPClient(client *http.Client) *V1TokensReadParams { + return &V1TokensReadParams{ + HTTPClient: client, + } +} + +/* +V1TokensReadParams contains all the parameters to send to the API endpoint + + for the v1 tokens read operation. + + Typically these are written to a http.Request. +*/ +type V1TokensReadParams struct { + + /* Address. + + A unique value identifying this token. + */ + Address string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 tokens read params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1TokensReadParams) WithDefaults() *V1TokensReadParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 tokens read params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1TokensReadParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 tokens read params +func (o *V1TokensReadParams) WithTimeout(timeout time.Duration) *V1TokensReadParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 tokens read params +func (o *V1TokensReadParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 tokens read params +func (o *V1TokensReadParams) WithContext(ctx context.Context) *V1TokensReadParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 tokens read params +func (o *V1TokensReadParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 tokens read params +func (o *V1TokensReadParams) WithHTTPClient(client *http.Client) *V1TokensReadParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 tokens read params +func (o *V1TokensReadParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 tokens read params +func (o *V1TokensReadParams) WithAddress(address string) *V1TokensReadParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 tokens read params +func (o *V1TokensReadParams) SetAddress(address string) { + o.Address = address +} + +// WriteToRequest writes these params to a swagger request +func (o *V1TokensReadParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/tokens/v1_tokens_read_responses.go b/utils/safe_api/client/tokens/v1_tokens_read_responses.go new file mode 100644 index 0000000..fe9a511 --- /dev/null +++ b/utils/safe_api/client/tokens/v1_tokens_read_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package tokens + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1TokensReadReader is a Reader for the V1TokensRead structure. +type V1TokensReadReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1TokensReadReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1TokensReadOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[GET /v1/tokens/{address}/] v1_tokens_read", response, response.Code()) + } +} + +// NewV1TokensReadOK creates a V1TokensReadOK with default headers values +func NewV1TokensReadOK() *V1TokensReadOK { + return &V1TokensReadOK{} +} + +/* +V1TokensReadOK describes a response with status code 200, with default header values. + +V1TokensReadOK v1 tokens read o k +*/ +type V1TokensReadOK struct { + Payload *models.TokenInfoResponse +} + +// IsSuccess returns true when this v1 tokens read o k response has a 2xx status code +func (o *V1TokensReadOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 tokens read o k response has a 3xx status code +func (o *V1TokensReadOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 tokens read o k response has a 4xx status code +func (o *V1TokensReadOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 tokens read o k response has a 5xx status code +func (o *V1TokensReadOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 tokens read o k response a status code equal to that given +func (o *V1TokensReadOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 tokens read o k response +func (o *V1TokensReadOK) Code() int { + return 200 +} + +func (o *V1TokensReadOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/tokens/{address}/][%d] v1TokensReadOK %s", 200, payload) +} + +func (o *V1TokensReadOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/tokens/{address}/][%d] v1TokensReadOK %s", 200, payload) +} + +func (o *V1TokensReadOK) GetPayload() *models.TokenInfoResponse { + return o.Payload +} + +func (o *V1TokensReadOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.TokenInfoResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/utils/safe_api/client/transactions/transactions_client.go b/utils/safe_api/client/transactions/transactions_client.go new file mode 100644 index 0000000..31c957a --- /dev/null +++ b/utils/safe_api/client/transactions/transactions_client.go @@ -0,0 +1,599 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "github.com/pkg/errors" + + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// New creates a new transactions API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +// New creates a new transactions API client with basic auth credentials. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - user: user for basic authentication header. +// - password: password for basic authentication header. +func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BasicAuth(user, password) + return &Client{transport: transport, formats: strfmt.Default} +} + +// New creates a new transactions API client with a bearer token for authentication. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - bearerToken: bearer token for Bearer authentication header. +func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) + return &Client{transport: transport, formats: strfmt.Default} +} + +/* +Client for transactions API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption may be used to customize the behavior of Client methods. +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + V1ModuleTransactionRead(params *V1ModuleTransactionReadParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1ModuleTransactionReadOK, error) + + V1MultisigTransactionsConfirmationsCreate(params *V1MultisigTransactionsConfirmationsCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1MultisigTransactionsConfirmationsCreateCreated, error) + + V1MultisigTransactionsConfirmationsList(params *V1MultisigTransactionsConfirmationsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1MultisigTransactionsConfirmationsListOK, error) + + V1MultisigTransactionsDelete(params *V1MultisigTransactionsDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1MultisigTransactionsDeleteNoContent, error) + + V1MultisigTransactionsRead(params *V1MultisigTransactionsReadParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1MultisigTransactionsReadOK, error) + + V1SafesAllTransactionsList(params *V1SafesAllTransactionsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesAllTransactionsListOK, error) + + V1SafesIncomingTransfersList(params *V1SafesIncomingTransfersListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesIncomingTransfersListOK, error) + + V1SafesModuleTransactionsList(params *V1SafesModuleTransactionsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesModuleTransactionsListOK, error) + + V1SafesMultisigTransactionsCreate(params *V1SafesMultisigTransactionsCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesMultisigTransactionsCreateCreated, error) + + V1SafesMultisigTransactionsEstimationsCreate(params *V1SafesMultisigTransactionsEstimationsCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesMultisigTransactionsEstimationsCreateOK, error) + + V1SafesMultisigTransactionsList(params *V1SafesMultisigTransactionsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesMultisigTransactionsListOK, error) + + V1SafesTransfersList(params *V1SafesTransfersListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesTransfersListOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +V1ModuleTransactionRead :return: module transaction filtered by module_transaction_id +*/ +func (a *Client) V1ModuleTransactionRead(params *V1ModuleTransactionReadParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1ModuleTransactionReadOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1ModuleTransactionReadParams() + } + op := &runtime.ClientOperation{ + ID: "v1_module-transaction_read", + Method: "GET", + PathPattern: "/v1/module-transaction/{module_transaction_id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1ModuleTransactionReadReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1ModuleTransactionReadOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_module-transaction_read: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* + V1MultisigTransactionsConfirmationsCreate Add a confirmation for a transaction. More than one signature can be used. This endpoint does not support + +the use of delegates to make a transaction trusted. +*/ +func (a *Client) V1MultisigTransactionsConfirmationsCreate(params *V1MultisigTransactionsConfirmationsCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1MultisigTransactionsConfirmationsCreateCreated, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1MultisigTransactionsConfirmationsCreateParams() + } + op := &runtime.ClientOperation{ + ID: "v1_multisig-transactions_confirmations_create", + Method: "POST", + PathPattern: "/v1/multisig-transactions/{safe_tx_hash}/confirmations/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1MultisigTransactionsConfirmationsCreateReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1MultisigTransactionsConfirmationsCreateCreated) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_multisig-transactions_confirmations_create: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1MultisigTransactionsConfirmationsList Get the list of confirmations for a multisig transaction +*/ +func (a *Client) V1MultisigTransactionsConfirmationsList(params *V1MultisigTransactionsConfirmationsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1MultisigTransactionsConfirmationsListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1MultisigTransactionsConfirmationsListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_multisig-transactions_confirmations_list", + Method: "GET", + PathPattern: "/v1/multisig-transactions/{safe_tx_hash}/confirmations/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1MultisigTransactionsConfirmationsListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1MultisigTransactionsConfirmationsListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_multisig-transactions_confirmations_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* + V1MultisigTransactionsDelete Delete a queued but not executed multisig transaction. Only the proposer can delete the transaction. + +Delegates are not valid, if the transaction was proposed by a delegator the owner who delegated to +the delegate must be used. +An EOA is required to sign the following EIP712 data: + +```python + + { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"}, + ], + "DeleteRequest": [ + {"name": "safeTxHash", "type": "bytes32"}, + {"name": "totp", "type": "uint256"}, + ], + }, + "primaryType": "DeleteRequest", + "domain": { + "name": "Safe Transaction Service", + "version": "1.0", + "chainId": chain_id, + "verifyingContract": safe_address, + }, + "message": { + "safeTxHash": safe_tx_hash, + "totp": totp, + }, + } + +``` + +`totp` parameter is calculated with `T0=0` and `Tx=3600`. `totp` is calculated by taking the +Unix UTC epoch time (no milliseconds) and dividing by 3600 (natural division, no decimals) +*/ +func (a *Client) V1MultisigTransactionsDelete(params *V1MultisigTransactionsDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1MultisigTransactionsDeleteNoContent, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1MultisigTransactionsDeleteParams() + } + op := &runtime.ClientOperation{ + ID: "v1_multisig-transactions_delete", + Method: "DELETE", + PathPattern: "/v1/multisig-transactions/{safe_tx_hash}/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1MultisigTransactionsDeleteReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1MultisigTransactionsDeleteNoContent) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_multisig-transactions_delete: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1MultisigTransactionsRead v1 multisig transactions read API +*/ +func (a *Client) V1MultisigTransactionsRead(params *V1MultisigTransactionsReadParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1MultisigTransactionsReadOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1MultisigTransactionsReadParams() + } + op := &runtime.ClientOperation{ + ID: "v1_multisig-transactions_read", + Method: "GET", + PathPattern: "/v1/multisig-transactions/{safe_tx_hash}/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1MultisigTransactionsReadReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1MultisigTransactionsReadOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_multisig-transactions_read: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1SafesAllTransactionsList v1 safes all transactions list API +*/ +func (a *Client) V1SafesAllTransactionsList(params *V1SafesAllTransactionsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesAllTransactionsListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SafesAllTransactionsListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_safes_all-transactions_list", + Method: "GET", + PathPattern: "/v1/safes/{address}/all-transactions/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1SafesAllTransactionsListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SafesAllTransactionsListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_safes_all-transactions_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1SafesIncomingTransfersList v1 safes incoming transfers list API +*/ +func (a *Client) V1SafesIncomingTransfersList(params *V1SafesIncomingTransfersListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesIncomingTransfersListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SafesIncomingTransfersListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_safes_incoming-transfers_list", + Method: "GET", + PathPattern: "/v1/safes/{address}/incoming-transfers/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1SafesIncomingTransfersListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SafesIncomingTransfersListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_safes_incoming-transfers_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1SafesModuleTransactionsList Returns the module transaction of a Safe +*/ +func (a *Client) V1SafesModuleTransactionsList(params *V1SafesModuleTransactionsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesModuleTransactionsListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SafesModuleTransactionsListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_safes_module-transactions_list", + Method: "GET", + PathPattern: "/v1/safes/{address}/module-transactions/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1SafesModuleTransactionsListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SafesModuleTransactionsListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_safes_module-transactions_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1SafesMultisigTransactionsCreate Creates a Multisig Transaction with its confirmations and retrieves all the information related. +*/ +func (a *Client) V1SafesMultisigTransactionsCreate(params *V1SafesMultisigTransactionsCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesMultisigTransactionsCreateCreated, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SafesMultisigTransactionsCreateParams() + } + op := &runtime.ClientOperation{ + ID: "v1_safes_multisig-transactions_create", + Method: "POST", + PathPattern: "/v1/safes/{address}/multisig-transactions/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1SafesMultisigTransactionsCreateReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SafesMultisigTransactionsCreateCreated) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_safes_multisig-transactions_create: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1SafesMultisigTransactionsEstimationsCreate Estimates `safeTxGas` for a Safe Multisig Transaction. +*/ +func (a *Client) V1SafesMultisigTransactionsEstimationsCreate(params *V1SafesMultisigTransactionsEstimationsCreateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesMultisigTransactionsEstimationsCreateOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SafesMultisigTransactionsEstimationsCreateParams() + } + op := &runtime.ClientOperation{ + ID: "v1_safes_multisig-transactions_estimations_create", + Method: "POST", + PathPattern: "/v1/safes/{address}/multisig-transactions/estimations/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1SafesMultisigTransactionsEstimationsCreateReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, errors.Wrap(err, "unable to submit request") + } + success, ok := result.(*V1SafesMultisigTransactionsEstimationsCreateOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_safes_multisig-transactions_estimations_create: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* + V1SafesMultisigTransactionsList Returns a paginated list of Multisig Transactions for a Safe. + +By default only “trusted“ multisig transactions are returned. +*/ +func (a *Client) V1SafesMultisigTransactionsList(params *V1SafesMultisigTransactionsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesMultisigTransactionsListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SafesMultisigTransactionsListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_safes_multisig-transactions_list", + Method: "GET", + PathPattern: "/v1/safes/{address}/multisig-transactions/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1SafesMultisigTransactionsListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SafesMultisigTransactionsListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_safes_multisig-transactions_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +V1SafesTransfersList v1 safes transfers list API +*/ +func (a *Client) V1SafesTransfersList(params *V1SafesTransfersListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1SafesTransfersListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1SafesTransfersListParams() + } + op := &runtime.ClientOperation{ + ID: "v1_safes_transfers_list", + Method: "GET", + PathPattern: "/v1/safes/{address}/transfers/", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1SafesTransfersListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1SafesTransfersListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_safes_transfers_list: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/utils/safe_api/client/transactions/v1_module_transaction_read_parameters.go b/utils/safe_api/client/transactions/v1_module_transaction_read_parameters.go new file mode 100644 index 0000000..f47634c --- /dev/null +++ b/utils/safe_api/client/transactions/v1_module_transaction_read_parameters.go @@ -0,0 +1,148 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1ModuleTransactionReadParams creates a new V1ModuleTransactionReadParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1ModuleTransactionReadParams() *V1ModuleTransactionReadParams { + return &V1ModuleTransactionReadParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1ModuleTransactionReadParamsWithTimeout creates a new V1ModuleTransactionReadParams object +// with the ability to set a timeout on a request. +func NewV1ModuleTransactionReadParamsWithTimeout(timeout time.Duration) *V1ModuleTransactionReadParams { + return &V1ModuleTransactionReadParams{ + timeout: timeout, + } +} + +// NewV1ModuleTransactionReadParamsWithContext creates a new V1ModuleTransactionReadParams object +// with the ability to set a context for a request. +func NewV1ModuleTransactionReadParamsWithContext(ctx context.Context) *V1ModuleTransactionReadParams { + return &V1ModuleTransactionReadParams{ + Context: ctx, + } +} + +// NewV1ModuleTransactionReadParamsWithHTTPClient creates a new V1ModuleTransactionReadParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1ModuleTransactionReadParamsWithHTTPClient(client *http.Client) *V1ModuleTransactionReadParams { + return &V1ModuleTransactionReadParams{ + HTTPClient: client, + } +} + +/* +V1ModuleTransactionReadParams contains all the parameters to send to the API endpoint + + for the v1 module transaction read operation. + + Typically these are written to a http.Request. +*/ +type V1ModuleTransactionReadParams struct { + + // ModuleTransactionID. + ModuleTransactionID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 module transaction read params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1ModuleTransactionReadParams) WithDefaults() *V1ModuleTransactionReadParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 module transaction read params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1ModuleTransactionReadParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 module transaction read params +func (o *V1ModuleTransactionReadParams) WithTimeout(timeout time.Duration) *V1ModuleTransactionReadParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 module transaction read params +func (o *V1ModuleTransactionReadParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 module transaction read params +func (o *V1ModuleTransactionReadParams) WithContext(ctx context.Context) *V1ModuleTransactionReadParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 module transaction read params +func (o *V1ModuleTransactionReadParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 module transaction read params +func (o *V1ModuleTransactionReadParams) WithHTTPClient(client *http.Client) *V1ModuleTransactionReadParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 module transaction read params +func (o *V1ModuleTransactionReadParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithModuleTransactionID adds the moduleTransactionID to the v1 module transaction read params +func (o *V1ModuleTransactionReadParams) WithModuleTransactionID(moduleTransactionID string) *V1ModuleTransactionReadParams { + o.SetModuleTransactionID(moduleTransactionID) + return o +} + +// SetModuleTransactionID adds the moduleTransactionId to the v1 module transaction read params +func (o *V1ModuleTransactionReadParams) SetModuleTransactionID(moduleTransactionID string) { + o.ModuleTransactionID = moduleTransactionID +} + +// WriteToRequest writes these params to a swagger request +func (o *V1ModuleTransactionReadParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param module_transaction_id + if err := r.SetPathParam("module_transaction_id", o.ModuleTransactionID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/transactions/v1_module_transaction_read_responses.go b/utils/safe_api/client/transactions/v1_module_transaction_read_responses.go new file mode 100644 index 0000000..c24b213 --- /dev/null +++ b/utils/safe_api/client/transactions/v1_module_transaction_read_responses.go @@ -0,0 +1,230 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1ModuleTransactionReadReader is a Reader for the V1ModuleTransactionRead structure. +type V1ModuleTransactionReadReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1ModuleTransactionReadReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1ModuleTransactionReadOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1ModuleTransactionReadBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewV1ModuleTransactionReadNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/module-transaction/{module_transaction_id}] v1_module-transaction_read", response, response.Code()) + } +} + +// NewV1ModuleTransactionReadOK creates a V1ModuleTransactionReadOK with default headers values +func NewV1ModuleTransactionReadOK() *V1ModuleTransactionReadOK { + return &V1ModuleTransactionReadOK{} +} + +/* +V1ModuleTransactionReadOK describes a response with status code 200, with default header values. + +V1ModuleTransactionReadOK v1 module transaction read o k +*/ +type V1ModuleTransactionReadOK struct { + Payload *models.SafeModuleTransactionResponse +} + +// IsSuccess returns true when this v1 module transaction read o k response has a 2xx status code +func (o *V1ModuleTransactionReadOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 module transaction read o k response has a 3xx status code +func (o *V1ModuleTransactionReadOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 module transaction read o k response has a 4xx status code +func (o *V1ModuleTransactionReadOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 module transaction read o k response has a 5xx status code +func (o *V1ModuleTransactionReadOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 module transaction read o k response a status code equal to that given +func (o *V1ModuleTransactionReadOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 module transaction read o k response +func (o *V1ModuleTransactionReadOK) Code() int { + return 200 +} + +func (o *V1ModuleTransactionReadOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/module-transaction/{module_transaction_id}][%d] v1ModuleTransactionReadOK %s", 200, payload) +} + +func (o *V1ModuleTransactionReadOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/module-transaction/{module_transaction_id}][%d] v1ModuleTransactionReadOK %s", 200, payload) +} + +func (o *V1ModuleTransactionReadOK) GetPayload() *models.SafeModuleTransactionResponse { + return o.Payload +} + +func (o *V1ModuleTransactionReadOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.SafeModuleTransactionResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1ModuleTransactionReadBadRequest creates a V1ModuleTransactionReadBadRequest with default headers values +func NewV1ModuleTransactionReadBadRequest() *V1ModuleTransactionReadBadRequest { + return &V1ModuleTransactionReadBadRequest{} +} + +/* +V1ModuleTransactionReadBadRequest describes a response with status code 400, with default header values. + +Invalid moduleTransactionId +*/ +type V1ModuleTransactionReadBadRequest struct { +} + +// IsSuccess returns true when this v1 module transaction read bad request response has a 2xx status code +func (o *V1ModuleTransactionReadBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 module transaction read bad request response has a 3xx status code +func (o *V1ModuleTransactionReadBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 module transaction read bad request response has a 4xx status code +func (o *V1ModuleTransactionReadBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 module transaction read bad request response has a 5xx status code +func (o *V1ModuleTransactionReadBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 module transaction read bad request response a status code equal to that given +func (o *V1ModuleTransactionReadBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 module transaction read bad request response +func (o *V1ModuleTransactionReadBadRequest) Code() int { + return 400 +} + +func (o *V1ModuleTransactionReadBadRequest) Error() string { + return fmt.Sprintf("[GET /v1/module-transaction/{module_transaction_id}][%d] v1ModuleTransactionReadBadRequest", 400) +} + +func (o *V1ModuleTransactionReadBadRequest) String() string { + return fmt.Sprintf("[GET /v1/module-transaction/{module_transaction_id}][%d] v1ModuleTransactionReadBadRequest", 400) +} + +func (o *V1ModuleTransactionReadBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1ModuleTransactionReadNotFound creates a V1ModuleTransactionReadNotFound with default headers values +func NewV1ModuleTransactionReadNotFound() *V1ModuleTransactionReadNotFound { + return &V1ModuleTransactionReadNotFound{} +} + +/* +V1ModuleTransactionReadNotFound describes a response with status code 404, with default header values. + +ModuleTransaction does not exist +*/ +type V1ModuleTransactionReadNotFound struct { +} + +// IsSuccess returns true when this v1 module transaction read not found response has a 2xx status code +func (o *V1ModuleTransactionReadNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 module transaction read not found response has a 3xx status code +func (o *V1ModuleTransactionReadNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 module transaction read not found response has a 4xx status code +func (o *V1ModuleTransactionReadNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 module transaction read not found response has a 5xx status code +func (o *V1ModuleTransactionReadNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 module transaction read not found response a status code equal to that given +func (o *V1ModuleTransactionReadNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 module transaction read not found response +func (o *V1ModuleTransactionReadNotFound) Code() int { + return 404 +} + +func (o *V1ModuleTransactionReadNotFound) Error() string { + return fmt.Sprintf("[GET /v1/module-transaction/{module_transaction_id}][%d] v1ModuleTransactionReadNotFound", 404) +} + +func (o *V1ModuleTransactionReadNotFound) String() string { + return fmt.Sprintf("[GET /v1/module-transaction/{module_transaction_id}][%d] v1ModuleTransactionReadNotFound", 404) +} + +func (o *V1ModuleTransactionReadNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/transactions/v1_multisig_transactions_confirmations_create_parameters.go b/utils/safe_api/client/transactions/v1_multisig_transactions_confirmations_create_parameters.go new file mode 100644 index 0000000..d52e370 --- /dev/null +++ b/utils/safe_api/client/transactions/v1_multisig_transactions_confirmations_create_parameters.go @@ -0,0 +1,169 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// NewV1MultisigTransactionsConfirmationsCreateParams creates a new V1MultisigTransactionsConfirmationsCreateParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1MultisigTransactionsConfirmationsCreateParams() *V1MultisigTransactionsConfirmationsCreateParams { + return &V1MultisigTransactionsConfirmationsCreateParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1MultisigTransactionsConfirmationsCreateParamsWithTimeout creates a new V1MultisigTransactionsConfirmationsCreateParams object +// with the ability to set a timeout on a request. +func NewV1MultisigTransactionsConfirmationsCreateParamsWithTimeout(timeout time.Duration) *V1MultisigTransactionsConfirmationsCreateParams { + return &V1MultisigTransactionsConfirmationsCreateParams{ + timeout: timeout, + } +} + +// NewV1MultisigTransactionsConfirmationsCreateParamsWithContext creates a new V1MultisigTransactionsConfirmationsCreateParams object +// with the ability to set a context for a request. +func NewV1MultisigTransactionsConfirmationsCreateParamsWithContext(ctx context.Context) *V1MultisigTransactionsConfirmationsCreateParams { + return &V1MultisigTransactionsConfirmationsCreateParams{ + Context: ctx, + } +} + +// NewV1MultisigTransactionsConfirmationsCreateParamsWithHTTPClient creates a new V1MultisigTransactionsConfirmationsCreateParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1MultisigTransactionsConfirmationsCreateParamsWithHTTPClient(client *http.Client) *V1MultisigTransactionsConfirmationsCreateParams { + return &V1MultisigTransactionsConfirmationsCreateParams{ + HTTPClient: client, + } +} + +/* +V1MultisigTransactionsConfirmationsCreateParams contains all the parameters to send to the API endpoint + + for the v1 multisig transactions confirmations create operation. + + Typically these are written to a http.Request. +*/ +type V1MultisigTransactionsConfirmationsCreateParams struct { + + // Data. + Data *models.SafeMultisigConfirmation + + // SafeTxHash. + SafeTxHash string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 multisig transactions confirmations create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1MultisigTransactionsConfirmationsCreateParams) WithDefaults() *V1MultisigTransactionsConfirmationsCreateParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 multisig transactions confirmations create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1MultisigTransactionsConfirmationsCreateParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 multisig transactions confirmations create params +func (o *V1MultisigTransactionsConfirmationsCreateParams) WithTimeout(timeout time.Duration) *V1MultisigTransactionsConfirmationsCreateParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 multisig transactions confirmations create params +func (o *V1MultisigTransactionsConfirmationsCreateParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 multisig transactions confirmations create params +func (o *V1MultisigTransactionsConfirmationsCreateParams) WithContext(ctx context.Context) *V1MultisigTransactionsConfirmationsCreateParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 multisig transactions confirmations create params +func (o *V1MultisigTransactionsConfirmationsCreateParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 multisig transactions confirmations create params +func (o *V1MultisigTransactionsConfirmationsCreateParams) WithHTTPClient(client *http.Client) *V1MultisigTransactionsConfirmationsCreateParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 multisig transactions confirmations create params +func (o *V1MultisigTransactionsConfirmationsCreateParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the v1 multisig transactions confirmations create params +func (o *V1MultisigTransactionsConfirmationsCreateParams) WithData(data *models.SafeMultisigConfirmation) *V1MultisigTransactionsConfirmationsCreateParams { + o.SetData(data) + return o +} + +// SetData adds the data to the v1 multisig transactions confirmations create params +func (o *V1MultisigTransactionsConfirmationsCreateParams) SetData(data *models.SafeMultisigConfirmation) { + o.Data = data +} + +// WithSafeTxHash adds the safeTxHash to the v1 multisig transactions confirmations create params +func (o *V1MultisigTransactionsConfirmationsCreateParams) WithSafeTxHash(safeTxHash string) *V1MultisigTransactionsConfirmationsCreateParams { + o.SetSafeTxHash(safeTxHash) + return o +} + +// SetSafeTxHash adds the safeTxHash to the v1 multisig transactions confirmations create params +func (o *V1MultisigTransactionsConfirmationsCreateParams) SetSafeTxHash(safeTxHash string) { + o.SafeTxHash = safeTxHash +} + +// WriteToRequest writes these params to a swagger request +func (o *V1MultisigTransactionsConfirmationsCreateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + // path param safe_tx_hash + if err := r.SetPathParam("safe_tx_hash", o.SafeTxHash); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/transactions/v1_multisig_transactions_confirmations_create_responses.go b/utils/safe_api/client/transactions/v1_multisig_transactions_confirmations_create_responses.go new file mode 100644 index 0000000..e54f6eb --- /dev/null +++ b/utils/safe_api/client/transactions/v1_multisig_transactions_confirmations_create_responses.go @@ -0,0 +1,212 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// V1MultisigTransactionsConfirmationsCreateReader is a Reader for the V1MultisigTransactionsConfirmationsCreate structure. +type V1MultisigTransactionsConfirmationsCreateReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1MultisigTransactionsConfirmationsCreateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 201: + result := NewV1MultisigTransactionsConfirmationsCreateCreated() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1MultisigTransactionsConfirmationsCreateBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 422: + result := NewV1MultisigTransactionsConfirmationsCreateUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /v1/multisig-transactions/{safe_tx_hash}/confirmations/] v1_multisig-transactions_confirmations_create", response, response.Code()) + } +} + +// NewV1MultisigTransactionsConfirmationsCreateCreated creates a V1MultisigTransactionsConfirmationsCreateCreated with default headers values +func NewV1MultisigTransactionsConfirmationsCreateCreated() *V1MultisigTransactionsConfirmationsCreateCreated { + return &V1MultisigTransactionsConfirmationsCreateCreated{} +} + +/* +V1MultisigTransactionsConfirmationsCreateCreated describes a response with status code 201, with default header values. + +Created +*/ +type V1MultisigTransactionsConfirmationsCreateCreated struct { +} + +// IsSuccess returns true when this v1 multisig transactions confirmations create created response has a 2xx status code +func (o *V1MultisigTransactionsConfirmationsCreateCreated) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 multisig transactions confirmations create created response has a 3xx status code +func (o *V1MultisigTransactionsConfirmationsCreateCreated) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 multisig transactions confirmations create created response has a 4xx status code +func (o *V1MultisigTransactionsConfirmationsCreateCreated) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 multisig transactions confirmations create created response has a 5xx status code +func (o *V1MultisigTransactionsConfirmationsCreateCreated) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 multisig transactions confirmations create created response a status code equal to that given +func (o *V1MultisigTransactionsConfirmationsCreateCreated) IsCode(code int) bool { + return code == 201 +} + +// Code gets the status code for the v1 multisig transactions confirmations create created response +func (o *V1MultisigTransactionsConfirmationsCreateCreated) Code() int { + return 201 +} + +func (o *V1MultisigTransactionsConfirmationsCreateCreated) Error() string { + return fmt.Sprintf("[POST /v1/multisig-transactions/{safe_tx_hash}/confirmations/][%d] v1MultisigTransactionsConfirmationsCreateCreated", 201) +} + +func (o *V1MultisigTransactionsConfirmationsCreateCreated) String() string { + return fmt.Sprintf("[POST /v1/multisig-transactions/{safe_tx_hash}/confirmations/][%d] v1MultisigTransactionsConfirmationsCreateCreated", 201) +} + +func (o *V1MultisigTransactionsConfirmationsCreateCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1MultisigTransactionsConfirmationsCreateBadRequest creates a V1MultisigTransactionsConfirmationsCreateBadRequest with default headers values +func NewV1MultisigTransactionsConfirmationsCreateBadRequest() *V1MultisigTransactionsConfirmationsCreateBadRequest { + return &V1MultisigTransactionsConfirmationsCreateBadRequest{} +} + +/* +V1MultisigTransactionsConfirmationsCreateBadRequest describes a response with status code 400, with default header values. + +Malformed data +*/ +type V1MultisigTransactionsConfirmationsCreateBadRequest struct { +} + +// IsSuccess returns true when this v1 multisig transactions confirmations create bad request response has a 2xx status code +func (o *V1MultisigTransactionsConfirmationsCreateBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 multisig transactions confirmations create bad request response has a 3xx status code +func (o *V1MultisigTransactionsConfirmationsCreateBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 multisig transactions confirmations create bad request response has a 4xx status code +func (o *V1MultisigTransactionsConfirmationsCreateBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 multisig transactions confirmations create bad request response has a 5xx status code +func (o *V1MultisigTransactionsConfirmationsCreateBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 multisig transactions confirmations create bad request response a status code equal to that given +func (o *V1MultisigTransactionsConfirmationsCreateBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 multisig transactions confirmations create bad request response +func (o *V1MultisigTransactionsConfirmationsCreateBadRequest) Code() int { + return 400 +} + +func (o *V1MultisigTransactionsConfirmationsCreateBadRequest) Error() string { + return fmt.Sprintf("[POST /v1/multisig-transactions/{safe_tx_hash}/confirmations/][%d] v1MultisigTransactionsConfirmationsCreateBadRequest", 400) +} + +func (o *V1MultisigTransactionsConfirmationsCreateBadRequest) String() string { + return fmt.Sprintf("[POST /v1/multisig-transactions/{safe_tx_hash}/confirmations/][%d] v1MultisigTransactionsConfirmationsCreateBadRequest", 400) +} + +func (o *V1MultisigTransactionsConfirmationsCreateBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1MultisigTransactionsConfirmationsCreateUnprocessableEntity creates a V1MultisigTransactionsConfirmationsCreateUnprocessableEntity with default headers values +func NewV1MultisigTransactionsConfirmationsCreateUnprocessableEntity() *V1MultisigTransactionsConfirmationsCreateUnprocessableEntity { + return &V1MultisigTransactionsConfirmationsCreateUnprocessableEntity{} +} + +/* +V1MultisigTransactionsConfirmationsCreateUnprocessableEntity describes a response with status code 422, with default header values. + +Error processing data +*/ +type V1MultisigTransactionsConfirmationsCreateUnprocessableEntity struct { +} + +// IsSuccess returns true when this v1 multisig transactions confirmations create unprocessable entity response has a 2xx status code +func (o *V1MultisigTransactionsConfirmationsCreateUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 multisig transactions confirmations create unprocessable entity response has a 3xx status code +func (o *V1MultisigTransactionsConfirmationsCreateUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 multisig transactions confirmations create unprocessable entity response has a 4xx status code +func (o *V1MultisigTransactionsConfirmationsCreateUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 multisig transactions confirmations create unprocessable entity response has a 5xx status code +func (o *V1MultisigTransactionsConfirmationsCreateUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 multisig transactions confirmations create unprocessable entity response a status code equal to that given +func (o *V1MultisigTransactionsConfirmationsCreateUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 multisig transactions confirmations create unprocessable entity response +func (o *V1MultisigTransactionsConfirmationsCreateUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1MultisigTransactionsConfirmationsCreateUnprocessableEntity) Error() string { + return fmt.Sprintf("[POST /v1/multisig-transactions/{safe_tx_hash}/confirmations/][%d] v1MultisigTransactionsConfirmationsCreateUnprocessableEntity", 422) +} + +func (o *V1MultisigTransactionsConfirmationsCreateUnprocessableEntity) String() string { + return fmt.Sprintf("[POST /v1/multisig-transactions/{safe_tx_hash}/confirmations/][%d] v1MultisigTransactionsConfirmationsCreateUnprocessableEntity", 422) +} + +func (o *V1MultisigTransactionsConfirmationsCreateUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/transactions/v1_multisig_transactions_confirmations_list_parameters.go b/utils/safe_api/client/transactions/v1_multisig_transactions_confirmations_list_parameters.go new file mode 100644 index 0000000..75cf596 --- /dev/null +++ b/utils/safe_api/client/transactions/v1_multisig_transactions_confirmations_list_parameters.go @@ -0,0 +1,217 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewV1MultisigTransactionsConfirmationsListParams creates a new V1MultisigTransactionsConfirmationsListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1MultisigTransactionsConfirmationsListParams() *V1MultisigTransactionsConfirmationsListParams { + return &V1MultisigTransactionsConfirmationsListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1MultisigTransactionsConfirmationsListParamsWithTimeout creates a new V1MultisigTransactionsConfirmationsListParams object +// with the ability to set a timeout on a request. +func NewV1MultisigTransactionsConfirmationsListParamsWithTimeout(timeout time.Duration) *V1MultisigTransactionsConfirmationsListParams { + return &V1MultisigTransactionsConfirmationsListParams{ + timeout: timeout, + } +} + +// NewV1MultisigTransactionsConfirmationsListParamsWithContext creates a new V1MultisigTransactionsConfirmationsListParams object +// with the ability to set a context for a request. +func NewV1MultisigTransactionsConfirmationsListParamsWithContext(ctx context.Context) *V1MultisigTransactionsConfirmationsListParams { + return &V1MultisigTransactionsConfirmationsListParams{ + Context: ctx, + } +} + +// NewV1MultisigTransactionsConfirmationsListParamsWithHTTPClient creates a new V1MultisigTransactionsConfirmationsListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1MultisigTransactionsConfirmationsListParamsWithHTTPClient(client *http.Client) *V1MultisigTransactionsConfirmationsListParams { + return &V1MultisigTransactionsConfirmationsListParams{ + HTTPClient: client, + } +} + +/* +V1MultisigTransactionsConfirmationsListParams contains all the parameters to send to the API endpoint + + for the v1 multisig transactions confirmations list operation. + + Typically these are written to a http.Request. +*/ +type V1MultisigTransactionsConfirmationsListParams struct { + + /* Limit. + + Number of results to return per page. + */ + Limit *int64 + + /* Offset. + + The initial index from which to return the results. + */ + Offset *int64 + + // SafeTxHash. + SafeTxHash string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 multisig transactions confirmations list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1MultisigTransactionsConfirmationsListParams) WithDefaults() *V1MultisigTransactionsConfirmationsListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 multisig transactions confirmations list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1MultisigTransactionsConfirmationsListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 multisig transactions confirmations list params +func (o *V1MultisigTransactionsConfirmationsListParams) WithTimeout(timeout time.Duration) *V1MultisigTransactionsConfirmationsListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 multisig transactions confirmations list params +func (o *V1MultisigTransactionsConfirmationsListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 multisig transactions confirmations list params +func (o *V1MultisigTransactionsConfirmationsListParams) WithContext(ctx context.Context) *V1MultisigTransactionsConfirmationsListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 multisig transactions confirmations list params +func (o *V1MultisigTransactionsConfirmationsListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 multisig transactions confirmations list params +func (o *V1MultisigTransactionsConfirmationsListParams) WithHTTPClient(client *http.Client) *V1MultisigTransactionsConfirmationsListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 multisig transactions confirmations list params +func (o *V1MultisigTransactionsConfirmationsListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithLimit adds the limit to the v1 multisig transactions confirmations list params +func (o *V1MultisigTransactionsConfirmationsListParams) WithLimit(limit *int64) *V1MultisigTransactionsConfirmationsListParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the v1 multisig transactions confirmations list params +func (o *V1MultisigTransactionsConfirmationsListParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the v1 multisig transactions confirmations list params +func (o *V1MultisigTransactionsConfirmationsListParams) WithOffset(offset *int64) *V1MultisigTransactionsConfirmationsListParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the v1 multisig transactions confirmations list params +func (o *V1MultisigTransactionsConfirmationsListParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithSafeTxHash adds the safeTxHash to the v1 multisig transactions confirmations list params +func (o *V1MultisigTransactionsConfirmationsListParams) WithSafeTxHash(safeTxHash string) *V1MultisigTransactionsConfirmationsListParams { + o.SetSafeTxHash(safeTxHash) + return o +} + +// SetSafeTxHash adds the safeTxHash to the v1 multisig transactions confirmations list params +func (o *V1MultisigTransactionsConfirmationsListParams) SetSafeTxHash(safeTxHash string) { + o.SafeTxHash = safeTxHash +} + +// WriteToRequest writes these params to a swagger request +func (o *V1MultisigTransactionsConfirmationsListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + // path param safe_tx_hash + if err := r.SetPathParam("safe_tx_hash", o.SafeTxHash); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/transactions/v1_multisig_transactions_confirmations_list_responses.go b/utils/safe_api/client/transactions/v1_multisig_transactions_confirmations_list_responses.go new file mode 100644 index 0000000..deac8e7 --- /dev/null +++ b/utils/safe_api/client/transactions/v1_multisig_transactions_confirmations_list_responses.go @@ -0,0 +1,339 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + models "omni-balance/utils/safe_api" +) + +// V1MultisigTransactionsConfirmationsListReader is a Reader for the V1MultisigTransactionsConfirmationsList structure. +type V1MultisigTransactionsConfirmationsListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1MultisigTransactionsConfirmationsListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1MultisigTransactionsConfirmationsListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1MultisigTransactionsConfirmationsListBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/multisig-transactions/{safe_tx_hash}/confirmations/] v1_multisig-transactions_confirmations_list", response, response.Code()) + } +} + +// NewV1MultisigTransactionsConfirmationsListOK creates a V1MultisigTransactionsConfirmationsListOK with default headers values +func NewV1MultisigTransactionsConfirmationsListOK() *V1MultisigTransactionsConfirmationsListOK { + return &V1MultisigTransactionsConfirmationsListOK{} +} + +/* +V1MultisigTransactionsConfirmationsListOK describes a response with status code 200, with default header values. + +V1MultisigTransactionsConfirmationsListOK v1 multisig transactions confirmations list o k +*/ +type V1MultisigTransactionsConfirmationsListOK struct { + Payload *V1MultisigTransactionsConfirmationsListOKBody +} + +// IsSuccess returns true when this v1 multisig transactions confirmations list o k response has a 2xx status code +func (o *V1MultisigTransactionsConfirmationsListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 multisig transactions confirmations list o k response has a 3xx status code +func (o *V1MultisigTransactionsConfirmationsListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 multisig transactions confirmations list o k response has a 4xx status code +func (o *V1MultisigTransactionsConfirmationsListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 multisig transactions confirmations list o k response has a 5xx status code +func (o *V1MultisigTransactionsConfirmationsListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 multisig transactions confirmations list o k response a status code equal to that given +func (o *V1MultisigTransactionsConfirmationsListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 multisig transactions confirmations list o k response +func (o *V1MultisigTransactionsConfirmationsListOK) Code() int { + return 200 +} + +func (o *V1MultisigTransactionsConfirmationsListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/multisig-transactions/{safe_tx_hash}/confirmations/][%d] v1MultisigTransactionsConfirmationsListOK %s", 200, payload) +} + +func (o *V1MultisigTransactionsConfirmationsListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/multisig-transactions/{safe_tx_hash}/confirmations/][%d] v1MultisigTransactionsConfirmationsListOK %s", 200, payload) +} + +func (o *V1MultisigTransactionsConfirmationsListOK) GetPayload() *V1MultisigTransactionsConfirmationsListOKBody { + return o.Payload +} + +func (o *V1MultisigTransactionsConfirmationsListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(V1MultisigTransactionsConfirmationsListOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1MultisigTransactionsConfirmationsListBadRequest creates a V1MultisigTransactionsConfirmationsListBadRequest with default headers values +func NewV1MultisigTransactionsConfirmationsListBadRequest() *V1MultisigTransactionsConfirmationsListBadRequest { + return &V1MultisigTransactionsConfirmationsListBadRequest{} +} + +/* +V1MultisigTransactionsConfirmationsListBadRequest describes a response with status code 400, with default header values. + +Invalid data +*/ +type V1MultisigTransactionsConfirmationsListBadRequest struct { +} + +// IsSuccess returns true when this v1 multisig transactions confirmations list bad request response has a 2xx status code +func (o *V1MultisigTransactionsConfirmationsListBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 multisig transactions confirmations list bad request response has a 3xx status code +func (o *V1MultisigTransactionsConfirmationsListBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 multisig transactions confirmations list bad request response has a 4xx status code +func (o *V1MultisigTransactionsConfirmationsListBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 multisig transactions confirmations list bad request response has a 5xx status code +func (o *V1MultisigTransactionsConfirmationsListBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 multisig transactions confirmations list bad request response a status code equal to that given +func (o *V1MultisigTransactionsConfirmationsListBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 multisig transactions confirmations list bad request response +func (o *V1MultisigTransactionsConfirmationsListBadRequest) Code() int { + return 400 +} + +func (o *V1MultisigTransactionsConfirmationsListBadRequest) Error() string { + return fmt.Sprintf("[GET /v1/multisig-transactions/{safe_tx_hash}/confirmations/][%d] v1MultisigTransactionsConfirmationsListBadRequest", 400) +} + +func (o *V1MultisigTransactionsConfirmationsListBadRequest) String() string { + return fmt.Sprintf("[GET /v1/multisig-transactions/{safe_tx_hash}/confirmations/][%d] v1MultisigTransactionsConfirmationsListBadRequest", 400) +} + +func (o *V1MultisigTransactionsConfirmationsListBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +/* +V1MultisigTransactionsConfirmationsListOKBody v1 multisig transactions confirmations list o k body +swagger:model V1MultisigTransactionsConfirmationsListOKBody +*/ +type V1MultisigTransactionsConfirmationsListOKBody struct { + + // count + // Required: true + Count *int64 `json:"count"` + + // next + // Format: uri + Next *strfmt.URI `json:"next,omitempty"` + + // previous + // Format: uri + Previous *strfmt.URI `json:"previous,omitempty"` + + // results + // Required: true + Results []*models.SafeMultisigConfirmationResponse `json:"results"` +} + +// Validate validates this v1 multisig transactions confirmations list o k body +func (o *V1MultisigTransactionsConfirmationsListOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateCount(formats); err != nil { + res = append(res, err) + } + + if err := o.validateNext(formats); err != nil { + res = append(res, err) + } + + if err := o.validatePrevious(formats); err != nil { + res = append(res, err) + } + + if err := o.validateResults(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V1MultisigTransactionsConfirmationsListOKBody) validateCount(formats strfmt.Registry) error { + + if err := validate.Required("v1MultisigTransactionsConfirmationsListOK"+"."+"count", "body", o.Count); err != nil { + return err + } + + return nil +} + +func (o *V1MultisigTransactionsConfirmationsListOKBody) validateNext(formats strfmt.Registry) error { + if swag.IsZero(o.Next) { // not required + return nil + } + + if err := validate.FormatOf("v1MultisigTransactionsConfirmationsListOK"+"."+"next", "body", "uri", o.Next.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V1MultisigTransactionsConfirmationsListOKBody) validatePrevious(formats strfmt.Registry) error { + if swag.IsZero(o.Previous) { // not required + return nil + } + + if err := validate.FormatOf("v1MultisigTransactionsConfirmationsListOK"+"."+"previous", "body", "uri", o.Previous.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V1MultisigTransactionsConfirmationsListOKBody) validateResults(formats strfmt.Registry) error { + + if err := validate.Required("v1MultisigTransactionsConfirmationsListOK"+"."+"results", "body", o.Results); err != nil { + return err + } + + for i := 0; i < len(o.Results); i++ { + if swag.IsZero(o.Results[i]) { // not required + continue + } + + if o.Results[i] != nil { + if err := o.Results[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v1MultisigTransactionsConfirmationsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v1MultisigTransactionsConfirmationsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this v1 multisig transactions confirmations list o k body based on the context it is used +func (o *V1MultisigTransactionsConfirmationsListOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResults(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V1MultisigTransactionsConfirmationsListOKBody) contextValidateResults(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Results); i++ { + + if o.Results[i] != nil { + + if swag.IsZero(o.Results[i]) { // not required + return nil + } + + if err := o.Results[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v1MultisigTransactionsConfirmationsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v1MultisigTransactionsConfirmationsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *V1MultisigTransactionsConfirmationsListOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *V1MultisigTransactionsConfirmationsListOKBody) UnmarshalBinary(b []byte) error { + var res V1MultisigTransactionsConfirmationsListOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/utils/safe_api/client/transactions/v1_multisig_transactions_delete_parameters.go b/utils/safe_api/client/transactions/v1_multisig_transactions_delete_parameters.go new file mode 100644 index 0000000..1183f74 --- /dev/null +++ b/utils/safe_api/client/transactions/v1_multisig_transactions_delete_parameters.go @@ -0,0 +1,169 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// NewV1MultisigTransactionsDeleteParams creates a new V1MultisigTransactionsDeleteParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1MultisigTransactionsDeleteParams() *V1MultisigTransactionsDeleteParams { + return &V1MultisigTransactionsDeleteParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1MultisigTransactionsDeleteParamsWithTimeout creates a new V1MultisigTransactionsDeleteParams object +// with the ability to set a timeout on a request. +func NewV1MultisigTransactionsDeleteParamsWithTimeout(timeout time.Duration) *V1MultisigTransactionsDeleteParams { + return &V1MultisigTransactionsDeleteParams{ + timeout: timeout, + } +} + +// NewV1MultisigTransactionsDeleteParamsWithContext creates a new V1MultisigTransactionsDeleteParams object +// with the ability to set a context for a request. +func NewV1MultisigTransactionsDeleteParamsWithContext(ctx context.Context) *V1MultisigTransactionsDeleteParams { + return &V1MultisigTransactionsDeleteParams{ + Context: ctx, + } +} + +// NewV1MultisigTransactionsDeleteParamsWithHTTPClient creates a new V1MultisigTransactionsDeleteParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1MultisigTransactionsDeleteParamsWithHTTPClient(client *http.Client) *V1MultisigTransactionsDeleteParams { + return &V1MultisigTransactionsDeleteParams{ + HTTPClient: client, + } +} + +/* +V1MultisigTransactionsDeleteParams contains all the parameters to send to the API endpoint + + for the v1 multisig transactions delete operation. + + Typically these are written to a http.Request. +*/ +type V1MultisigTransactionsDeleteParams struct { + + // Data. + Data *models.SafeMultisigTransactionDelete + + // SafeTxHash. + SafeTxHash string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 multisig transactions delete params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1MultisigTransactionsDeleteParams) WithDefaults() *V1MultisigTransactionsDeleteParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 multisig transactions delete params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1MultisigTransactionsDeleteParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 multisig transactions delete params +func (o *V1MultisigTransactionsDeleteParams) WithTimeout(timeout time.Duration) *V1MultisigTransactionsDeleteParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 multisig transactions delete params +func (o *V1MultisigTransactionsDeleteParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 multisig transactions delete params +func (o *V1MultisigTransactionsDeleteParams) WithContext(ctx context.Context) *V1MultisigTransactionsDeleteParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 multisig transactions delete params +func (o *V1MultisigTransactionsDeleteParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 multisig transactions delete params +func (o *V1MultisigTransactionsDeleteParams) WithHTTPClient(client *http.Client) *V1MultisigTransactionsDeleteParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 multisig transactions delete params +func (o *V1MultisigTransactionsDeleteParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the v1 multisig transactions delete params +func (o *V1MultisigTransactionsDeleteParams) WithData(data *models.SafeMultisigTransactionDelete) *V1MultisigTransactionsDeleteParams { + o.SetData(data) + return o +} + +// SetData adds the data to the v1 multisig transactions delete params +func (o *V1MultisigTransactionsDeleteParams) SetData(data *models.SafeMultisigTransactionDelete) { + o.Data = data +} + +// WithSafeTxHash adds the safeTxHash to the v1 multisig transactions delete params +func (o *V1MultisigTransactionsDeleteParams) WithSafeTxHash(safeTxHash string) *V1MultisigTransactionsDeleteParams { + o.SetSafeTxHash(safeTxHash) + return o +} + +// SetSafeTxHash adds the safeTxHash to the v1 multisig transactions delete params +func (o *V1MultisigTransactionsDeleteParams) SetSafeTxHash(safeTxHash string) { + o.SafeTxHash = safeTxHash +} + +// WriteToRequest writes these params to a swagger request +func (o *V1MultisigTransactionsDeleteParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + // path param safe_tx_hash + if err := r.SetPathParam("safe_tx_hash", o.SafeTxHash); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/transactions/v1_multisig_transactions_delete_responses.go b/utils/safe_api/client/transactions/v1_multisig_transactions_delete_responses.go new file mode 100644 index 0000000..85c5342 --- /dev/null +++ b/utils/safe_api/client/transactions/v1_multisig_transactions_delete_responses.go @@ -0,0 +1,212 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// V1MultisigTransactionsDeleteReader is a Reader for the V1MultisigTransactionsDelete structure. +type V1MultisigTransactionsDeleteReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1MultisigTransactionsDeleteReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 204: + result := NewV1MultisigTransactionsDeleteNoContent() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1MultisigTransactionsDeleteBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewV1MultisigTransactionsDeleteNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /v1/multisig-transactions/{safe_tx_hash}/] v1_multisig-transactions_delete", response, response.Code()) + } +} + +// NewV1MultisigTransactionsDeleteNoContent creates a V1MultisigTransactionsDeleteNoContent with default headers values +func NewV1MultisigTransactionsDeleteNoContent() *V1MultisigTransactionsDeleteNoContent { + return &V1MultisigTransactionsDeleteNoContent{} +} + +/* +V1MultisigTransactionsDeleteNoContent describes a response with status code 204, with default header values. + +Deleted +*/ +type V1MultisigTransactionsDeleteNoContent struct { +} + +// IsSuccess returns true when this v1 multisig transactions delete no content response has a 2xx status code +func (o *V1MultisigTransactionsDeleteNoContent) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 multisig transactions delete no content response has a 3xx status code +func (o *V1MultisigTransactionsDeleteNoContent) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 multisig transactions delete no content response has a 4xx status code +func (o *V1MultisigTransactionsDeleteNoContent) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 multisig transactions delete no content response has a 5xx status code +func (o *V1MultisigTransactionsDeleteNoContent) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 multisig transactions delete no content response a status code equal to that given +func (o *V1MultisigTransactionsDeleteNoContent) IsCode(code int) bool { + return code == 204 +} + +// Code gets the status code for the v1 multisig transactions delete no content response +func (o *V1MultisigTransactionsDeleteNoContent) Code() int { + return 204 +} + +func (o *V1MultisigTransactionsDeleteNoContent) Error() string { + return fmt.Sprintf("[DELETE /v1/multisig-transactions/{safe_tx_hash}/][%d] v1MultisigTransactionsDeleteNoContent", 204) +} + +func (o *V1MultisigTransactionsDeleteNoContent) String() string { + return fmt.Sprintf("[DELETE /v1/multisig-transactions/{safe_tx_hash}/][%d] v1MultisigTransactionsDeleteNoContent", 204) +} + +func (o *V1MultisigTransactionsDeleteNoContent) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1MultisigTransactionsDeleteBadRequest creates a V1MultisigTransactionsDeleteBadRequest with default headers values +func NewV1MultisigTransactionsDeleteBadRequest() *V1MultisigTransactionsDeleteBadRequest { + return &V1MultisigTransactionsDeleteBadRequest{} +} + +/* +V1MultisigTransactionsDeleteBadRequest describes a response with status code 400, with default header values. + +Error processing data +*/ +type V1MultisigTransactionsDeleteBadRequest struct { +} + +// IsSuccess returns true when this v1 multisig transactions delete bad request response has a 2xx status code +func (o *V1MultisigTransactionsDeleteBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 multisig transactions delete bad request response has a 3xx status code +func (o *V1MultisigTransactionsDeleteBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 multisig transactions delete bad request response has a 4xx status code +func (o *V1MultisigTransactionsDeleteBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 multisig transactions delete bad request response has a 5xx status code +func (o *V1MultisigTransactionsDeleteBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 multisig transactions delete bad request response a status code equal to that given +func (o *V1MultisigTransactionsDeleteBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 multisig transactions delete bad request response +func (o *V1MultisigTransactionsDeleteBadRequest) Code() int { + return 400 +} + +func (o *V1MultisigTransactionsDeleteBadRequest) Error() string { + return fmt.Sprintf("[DELETE /v1/multisig-transactions/{safe_tx_hash}/][%d] v1MultisigTransactionsDeleteBadRequest", 400) +} + +func (o *V1MultisigTransactionsDeleteBadRequest) String() string { + return fmt.Sprintf("[DELETE /v1/multisig-transactions/{safe_tx_hash}/][%d] v1MultisigTransactionsDeleteBadRequest", 400) +} + +func (o *V1MultisigTransactionsDeleteBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1MultisigTransactionsDeleteNotFound creates a V1MultisigTransactionsDeleteNotFound with default headers values +func NewV1MultisigTransactionsDeleteNotFound() *V1MultisigTransactionsDeleteNotFound { + return &V1MultisigTransactionsDeleteNotFound{} +} + +/* +V1MultisigTransactionsDeleteNotFound describes a response with status code 404, with default header values. + +Transaction not found +*/ +type V1MultisigTransactionsDeleteNotFound struct { +} + +// IsSuccess returns true when this v1 multisig transactions delete not found response has a 2xx status code +func (o *V1MultisigTransactionsDeleteNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 multisig transactions delete not found response has a 3xx status code +func (o *V1MultisigTransactionsDeleteNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 multisig transactions delete not found response has a 4xx status code +func (o *V1MultisigTransactionsDeleteNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 multisig transactions delete not found response has a 5xx status code +func (o *V1MultisigTransactionsDeleteNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 multisig transactions delete not found response a status code equal to that given +func (o *V1MultisigTransactionsDeleteNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 multisig transactions delete not found response +func (o *V1MultisigTransactionsDeleteNotFound) Code() int { + return 404 +} + +func (o *V1MultisigTransactionsDeleteNotFound) Error() string { + return fmt.Sprintf("[DELETE /v1/multisig-transactions/{safe_tx_hash}/][%d] v1MultisigTransactionsDeleteNotFound", 404) +} + +func (o *V1MultisigTransactionsDeleteNotFound) String() string { + return fmt.Sprintf("[DELETE /v1/multisig-transactions/{safe_tx_hash}/][%d] v1MultisigTransactionsDeleteNotFound", 404) +} + +func (o *V1MultisigTransactionsDeleteNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/transactions/v1_multisig_transactions_read_parameters.go b/utils/safe_api/client/transactions/v1_multisig_transactions_read_parameters.go new file mode 100644 index 0000000..63ef766 --- /dev/null +++ b/utils/safe_api/client/transactions/v1_multisig_transactions_read_parameters.go @@ -0,0 +1,148 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1MultisigTransactionsReadParams creates a new V1MultisigTransactionsReadParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1MultisigTransactionsReadParams() *V1MultisigTransactionsReadParams { + return &V1MultisigTransactionsReadParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1MultisigTransactionsReadParamsWithTimeout creates a new V1MultisigTransactionsReadParams object +// with the ability to set a timeout on a request. +func NewV1MultisigTransactionsReadParamsWithTimeout(timeout time.Duration) *V1MultisigTransactionsReadParams { + return &V1MultisigTransactionsReadParams{ + timeout: timeout, + } +} + +// NewV1MultisigTransactionsReadParamsWithContext creates a new V1MultisigTransactionsReadParams object +// with the ability to set a context for a request. +func NewV1MultisigTransactionsReadParamsWithContext(ctx context.Context) *V1MultisigTransactionsReadParams { + return &V1MultisigTransactionsReadParams{ + Context: ctx, + } +} + +// NewV1MultisigTransactionsReadParamsWithHTTPClient creates a new V1MultisigTransactionsReadParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1MultisigTransactionsReadParamsWithHTTPClient(client *http.Client) *V1MultisigTransactionsReadParams { + return &V1MultisigTransactionsReadParams{ + HTTPClient: client, + } +} + +/* +V1MultisigTransactionsReadParams contains all the parameters to send to the API endpoint + + for the v1 multisig transactions read operation. + + Typically these are written to a http.Request. +*/ +type V1MultisigTransactionsReadParams struct { + + // SafeTxHash. + SafeTxHash string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 multisig transactions read params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1MultisigTransactionsReadParams) WithDefaults() *V1MultisigTransactionsReadParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 multisig transactions read params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1MultisigTransactionsReadParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 multisig transactions read params +func (o *V1MultisigTransactionsReadParams) WithTimeout(timeout time.Duration) *V1MultisigTransactionsReadParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 multisig transactions read params +func (o *V1MultisigTransactionsReadParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 multisig transactions read params +func (o *V1MultisigTransactionsReadParams) WithContext(ctx context.Context) *V1MultisigTransactionsReadParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 multisig transactions read params +func (o *V1MultisigTransactionsReadParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 multisig transactions read params +func (o *V1MultisigTransactionsReadParams) WithHTTPClient(client *http.Client) *V1MultisigTransactionsReadParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 multisig transactions read params +func (o *V1MultisigTransactionsReadParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithSafeTxHash adds the safeTxHash to the v1 multisig transactions read params +func (o *V1MultisigTransactionsReadParams) WithSafeTxHash(safeTxHash string) *V1MultisigTransactionsReadParams { + o.SetSafeTxHash(safeTxHash) + return o +} + +// SetSafeTxHash adds the safeTxHash to the v1 multisig transactions read params +func (o *V1MultisigTransactionsReadParams) SetSafeTxHash(safeTxHash string) { + o.SafeTxHash = safeTxHash +} + +// WriteToRequest writes these params to a swagger request +func (o *V1MultisigTransactionsReadParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param safe_tx_hash + if err := r.SetPathParam("safe_tx_hash", o.SafeTxHash); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/transactions/v1_multisig_transactions_read_responses.go b/utils/safe_api/client/transactions/v1_multisig_transactions_read_responses.go new file mode 100644 index 0000000..7e0eed3 --- /dev/null +++ b/utils/safe_api/client/transactions/v1_multisig_transactions_read_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1MultisigTransactionsReadReader is a Reader for the V1MultisigTransactionsRead structure. +type V1MultisigTransactionsReadReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1MultisigTransactionsReadReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1MultisigTransactionsReadOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + return nil, runtime.NewAPIError("[GET /v1/multisig-transactions/{safe_tx_hash}/] v1_multisig-transactions_read", response, response.Code()) + } +} + +// NewV1MultisigTransactionsReadOK creates a V1MultisigTransactionsReadOK with default headers values +func NewV1MultisigTransactionsReadOK() *V1MultisigTransactionsReadOK { + return &V1MultisigTransactionsReadOK{} +} + +/* +V1MultisigTransactionsReadOK describes a response with status code 200, with default header values. + +V1MultisigTransactionsReadOK v1 multisig transactions read o k +*/ +type V1MultisigTransactionsReadOK struct { + Payload *models.SafeMultisigTransactionResponse +} + +// IsSuccess returns true when this v1 multisig transactions read o k response has a 2xx status code +func (o *V1MultisigTransactionsReadOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 multisig transactions read o k response has a 3xx status code +func (o *V1MultisigTransactionsReadOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 multisig transactions read o k response has a 4xx status code +func (o *V1MultisigTransactionsReadOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 multisig transactions read o k response has a 5xx status code +func (o *V1MultisigTransactionsReadOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 multisig transactions read o k response a status code equal to that given +func (o *V1MultisigTransactionsReadOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 multisig transactions read o k response +func (o *V1MultisigTransactionsReadOK) Code() int { + return 200 +} + +func (o *V1MultisigTransactionsReadOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/multisig-transactions/{safe_tx_hash}/][%d] v1MultisigTransactionsReadOK %s", 200, payload) +} + +func (o *V1MultisigTransactionsReadOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/multisig-transactions/{safe_tx_hash}/][%d] v1MultisigTransactionsReadOK %s", 200, payload) +} + +func (o *V1MultisigTransactionsReadOK) GetPayload() *models.SafeMultisigTransactionResponse { + return o.Payload +} + +func (o *V1MultisigTransactionsReadOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.SafeMultisigTransactionResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/utils/safe_api/client/transactions/v1_safes_all_transactions_list_parameters.go b/utils/safe_api/client/transactions/v1_safes_all_transactions_list_parameters.go new file mode 100644 index 0000000..b016333 --- /dev/null +++ b/utils/safe_api/client/transactions/v1_safes_all_transactions_list_parameters.go @@ -0,0 +1,374 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewV1SafesAllTransactionsListParams creates a new V1SafesAllTransactionsListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SafesAllTransactionsListParams() *V1SafesAllTransactionsListParams { + return &V1SafesAllTransactionsListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SafesAllTransactionsListParamsWithTimeout creates a new V1SafesAllTransactionsListParams object +// with the ability to set a timeout on a request. +func NewV1SafesAllTransactionsListParamsWithTimeout(timeout time.Duration) *V1SafesAllTransactionsListParams { + return &V1SafesAllTransactionsListParams{ + timeout: timeout, + } +} + +// NewV1SafesAllTransactionsListParamsWithContext creates a new V1SafesAllTransactionsListParams object +// with the ability to set a context for a request. +func NewV1SafesAllTransactionsListParamsWithContext(ctx context.Context) *V1SafesAllTransactionsListParams { + return &V1SafesAllTransactionsListParams{ + Context: ctx, + } +} + +// NewV1SafesAllTransactionsListParamsWithHTTPClient creates a new V1SafesAllTransactionsListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SafesAllTransactionsListParamsWithHTTPClient(client *http.Client) *V1SafesAllTransactionsListParams { + return &V1SafesAllTransactionsListParams{ + HTTPClient: client, + } +} + +/* +V1SafesAllTransactionsListParams contains all the parameters to send to the API endpoint + + for the v1 safes all transactions list operation. + + Typically these are written to a http.Request. +*/ +type V1SafesAllTransactionsListParams struct { + + // Address. + Address string + + /* Executed. + + If `True` only executed transactions are returned + */ + Executed *bool + + /* Limit. + + Number of results to return per page. + */ + Limit *int64 + + /* Offset. + + The initial index from which to return the results. + */ + Offset *int64 + + /* Ordering. + + Which field to use when ordering the results. + */ + Ordering *string + + /* Queued. + + If `True` transactions with `nonce >= Safe current nonce` are also returned + + Default: true + */ + Queued *bool + + /* Trusted. + + If `True` just trusted transactions are shown (indexed, added by a delegate or with at least one confirmation) + + Default: true + */ + Trusted *bool + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 safes all transactions list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesAllTransactionsListParams) WithDefaults() *V1SafesAllTransactionsListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 safes all transactions list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesAllTransactionsListParams) SetDefaults() { + var ( + executedDefault = bool(false) + + queuedDefault = bool(true) + + trustedDefault = bool(true) + ) + + val := V1SafesAllTransactionsListParams{ + Executed: &executedDefault, + Queued: &queuedDefault, + Trusted: &trustedDefault, + } + + val.timeout = o.timeout + val.Context = o.Context + val.HTTPClient = o.HTTPClient + *o = val +} + +// WithTimeout adds the timeout to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) WithTimeout(timeout time.Duration) *V1SafesAllTransactionsListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) WithContext(ctx context.Context) *V1SafesAllTransactionsListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) WithHTTPClient(client *http.Client) *V1SafesAllTransactionsListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) WithAddress(address string) *V1SafesAllTransactionsListParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) SetAddress(address string) { + o.Address = address +} + +// WithExecuted adds the executed to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) WithExecuted(executed *bool) *V1SafesAllTransactionsListParams { + o.SetExecuted(executed) + return o +} + +// SetExecuted adds the executed to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) SetExecuted(executed *bool) { + o.Executed = executed +} + +// WithLimit adds the limit to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) WithLimit(limit *int64) *V1SafesAllTransactionsListParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) WithOffset(offset *int64) *V1SafesAllTransactionsListParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithOrdering adds the ordering to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) WithOrdering(ordering *string) *V1SafesAllTransactionsListParams { + o.SetOrdering(ordering) + return o +} + +// SetOrdering adds the ordering to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) SetOrdering(ordering *string) { + o.Ordering = ordering +} + +// WithQueued adds the queued to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) WithQueued(queued *bool) *V1SafesAllTransactionsListParams { + o.SetQueued(queued) + return o +} + +// SetQueued adds the queued to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) SetQueued(queued *bool) { + o.Queued = queued +} + +// WithTrusted adds the trusted to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) WithTrusted(trusted *bool) *V1SafesAllTransactionsListParams { + o.SetTrusted(trusted) + return o +} + +// SetTrusted adds the trusted to the v1 safes all transactions list params +func (o *V1SafesAllTransactionsListParams) SetTrusted(trusted *bool) { + o.Trusted = trusted +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SafesAllTransactionsListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + + if o.Executed != nil { + + // query param executed + var qrExecuted bool + + if o.Executed != nil { + qrExecuted = *o.Executed + } + qExecuted := swag.FormatBool(qrExecuted) + if qExecuted != "" { + + if err := r.SetQueryParam("executed", qExecuted); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Ordering != nil { + + // query param ordering + var qrOrdering string + + if o.Ordering != nil { + qrOrdering = *o.Ordering + } + qOrdering := qrOrdering + if qOrdering != "" { + + if err := r.SetQueryParam("ordering", qOrdering); err != nil { + return err + } + } + } + + if o.Queued != nil { + + // query param queued + var qrQueued bool + + if o.Queued != nil { + qrQueued = *o.Queued + } + qQueued := swag.FormatBool(qrQueued) + if qQueued != "" { + + if err := r.SetQueryParam("queued", qQueued); err != nil { + return err + } + } + } + + if o.Trusted != nil { + + // query param trusted + var qrTrusted bool + + if o.Trusted != nil { + qrTrusted = *o.Trusted + } + qTrusted := swag.FormatBool(qrTrusted) + if qTrusted != "" { + + if err := r.SetQueryParam("trusted", qTrusted); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/transactions/v1_safes_all_transactions_list_responses.go b/utils/safe_api/client/transactions/v1_safes_all_transactions_list_responses.go new file mode 100644 index 0000000..e76a3e8 --- /dev/null +++ b/utils/safe_api/client/transactions/v1_safes_all_transactions_list_responses.go @@ -0,0 +1,168 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1SafesAllTransactionsListReader is a Reader for the V1SafesAllTransactionsList structure. +type V1SafesAllTransactionsListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SafesAllTransactionsListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1SafesAllTransactionsListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 422: + result := NewV1SafesAllTransactionsListUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/safes/{address}/all-transactions/] v1_safes_all-transactions_list", response, response.Code()) + } +} + +// NewV1SafesAllTransactionsListOK creates a V1SafesAllTransactionsListOK with default headers values +func NewV1SafesAllTransactionsListOK() *V1SafesAllTransactionsListOK { + return &V1SafesAllTransactionsListOK{} +} + +/* +V1SafesAllTransactionsListOK describes a response with status code 200, with default header values. + +A list with every element with the structure of one of these transactiontypes +*/ +type V1SafesAllTransactionsListOK struct { + Payload *models.AllTransactionsSchema +} + +// IsSuccess returns true when this v1 safes all transactions list o k response has a 2xx status code +func (o *V1SafesAllTransactionsListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 safes all transactions list o k response has a 3xx status code +func (o *V1SafesAllTransactionsListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes all transactions list o k response has a 4xx status code +func (o *V1SafesAllTransactionsListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 safes all transactions list o k response has a 5xx status code +func (o *V1SafesAllTransactionsListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes all transactions list o k response a status code equal to that given +func (o *V1SafesAllTransactionsListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 safes all transactions list o k response +func (o *V1SafesAllTransactionsListOK) Code() int { + return 200 +} + +func (o *V1SafesAllTransactionsListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/all-transactions/][%d] v1SafesAllTransactionsListOK %s", 200, payload) +} + +func (o *V1SafesAllTransactionsListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/all-transactions/][%d] v1SafesAllTransactionsListOK %s", 200, payload) +} + +func (o *V1SafesAllTransactionsListOK) GetPayload() *models.AllTransactionsSchema { + return o.Payload +} + +func (o *V1SafesAllTransactionsListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.AllTransactionsSchema) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SafesAllTransactionsListUnprocessableEntity creates a V1SafesAllTransactionsListUnprocessableEntity with default headers values +func NewV1SafesAllTransactionsListUnprocessableEntity() *V1SafesAllTransactionsListUnprocessableEntity { + return &V1SafesAllTransactionsListUnprocessableEntity{} +} + +/* +V1SafesAllTransactionsListUnprocessableEntity describes a response with status code 422, with default header values. + +code = 1: Checksum address validation failed +*/ +type V1SafesAllTransactionsListUnprocessableEntity struct { +} + +// IsSuccess returns true when this v1 safes all transactions list unprocessable entity response has a 2xx status code +func (o *V1SafesAllTransactionsListUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes all transactions list unprocessable entity response has a 3xx status code +func (o *V1SafesAllTransactionsListUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes all transactions list unprocessable entity response has a 4xx status code +func (o *V1SafesAllTransactionsListUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes all transactions list unprocessable entity response has a 5xx status code +func (o *V1SafesAllTransactionsListUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes all transactions list unprocessable entity response a status code equal to that given +func (o *V1SafesAllTransactionsListUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 safes all transactions list unprocessable entity response +func (o *V1SafesAllTransactionsListUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1SafesAllTransactionsListUnprocessableEntity) Error() string { + return fmt.Sprintf("[GET /v1/safes/{address}/all-transactions/][%d] v1SafesAllTransactionsListUnprocessableEntity", 422) +} + +func (o *V1SafesAllTransactionsListUnprocessableEntity) String() string { + return fmt.Sprintf("[GET /v1/safes/{address}/all-transactions/][%d] v1SafesAllTransactionsListUnprocessableEntity", 422) +} + +func (o *V1SafesAllTransactionsListUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/transactions/v1_safes_incoming_transfers_list_parameters.go b/utils/safe_api/client/transactions/v1_safes_incoming_transfers_list_parameters.go new file mode 100644 index 0000000..8aafb19 --- /dev/null +++ b/utils/safe_api/client/transactions/v1_safes_incoming_transfers_list_parameters.go @@ -0,0 +1,795 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewV1SafesIncomingTransfersListParams creates a new V1SafesIncomingTransfersListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SafesIncomingTransfersListParams() *V1SafesIncomingTransfersListParams { + return &V1SafesIncomingTransfersListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SafesIncomingTransfersListParamsWithTimeout creates a new V1SafesIncomingTransfersListParams object +// with the ability to set a timeout on a request. +func NewV1SafesIncomingTransfersListParamsWithTimeout(timeout time.Duration) *V1SafesIncomingTransfersListParams { + return &V1SafesIncomingTransfersListParams{ + timeout: timeout, + } +} + +// NewV1SafesIncomingTransfersListParamsWithContext creates a new V1SafesIncomingTransfersListParams object +// with the ability to set a context for a request. +func NewV1SafesIncomingTransfersListParamsWithContext(ctx context.Context) *V1SafesIncomingTransfersListParams { + return &V1SafesIncomingTransfersListParams{ + Context: ctx, + } +} + +// NewV1SafesIncomingTransfersListParamsWithHTTPClient creates a new V1SafesIncomingTransfersListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SafesIncomingTransfersListParamsWithHTTPClient(client *http.Client) *V1SafesIncomingTransfersListParams { + return &V1SafesIncomingTransfersListParams{ + HTTPClient: client, + } +} + +/* +V1SafesIncomingTransfersListParams contains all the parameters to send to the API endpoint + + for the v1 safes incoming transfers list operation. + + Typically these are written to a http.Request. +*/ +type V1SafesIncomingTransfersListParams struct { + + /* From. + + _from + */ + From *string + + // Address. + Address string + + /* BlockNumber. + + block_number + */ + BlockNumber *string + + /* BlockNumberGt. + + block_number__gt + */ + BlockNumberGt *string + + /* BlockNumberLt. + + block_number__lt + */ + BlockNumberLt *string + + /* Erc20. + + erc20 + */ + Erc20 *string + + /* Erc721. + + erc721 + */ + Erc721 *string + + /* Ether. + + ether + */ + Ether *string + + /* ExecutionDateGt. + + execution_date__gt + */ + ExecutionDateGt *string + + /* ExecutionDateGte. + + execution_date__gte + */ + ExecutionDateGte *string + + /* ExecutionDateLt. + + execution_date__lt + */ + ExecutionDateLt *string + + /* ExecutionDateLte. + + execution_date__lte + */ + ExecutionDateLte *string + + /* Limit. + + Number of results to return per page. + */ + Limit *int64 + + /* Offset. + + The initial index from which to return the results. + */ + Offset *int64 + + /* To. + + to + */ + To *string + + /* TokenAddress. + + token_address + */ + TokenAddress *string + + /* TransactionHash. + + transaction_hash + */ + TransactionHash *string + + /* Value. + + value + */ + Value *string + + /* ValueGt. + + value__gt + */ + ValueGt *string + + /* ValueLt. + + value__lt + */ + ValueLt *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 safes incoming transfers list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesIncomingTransfersListParams) WithDefaults() *V1SafesIncomingTransfersListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 safes incoming transfers list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesIncomingTransfersListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithTimeout(timeout time.Duration) *V1SafesIncomingTransfersListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithContext(ctx context.Context) *V1SafesIncomingTransfersListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithHTTPClient(client *http.Client) *V1SafesIncomingTransfersListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFrom adds the from to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithFrom(from *string) *V1SafesIncomingTransfersListParams { + o.SetFrom(from) + return o +} + +// SetFrom adds the from to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetFrom(from *string) { + o.From = from +} + +// WithAddress adds the address to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithAddress(address string) *V1SafesIncomingTransfersListParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetAddress(address string) { + o.Address = address +} + +// WithBlockNumber adds the blockNumber to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithBlockNumber(blockNumber *string) *V1SafesIncomingTransfersListParams { + o.SetBlockNumber(blockNumber) + return o +} + +// SetBlockNumber adds the blockNumber to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetBlockNumber(blockNumber *string) { + o.BlockNumber = blockNumber +} + +// WithBlockNumberGt adds the blockNumberGt to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithBlockNumberGt(blockNumberGt *string) *V1SafesIncomingTransfersListParams { + o.SetBlockNumberGt(blockNumberGt) + return o +} + +// SetBlockNumberGt adds the blockNumberGt to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetBlockNumberGt(blockNumberGt *string) { + o.BlockNumberGt = blockNumberGt +} + +// WithBlockNumberLt adds the blockNumberLt to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithBlockNumberLt(blockNumberLt *string) *V1SafesIncomingTransfersListParams { + o.SetBlockNumberLt(blockNumberLt) + return o +} + +// SetBlockNumberLt adds the blockNumberLt to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetBlockNumberLt(blockNumberLt *string) { + o.BlockNumberLt = blockNumberLt +} + +// WithErc20 adds the erc20 to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithErc20(erc20 *string) *V1SafesIncomingTransfersListParams { + o.SetErc20(erc20) + return o +} + +// SetErc20 adds the erc20 to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetErc20(erc20 *string) { + o.Erc20 = erc20 +} + +// WithErc721 adds the erc721 to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithErc721(erc721 *string) *V1SafesIncomingTransfersListParams { + o.SetErc721(erc721) + return o +} + +// SetErc721 adds the erc721 to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetErc721(erc721 *string) { + o.Erc721 = erc721 +} + +// WithEther adds the ether to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithEther(ether *string) *V1SafesIncomingTransfersListParams { + o.SetEther(ether) + return o +} + +// SetEther adds the ether to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetEther(ether *string) { + o.Ether = ether +} + +// WithExecutionDateGt adds the executionDateGt to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithExecutionDateGt(executionDateGt *string) *V1SafesIncomingTransfersListParams { + o.SetExecutionDateGt(executionDateGt) + return o +} + +// SetExecutionDateGt adds the executionDateGt to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetExecutionDateGt(executionDateGt *string) { + o.ExecutionDateGt = executionDateGt +} + +// WithExecutionDateGte adds the executionDateGte to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithExecutionDateGte(executionDateGte *string) *V1SafesIncomingTransfersListParams { + o.SetExecutionDateGte(executionDateGte) + return o +} + +// SetExecutionDateGte adds the executionDateGte to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetExecutionDateGte(executionDateGte *string) { + o.ExecutionDateGte = executionDateGte +} + +// WithExecutionDateLt adds the executionDateLt to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithExecutionDateLt(executionDateLt *string) *V1SafesIncomingTransfersListParams { + o.SetExecutionDateLt(executionDateLt) + return o +} + +// SetExecutionDateLt adds the executionDateLt to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetExecutionDateLt(executionDateLt *string) { + o.ExecutionDateLt = executionDateLt +} + +// WithExecutionDateLte adds the executionDateLte to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithExecutionDateLte(executionDateLte *string) *V1SafesIncomingTransfersListParams { + o.SetExecutionDateLte(executionDateLte) + return o +} + +// SetExecutionDateLte adds the executionDateLte to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetExecutionDateLte(executionDateLte *string) { + o.ExecutionDateLte = executionDateLte +} + +// WithLimit adds the limit to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithLimit(limit *int64) *V1SafesIncomingTransfersListParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithOffset(offset *int64) *V1SafesIncomingTransfersListParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithTo adds the to to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithTo(to *string) *V1SafesIncomingTransfersListParams { + o.SetTo(to) + return o +} + +// SetTo adds the to to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetTo(to *string) { + o.To = to +} + +// WithTokenAddress adds the tokenAddress to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithTokenAddress(tokenAddress *string) *V1SafesIncomingTransfersListParams { + o.SetTokenAddress(tokenAddress) + return o +} + +// SetTokenAddress adds the tokenAddress to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetTokenAddress(tokenAddress *string) { + o.TokenAddress = tokenAddress +} + +// WithTransactionHash adds the transactionHash to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithTransactionHash(transactionHash *string) *V1SafesIncomingTransfersListParams { + o.SetTransactionHash(transactionHash) + return o +} + +// SetTransactionHash adds the transactionHash to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetTransactionHash(transactionHash *string) { + o.TransactionHash = transactionHash +} + +// WithValue adds the value to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithValue(value *string) *V1SafesIncomingTransfersListParams { + o.SetValue(value) + return o +} + +// SetValue adds the value to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetValue(value *string) { + o.Value = value +} + +// WithValueGt adds the valueGt to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithValueGt(valueGt *string) *V1SafesIncomingTransfersListParams { + o.SetValueGt(valueGt) + return o +} + +// SetValueGt adds the valueGt to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetValueGt(valueGt *string) { + o.ValueGt = valueGt +} + +// WithValueLt adds the valueLt to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) WithValueLt(valueLt *string) *V1SafesIncomingTransfersListParams { + o.SetValueLt(valueLt) + return o +} + +// SetValueLt adds the valueLt to the v1 safes incoming transfers list params +func (o *V1SafesIncomingTransfersListParams) SetValueLt(valueLt *string) { + o.ValueLt = valueLt +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SafesIncomingTransfersListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.From != nil { + + // query param _from + var qrFrom string + + if o.From != nil { + qrFrom = *o.From + } + qFrom := qrFrom + if qFrom != "" { + + if err := r.SetQueryParam("_from", qFrom); err != nil { + return err + } + } + } + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + + if o.BlockNumber != nil { + + // query param block_number + var qrBlockNumber string + + if o.BlockNumber != nil { + qrBlockNumber = *o.BlockNumber + } + qBlockNumber := qrBlockNumber + if qBlockNumber != "" { + + if err := r.SetQueryParam("block_number", qBlockNumber); err != nil { + return err + } + } + } + + if o.BlockNumberGt != nil { + + // query param block_number__gt + var qrBlockNumberGt string + + if o.BlockNumberGt != nil { + qrBlockNumberGt = *o.BlockNumberGt + } + qBlockNumberGt := qrBlockNumberGt + if qBlockNumberGt != "" { + + if err := r.SetQueryParam("block_number__gt", qBlockNumberGt); err != nil { + return err + } + } + } + + if o.BlockNumberLt != nil { + + // query param block_number__lt + var qrBlockNumberLt string + + if o.BlockNumberLt != nil { + qrBlockNumberLt = *o.BlockNumberLt + } + qBlockNumberLt := qrBlockNumberLt + if qBlockNumberLt != "" { + + if err := r.SetQueryParam("block_number__lt", qBlockNumberLt); err != nil { + return err + } + } + } + + if o.Erc20 != nil { + + // query param erc20 + var qrErc20 string + + if o.Erc20 != nil { + qrErc20 = *o.Erc20 + } + qErc20 := qrErc20 + if qErc20 != "" { + + if err := r.SetQueryParam("erc20", qErc20); err != nil { + return err + } + } + } + + if o.Erc721 != nil { + + // query param erc721 + var qrErc721 string + + if o.Erc721 != nil { + qrErc721 = *o.Erc721 + } + qErc721 := qrErc721 + if qErc721 != "" { + + if err := r.SetQueryParam("erc721", qErc721); err != nil { + return err + } + } + } + + if o.Ether != nil { + + // query param ether + var qrEther string + + if o.Ether != nil { + qrEther = *o.Ether + } + qEther := qrEther + if qEther != "" { + + if err := r.SetQueryParam("ether", qEther); err != nil { + return err + } + } + } + + if o.ExecutionDateGt != nil { + + // query param execution_date__gt + var qrExecutionDateGt string + + if o.ExecutionDateGt != nil { + qrExecutionDateGt = *o.ExecutionDateGt + } + qExecutionDateGt := qrExecutionDateGt + if qExecutionDateGt != "" { + + if err := r.SetQueryParam("execution_date__gt", qExecutionDateGt); err != nil { + return err + } + } + } + + if o.ExecutionDateGte != nil { + + // query param execution_date__gte + var qrExecutionDateGte string + + if o.ExecutionDateGte != nil { + qrExecutionDateGte = *o.ExecutionDateGte + } + qExecutionDateGte := qrExecutionDateGte + if qExecutionDateGte != "" { + + if err := r.SetQueryParam("execution_date__gte", qExecutionDateGte); err != nil { + return err + } + } + } + + if o.ExecutionDateLt != nil { + + // query param execution_date__lt + var qrExecutionDateLt string + + if o.ExecutionDateLt != nil { + qrExecutionDateLt = *o.ExecutionDateLt + } + qExecutionDateLt := qrExecutionDateLt + if qExecutionDateLt != "" { + + if err := r.SetQueryParam("execution_date__lt", qExecutionDateLt); err != nil { + return err + } + } + } + + if o.ExecutionDateLte != nil { + + // query param execution_date__lte + var qrExecutionDateLte string + + if o.ExecutionDateLte != nil { + qrExecutionDateLte = *o.ExecutionDateLte + } + qExecutionDateLte := qrExecutionDateLte + if qExecutionDateLte != "" { + + if err := r.SetQueryParam("execution_date__lte", qExecutionDateLte); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.To != nil { + + // query param to + var qrTo string + + if o.To != nil { + qrTo = *o.To + } + qTo := qrTo + if qTo != "" { + + if err := r.SetQueryParam("to", qTo); err != nil { + return err + } + } + } + + if o.TokenAddress != nil { + + // query param token_address + var qrTokenAddress string + + if o.TokenAddress != nil { + qrTokenAddress = *o.TokenAddress + } + qTokenAddress := qrTokenAddress + if qTokenAddress != "" { + + if err := r.SetQueryParam("token_address", qTokenAddress); err != nil { + return err + } + } + } + + if o.TransactionHash != nil { + + // query param transaction_hash + var qrTransactionHash string + + if o.TransactionHash != nil { + qrTransactionHash = *o.TransactionHash + } + qTransactionHash := qrTransactionHash + if qTransactionHash != "" { + + if err := r.SetQueryParam("transaction_hash", qTransactionHash); err != nil { + return err + } + } + } + + if o.Value != nil { + + // query param value + var qrValue string + + if o.Value != nil { + qrValue = *o.Value + } + qValue := qrValue + if qValue != "" { + + if err := r.SetQueryParam("value", qValue); err != nil { + return err + } + } + } + + if o.ValueGt != nil { + + // query param value__gt + var qrValueGt string + + if o.ValueGt != nil { + qrValueGt = *o.ValueGt + } + qValueGt := qrValueGt + if qValueGt != "" { + + if err := r.SetQueryParam("value__gt", qValueGt); err != nil { + return err + } + } + } + + if o.ValueLt != nil { + + // query param value__lt + var qrValueLt string + + if o.ValueLt != nil { + qrValueLt = *o.ValueLt + } + qValueLt := qrValueLt + if qValueLt != "" { + + if err := r.SetQueryParam("value__lt", qValueLt); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/transactions/v1_safes_incoming_transfers_list_responses.go b/utils/safe_api/client/transactions/v1_safes_incoming_transfers_list_responses.go new file mode 100644 index 0000000..d52de3e --- /dev/null +++ b/utils/safe_api/client/transactions/v1_safes_incoming_transfers_list_responses.go @@ -0,0 +1,166 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1SafesIncomingTransfersListReader is a Reader for the V1SafesIncomingTransfersList structure. +type V1SafesIncomingTransfersListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SafesIncomingTransfersListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1SafesIncomingTransfersListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 422: + result := NewV1SafesIncomingTransfersListUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/safes/{address}/incoming-transfers/] v1_safes_incoming-transfers_list", response, response.Code()) + } +} + +// NewV1SafesIncomingTransfersListOK creates a V1SafesIncomingTransfersListOK with default headers values +func NewV1SafesIncomingTransfersListOK() *V1SafesIncomingTransfersListOK { + return &V1SafesIncomingTransfersListOK{} +} + +/* +V1SafesIncomingTransfersListOK describes a response with status code 200, with default header values. + +V1SafesIncomingTransfersListOK v1 safes incoming transfers list o k +*/ +type V1SafesIncomingTransfersListOK struct { + Payload []*models.TransferWithTokenInfoResponse +} + +// IsSuccess returns true when this v1 safes incoming transfers list o k response has a 2xx status code +func (o *V1SafesIncomingTransfersListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 safes incoming transfers list o k response has a 3xx status code +func (o *V1SafesIncomingTransfersListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes incoming transfers list o k response has a 4xx status code +func (o *V1SafesIncomingTransfersListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 safes incoming transfers list o k response has a 5xx status code +func (o *V1SafesIncomingTransfersListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes incoming transfers list o k response a status code equal to that given +func (o *V1SafesIncomingTransfersListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 safes incoming transfers list o k response +func (o *V1SafesIncomingTransfersListOK) Code() int { + return 200 +} + +func (o *V1SafesIncomingTransfersListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/incoming-transfers/][%d] v1SafesIncomingTransfersListOK %s", 200, payload) +} + +func (o *V1SafesIncomingTransfersListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/incoming-transfers/][%d] v1SafesIncomingTransfersListOK %s", 200, payload) +} + +func (o *V1SafesIncomingTransfersListOK) GetPayload() []*models.TransferWithTokenInfoResponse { + return o.Payload +} + +func (o *V1SafesIncomingTransfersListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SafesIncomingTransfersListUnprocessableEntity creates a V1SafesIncomingTransfersListUnprocessableEntity with default headers values +func NewV1SafesIncomingTransfersListUnprocessableEntity() *V1SafesIncomingTransfersListUnprocessableEntity { + return &V1SafesIncomingTransfersListUnprocessableEntity{} +} + +/* +V1SafesIncomingTransfersListUnprocessableEntity describes a response with status code 422, with default header values. + +Safe address checksum not valid +*/ +type V1SafesIncomingTransfersListUnprocessableEntity struct { +} + +// IsSuccess returns true when this v1 safes incoming transfers list unprocessable entity response has a 2xx status code +func (o *V1SafesIncomingTransfersListUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes incoming transfers list unprocessable entity response has a 3xx status code +func (o *V1SafesIncomingTransfersListUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes incoming transfers list unprocessable entity response has a 4xx status code +func (o *V1SafesIncomingTransfersListUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes incoming transfers list unprocessable entity response has a 5xx status code +func (o *V1SafesIncomingTransfersListUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes incoming transfers list unprocessable entity response a status code equal to that given +func (o *V1SafesIncomingTransfersListUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 safes incoming transfers list unprocessable entity response +func (o *V1SafesIncomingTransfersListUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1SafesIncomingTransfersListUnprocessableEntity) Error() string { + return fmt.Sprintf("[GET /v1/safes/{address}/incoming-transfers/][%d] v1SafesIncomingTransfersListUnprocessableEntity", 422) +} + +func (o *V1SafesIncomingTransfersListUnprocessableEntity) String() string { + return fmt.Sprintf("[GET /v1/safes/{address}/incoming-transfers/][%d] v1SafesIncomingTransfersListUnprocessableEntity", 422) +} + +func (o *V1SafesIncomingTransfersListUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/transactions/v1_safes_module_transactions_list_parameters.go b/utils/safe_api/client/transactions/v1_safes_module_transactions_list_parameters.go new file mode 100644 index 0000000..2f5e6df --- /dev/null +++ b/utils/safe_api/client/transactions/v1_safes_module_transactions_list_parameters.go @@ -0,0 +1,557 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewV1SafesModuleTransactionsListParams creates a new V1SafesModuleTransactionsListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SafesModuleTransactionsListParams() *V1SafesModuleTransactionsListParams { + return &V1SafesModuleTransactionsListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SafesModuleTransactionsListParamsWithTimeout creates a new V1SafesModuleTransactionsListParams object +// with the ability to set a timeout on a request. +func NewV1SafesModuleTransactionsListParamsWithTimeout(timeout time.Duration) *V1SafesModuleTransactionsListParams { + return &V1SafesModuleTransactionsListParams{ + timeout: timeout, + } +} + +// NewV1SafesModuleTransactionsListParamsWithContext creates a new V1SafesModuleTransactionsListParams object +// with the ability to set a context for a request. +func NewV1SafesModuleTransactionsListParamsWithContext(ctx context.Context) *V1SafesModuleTransactionsListParams { + return &V1SafesModuleTransactionsListParams{ + Context: ctx, + } +} + +// NewV1SafesModuleTransactionsListParamsWithHTTPClient creates a new V1SafesModuleTransactionsListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SafesModuleTransactionsListParamsWithHTTPClient(client *http.Client) *V1SafesModuleTransactionsListParams { + return &V1SafesModuleTransactionsListParams{ + HTTPClient: client, + } +} + +/* +V1SafesModuleTransactionsListParams contains all the parameters to send to the API endpoint + + for the v1 safes module transactions list operation. + + Typically these are written to a http.Request. +*/ +type V1SafesModuleTransactionsListParams struct { + + // Address. + Address string + + /* BlockNumber. + + block_number + */ + BlockNumber *string + + /* BlockNumberGt. + + block_number__gt + */ + BlockNumberGt *string + + /* BlockNumberLt. + + block_number__lt + */ + BlockNumberLt *string + + /* Failed. + + failed + */ + Failed *string + + /* Limit. + + Number of results to return per page. + */ + Limit *int64 + + /* Module. + + module + */ + Module *string + + /* Offset. + + The initial index from which to return the results. + */ + Offset *int64 + + /* Operation. + + operation + */ + Operation *string + + /* Ordering. + + Which field to use when ordering the results. + */ + Ordering *string + + /* Safe. + + safe + */ + Safe *string + + /* To. + + to + */ + To *string + + /* TransactionHash. + + transaction_hash + */ + TransactionHash *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 safes module transactions list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesModuleTransactionsListParams) WithDefaults() *V1SafesModuleTransactionsListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 safes module transactions list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesModuleTransactionsListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) WithTimeout(timeout time.Duration) *V1SafesModuleTransactionsListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) WithContext(ctx context.Context) *V1SafesModuleTransactionsListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) WithHTTPClient(client *http.Client) *V1SafesModuleTransactionsListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) WithAddress(address string) *V1SafesModuleTransactionsListParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) SetAddress(address string) { + o.Address = address +} + +// WithBlockNumber adds the blockNumber to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) WithBlockNumber(blockNumber *string) *V1SafesModuleTransactionsListParams { + o.SetBlockNumber(blockNumber) + return o +} + +// SetBlockNumber adds the blockNumber to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) SetBlockNumber(blockNumber *string) { + o.BlockNumber = blockNumber +} + +// WithBlockNumberGt adds the blockNumberGt to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) WithBlockNumberGt(blockNumberGt *string) *V1SafesModuleTransactionsListParams { + o.SetBlockNumberGt(blockNumberGt) + return o +} + +// SetBlockNumberGt adds the blockNumberGt to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) SetBlockNumberGt(blockNumberGt *string) { + o.BlockNumberGt = blockNumberGt +} + +// WithBlockNumberLt adds the blockNumberLt to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) WithBlockNumberLt(blockNumberLt *string) *V1SafesModuleTransactionsListParams { + o.SetBlockNumberLt(blockNumberLt) + return o +} + +// SetBlockNumberLt adds the blockNumberLt to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) SetBlockNumberLt(blockNumberLt *string) { + o.BlockNumberLt = blockNumberLt +} + +// WithFailed adds the failed to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) WithFailed(failed *string) *V1SafesModuleTransactionsListParams { + o.SetFailed(failed) + return o +} + +// SetFailed adds the failed to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) SetFailed(failed *string) { + o.Failed = failed +} + +// WithLimit adds the limit to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) WithLimit(limit *int64) *V1SafesModuleTransactionsListParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithModule adds the module to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) WithModule(module *string) *V1SafesModuleTransactionsListParams { + o.SetModule(module) + return o +} + +// SetModule adds the module to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) SetModule(module *string) { + o.Module = module +} + +// WithOffset adds the offset to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) WithOffset(offset *int64) *V1SafesModuleTransactionsListParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithOperation adds the operation to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) WithOperation(operation *string) *V1SafesModuleTransactionsListParams { + o.SetOperation(operation) + return o +} + +// SetOperation adds the operation to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) SetOperation(operation *string) { + o.Operation = operation +} + +// WithOrdering adds the ordering to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) WithOrdering(ordering *string) *V1SafesModuleTransactionsListParams { + o.SetOrdering(ordering) + return o +} + +// SetOrdering adds the ordering to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) SetOrdering(ordering *string) { + o.Ordering = ordering +} + +// WithSafe adds the safe to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) WithSafe(safe *string) *V1SafesModuleTransactionsListParams { + o.SetSafe(safe) + return o +} + +// SetSafe adds the safe to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) SetSafe(safe *string) { + o.Safe = safe +} + +// WithTo adds the to to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) WithTo(to *string) *V1SafesModuleTransactionsListParams { + o.SetTo(to) + return o +} + +// SetTo adds the to to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) SetTo(to *string) { + o.To = to +} + +// WithTransactionHash adds the transactionHash to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) WithTransactionHash(transactionHash *string) *V1SafesModuleTransactionsListParams { + o.SetTransactionHash(transactionHash) + return o +} + +// SetTransactionHash adds the transactionHash to the v1 safes module transactions list params +func (o *V1SafesModuleTransactionsListParams) SetTransactionHash(transactionHash *string) { + o.TransactionHash = transactionHash +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SafesModuleTransactionsListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + + if o.BlockNumber != nil { + + // query param block_number + var qrBlockNumber string + + if o.BlockNumber != nil { + qrBlockNumber = *o.BlockNumber + } + qBlockNumber := qrBlockNumber + if qBlockNumber != "" { + + if err := r.SetQueryParam("block_number", qBlockNumber); err != nil { + return err + } + } + } + + if o.BlockNumberGt != nil { + + // query param block_number__gt + var qrBlockNumberGt string + + if o.BlockNumberGt != nil { + qrBlockNumberGt = *o.BlockNumberGt + } + qBlockNumberGt := qrBlockNumberGt + if qBlockNumberGt != "" { + + if err := r.SetQueryParam("block_number__gt", qBlockNumberGt); err != nil { + return err + } + } + } + + if o.BlockNumberLt != nil { + + // query param block_number__lt + var qrBlockNumberLt string + + if o.BlockNumberLt != nil { + qrBlockNumberLt = *o.BlockNumberLt + } + qBlockNumberLt := qrBlockNumberLt + if qBlockNumberLt != "" { + + if err := r.SetQueryParam("block_number__lt", qBlockNumberLt); err != nil { + return err + } + } + } + + if o.Failed != nil { + + // query param failed + var qrFailed string + + if o.Failed != nil { + qrFailed = *o.Failed + } + qFailed := qrFailed + if qFailed != "" { + + if err := r.SetQueryParam("failed", qFailed); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Module != nil { + + // query param module + var qrModule string + + if o.Module != nil { + qrModule = *o.Module + } + qModule := qrModule + if qModule != "" { + + if err := r.SetQueryParam("module", qModule); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Operation != nil { + + // query param operation + var qrOperation string + + if o.Operation != nil { + qrOperation = *o.Operation + } + qOperation := qrOperation + if qOperation != "" { + + if err := r.SetQueryParam("operation", qOperation); err != nil { + return err + } + } + } + + if o.Ordering != nil { + + // query param ordering + var qrOrdering string + + if o.Ordering != nil { + qrOrdering = *o.Ordering + } + qOrdering := qrOrdering + if qOrdering != "" { + + if err := r.SetQueryParam("ordering", qOrdering); err != nil { + return err + } + } + } + + if o.Safe != nil { + + // query param safe + var qrSafe string + + if o.Safe != nil { + qrSafe = *o.Safe + } + qSafe := qrSafe + if qSafe != "" { + + if err := r.SetQueryParam("safe", qSafe); err != nil { + return err + } + } + } + + if o.To != nil { + + // query param to + var qrTo string + + if o.To != nil { + qrTo = *o.To + } + qTo := qrTo + if qTo != "" { + + if err := r.SetQueryParam("to", qTo); err != nil { + return err + } + } + } + + if o.TransactionHash != nil { + + // query param transaction_hash + var qrTransactionHash string + + if o.TransactionHash != nil { + qrTransactionHash = *o.TransactionHash + } + qTransactionHash := qrTransactionHash + if qTransactionHash != "" { + + if err := r.SetQueryParam("transaction_hash", qTransactionHash); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/transactions/v1_safes_module_transactions_list_responses.go b/utils/safe_api/client/transactions/v1_safes_module_transactions_list_responses.go new file mode 100644 index 0000000..88863cd --- /dev/null +++ b/utils/safe_api/client/transactions/v1_safes_module_transactions_list_responses.go @@ -0,0 +1,401 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + models "omni-balance/utils/safe_api" +) + +// V1SafesModuleTransactionsListReader is a Reader for the V1SafesModuleTransactionsList structure. +type V1SafesModuleTransactionsListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SafesModuleTransactionsListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1SafesModuleTransactionsListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1SafesModuleTransactionsListBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 422: + result := NewV1SafesModuleTransactionsListUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/safes/{address}/module-transactions/] v1_safes_module-transactions_list", response, response.Code()) + } +} + +// NewV1SafesModuleTransactionsListOK creates a V1SafesModuleTransactionsListOK with default headers values +func NewV1SafesModuleTransactionsListOK() *V1SafesModuleTransactionsListOK { + return &V1SafesModuleTransactionsListOK{} +} + +/* +V1SafesModuleTransactionsListOK describes a response with status code 200, with default header values. + +V1SafesModuleTransactionsListOK v1 safes module transactions list o k +*/ +type V1SafesModuleTransactionsListOK struct { + Payload *V1SafesModuleTransactionsListOKBody +} + +// IsSuccess returns true when this v1 safes module transactions list o k response has a 2xx status code +func (o *V1SafesModuleTransactionsListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 safes module transactions list o k response has a 3xx status code +func (o *V1SafesModuleTransactionsListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes module transactions list o k response has a 4xx status code +func (o *V1SafesModuleTransactionsListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 safes module transactions list o k response has a 5xx status code +func (o *V1SafesModuleTransactionsListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes module transactions list o k response a status code equal to that given +func (o *V1SafesModuleTransactionsListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 safes module transactions list o k response +func (o *V1SafesModuleTransactionsListOK) Code() int { + return 200 +} + +func (o *V1SafesModuleTransactionsListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/module-transactions/][%d] v1SafesModuleTransactionsListOK %s", 200, payload) +} + +func (o *V1SafesModuleTransactionsListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/module-transactions/][%d] v1SafesModuleTransactionsListOK %s", 200, payload) +} + +func (o *V1SafesModuleTransactionsListOK) GetPayload() *V1SafesModuleTransactionsListOKBody { + return o.Payload +} + +func (o *V1SafesModuleTransactionsListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(V1SafesModuleTransactionsListOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SafesModuleTransactionsListBadRequest creates a V1SafesModuleTransactionsListBadRequest with default headers values +func NewV1SafesModuleTransactionsListBadRequest() *V1SafesModuleTransactionsListBadRequest { + return &V1SafesModuleTransactionsListBadRequest{} +} + +/* +V1SafesModuleTransactionsListBadRequest describes a response with status code 400, with default header values. + +Invalid data +*/ +type V1SafesModuleTransactionsListBadRequest struct { +} + +// IsSuccess returns true when this v1 safes module transactions list bad request response has a 2xx status code +func (o *V1SafesModuleTransactionsListBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes module transactions list bad request response has a 3xx status code +func (o *V1SafesModuleTransactionsListBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes module transactions list bad request response has a 4xx status code +func (o *V1SafesModuleTransactionsListBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes module transactions list bad request response has a 5xx status code +func (o *V1SafesModuleTransactionsListBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes module transactions list bad request response a status code equal to that given +func (o *V1SafesModuleTransactionsListBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 safes module transactions list bad request response +func (o *V1SafesModuleTransactionsListBadRequest) Code() int { + return 400 +} + +func (o *V1SafesModuleTransactionsListBadRequest) Error() string { + return fmt.Sprintf("[GET /v1/safes/{address}/module-transactions/][%d] v1SafesModuleTransactionsListBadRequest", 400) +} + +func (o *V1SafesModuleTransactionsListBadRequest) String() string { + return fmt.Sprintf("[GET /v1/safes/{address}/module-transactions/][%d] v1SafesModuleTransactionsListBadRequest", 400) +} + +func (o *V1SafesModuleTransactionsListBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1SafesModuleTransactionsListUnprocessableEntity creates a V1SafesModuleTransactionsListUnprocessableEntity with default headers values +func NewV1SafesModuleTransactionsListUnprocessableEntity() *V1SafesModuleTransactionsListUnprocessableEntity { + return &V1SafesModuleTransactionsListUnprocessableEntity{} +} + +/* +V1SafesModuleTransactionsListUnprocessableEntity describes a response with status code 422, with default header values. + +Invalid ethereum address +*/ +type V1SafesModuleTransactionsListUnprocessableEntity struct { +} + +// IsSuccess returns true when this v1 safes module transactions list unprocessable entity response has a 2xx status code +func (o *V1SafesModuleTransactionsListUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes module transactions list unprocessable entity response has a 3xx status code +func (o *V1SafesModuleTransactionsListUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes module transactions list unprocessable entity response has a 4xx status code +func (o *V1SafesModuleTransactionsListUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes module transactions list unprocessable entity response has a 5xx status code +func (o *V1SafesModuleTransactionsListUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes module transactions list unprocessable entity response a status code equal to that given +func (o *V1SafesModuleTransactionsListUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 safes module transactions list unprocessable entity response +func (o *V1SafesModuleTransactionsListUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1SafesModuleTransactionsListUnprocessableEntity) Error() string { + return fmt.Sprintf("[GET /v1/safes/{address}/module-transactions/][%d] v1SafesModuleTransactionsListUnprocessableEntity", 422) +} + +func (o *V1SafesModuleTransactionsListUnprocessableEntity) String() string { + return fmt.Sprintf("[GET /v1/safes/{address}/module-transactions/][%d] v1SafesModuleTransactionsListUnprocessableEntity", 422) +} + +func (o *V1SafesModuleTransactionsListUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +/* +V1SafesModuleTransactionsListOKBody v1 safes module transactions list o k body +swagger:model V1SafesModuleTransactionsListOKBody +*/ +type V1SafesModuleTransactionsListOKBody struct { + + // count + // Required: true + Count *int64 `json:"count"` + + // next + // Format: uri + Next *strfmt.URI `json:"next,omitempty"` + + // previous + // Format: uri + Previous *strfmt.URI `json:"previous,omitempty"` + + // results + // Required: true + Results []*models.SafeModuleTransactionResponse `json:"results"` +} + +// Validate validates this v1 safes module transactions list o k body +func (o *V1SafesModuleTransactionsListOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateCount(formats); err != nil { + res = append(res, err) + } + + if err := o.validateNext(formats); err != nil { + res = append(res, err) + } + + if err := o.validatePrevious(formats); err != nil { + res = append(res, err) + } + + if err := o.validateResults(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V1SafesModuleTransactionsListOKBody) validateCount(formats strfmt.Registry) error { + + if err := validate.Required("v1SafesModuleTransactionsListOK"+"."+"count", "body", o.Count); err != nil { + return err + } + + return nil +} + +func (o *V1SafesModuleTransactionsListOKBody) validateNext(formats strfmt.Registry) error { + if swag.IsZero(o.Next) { // not required + return nil + } + + if err := validate.FormatOf("v1SafesModuleTransactionsListOK"+"."+"next", "body", "uri", o.Next.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V1SafesModuleTransactionsListOKBody) validatePrevious(formats strfmt.Registry) error { + if swag.IsZero(o.Previous) { // not required + return nil + } + + if err := validate.FormatOf("v1SafesModuleTransactionsListOK"+"."+"previous", "body", "uri", o.Previous.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V1SafesModuleTransactionsListOKBody) validateResults(formats strfmt.Registry) error { + + if err := validate.Required("v1SafesModuleTransactionsListOK"+"."+"results", "body", o.Results); err != nil { + return err + } + + for i := 0; i < len(o.Results); i++ { + if swag.IsZero(o.Results[i]) { // not required + continue + } + + if o.Results[i] != nil { + if err := o.Results[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v1SafesModuleTransactionsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v1SafesModuleTransactionsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this v1 safes module transactions list o k body based on the context it is used +func (o *V1SafesModuleTransactionsListOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResults(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V1SafesModuleTransactionsListOKBody) contextValidateResults(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Results); i++ { + + if o.Results[i] != nil { + + if swag.IsZero(o.Results[i]) { // not required + return nil + } + + if err := o.Results[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v1SafesModuleTransactionsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v1SafesModuleTransactionsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *V1SafesModuleTransactionsListOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *V1SafesModuleTransactionsListOKBody) UnmarshalBinary(b []byte) error { + var res V1SafesModuleTransactionsListOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/utils/safe_api/client/transactions/v1_safes_multisig_transactions_create_parameters.go b/utils/safe_api/client/transactions/v1_safes_multisig_transactions_create_parameters.go new file mode 100644 index 0000000..877e2c9 --- /dev/null +++ b/utils/safe_api/client/transactions/v1_safes_multisig_transactions_create_parameters.go @@ -0,0 +1,169 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// NewV1SafesMultisigTransactionsCreateParams creates a new V1SafesMultisigTransactionsCreateParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SafesMultisigTransactionsCreateParams() *V1SafesMultisigTransactionsCreateParams { + return &V1SafesMultisigTransactionsCreateParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SafesMultisigTransactionsCreateParamsWithTimeout creates a new V1SafesMultisigTransactionsCreateParams object +// with the ability to set a timeout on a request. +func NewV1SafesMultisigTransactionsCreateParamsWithTimeout(timeout time.Duration) *V1SafesMultisigTransactionsCreateParams { + return &V1SafesMultisigTransactionsCreateParams{ + timeout: timeout, + } +} + +// NewV1SafesMultisigTransactionsCreateParamsWithContext creates a new V1SafesMultisigTransactionsCreateParams object +// with the ability to set a context for a request. +func NewV1SafesMultisigTransactionsCreateParamsWithContext(ctx context.Context) *V1SafesMultisigTransactionsCreateParams { + return &V1SafesMultisigTransactionsCreateParams{ + Context: ctx, + } +} + +// NewV1SafesMultisigTransactionsCreateParamsWithHTTPClient creates a new V1SafesMultisigTransactionsCreateParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SafesMultisigTransactionsCreateParamsWithHTTPClient(client *http.Client) *V1SafesMultisigTransactionsCreateParams { + return &V1SafesMultisigTransactionsCreateParams{ + HTTPClient: client, + } +} + +/* +V1SafesMultisigTransactionsCreateParams contains all the parameters to send to the API endpoint + + for the v1 safes multisig transactions create operation. + + Typically these are written to a http.Request. +*/ +type V1SafesMultisigTransactionsCreateParams struct { + + // Address. + Address string + + // Data. + Data *models.SafeMultisigTransaction + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 safes multisig transactions create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesMultisigTransactionsCreateParams) WithDefaults() *V1SafesMultisigTransactionsCreateParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 safes multisig transactions create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesMultisigTransactionsCreateParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 safes multisig transactions create params +func (o *V1SafesMultisigTransactionsCreateParams) WithTimeout(timeout time.Duration) *V1SafesMultisigTransactionsCreateParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 safes multisig transactions create params +func (o *V1SafesMultisigTransactionsCreateParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 safes multisig transactions create params +func (o *V1SafesMultisigTransactionsCreateParams) WithContext(ctx context.Context) *V1SafesMultisigTransactionsCreateParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 safes multisig transactions create params +func (o *V1SafesMultisigTransactionsCreateParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 safes multisig transactions create params +func (o *V1SafesMultisigTransactionsCreateParams) WithHTTPClient(client *http.Client) *V1SafesMultisigTransactionsCreateParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 safes multisig transactions create params +func (o *V1SafesMultisigTransactionsCreateParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 safes multisig transactions create params +func (o *V1SafesMultisigTransactionsCreateParams) WithAddress(address string) *V1SafesMultisigTransactionsCreateParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 safes multisig transactions create params +func (o *V1SafesMultisigTransactionsCreateParams) SetAddress(address string) { + o.Address = address +} + +// WithData adds the data to the v1 safes multisig transactions create params +func (o *V1SafesMultisigTransactionsCreateParams) WithData(data *models.SafeMultisigTransaction) *V1SafesMultisigTransactionsCreateParams { + o.SetData(data) + return o +} + +// SetData adds the data to the v1 safes multisig transactions create params +func (o *V1SafesMultisigTransactionsCreateParams) SetData(data *models.SafeMultisigTransaction) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SafesMultisigTransactionsCreateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/transactions/v1_safes_multisig_transactions_create_responses.go b/utils/safe_api/client/transactions/v1_safes_multisig_transactions_create_responses.go new file mode 100644 index 0000000..baf4872 --- /dev/null +++ b/utils/safe_api/client/transactions/v1_safes_multisig_transactions_create_responses.go @@ -0,0 +1,207 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// V1SafesMultisigTransactionsCreateReader is a Reader for the V1SafesMultisigTransactionsCreate structure. +type V1SafesMultisigTransactionsCreateReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SafesMultisigTransactionsCreateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 201: + result := NewV1SafesMultisigTransactionsCreateCreated() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + data, _ := io.ReadAll(response.Body()) + return nil, fmt.Errorf("unable to decode response body into error: %s", string(data)) + case 422: + data, _ := io.ReadAll(response.Body()) + return nil, fmt.Errorf("unable to decode response body into error: %s", string(data)) + default: + return nil, runtime.NewAPIError("[POST /v1/safes/{address}/multisig-transactions/] v1_safes_multisig-transactions_create", response, response.Code()) + } +} + +// NewV1SafesMultisigTransactionsCreateCreated creates a V1SafesMultisigTransactionsCreateCreated with default headers values +func NewV1SafesMultisigTransactionsCreateCreated() *V1SafesMultisigTransactionsCreateCreated { + return &V1SafesMultisigTransactionsCreateCreated{} +} + +/* +V1SafesMultisigTransactionsCreateCreated describes a response with status code 201, with default header values. + +Created or signature updated +*/ +type V1SafesMultisigTransactionsCreateCreated struct { +} + +// IsSuccess returns true when this v1 safes multisig transactions create created response has a 2xx status code +func (o *V1SafesMultisigTransactionsCreateCreated) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 safes multisig transactions create created response has a 3xx status code +func (o *V1SafesMultisigTransactionsCreateCreated) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes multisig transactions create created response has a 4xx status code +func (o *V1SafesMultisigTransactionsCreateCreated) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 safes multisig transactions create created response has a 5xx status code +func (o *V1SafesMultisigTransactionsCreateCreated) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes multisig transactions create created response a status code equal to that given +func (o *V1SafesMultisigTransactionsCreateCreated) IsCode(code int) bool { + return code == 201 +} + +// Code gets the status code for the v1 safes multisig transactions create created response +func (o *V1SafesMultisigTransactionsCreateCreated) Code() int { + return 201 +} + +func (o *V1SafesMultisigTransactionsCreateCreated) Error() string { + return fmt.Sprintf("[POST /v1/safes/{address}/multisig-transactions/][%d] v1SafesMultisigTransactionsCreateCreated", 201) +} + +func (o *V1SafesMultisigTransactionsCreateCreated) String() string { + return fmt.Sprintf("[POST /v1/safes/{address}/multisig-transactions/][%d] v1SafesMultisigTransactionsCreateCreated", 201) +} + +func (o *V1SafesMultisigTransactionsCreateCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1SafesMultisigTransactionsCreateBadRequest creates a V1SafesMultisigTransactionsCreateBadRequest with default headers values +func NewV1SafesMultisigTransactionsCreateBadRequest() *V1SafesMultisigTransactionsCreateBadRequest { + return &V1SafesMultisigTransactionsCreateBadRequest{} +} + +/* +V1SafesMultisigTransactionsCreateBadRequest describes a response with status code 400, with default header values. + +Invalid data +*/ +type V1SafesMultisigTransactionsCreateBadRequest struct { +} + +// IsSuccess returns true when this v1 safes multisig transactions create bad request response has a 2xx status code +func (o *V1SafesMultisigTransactionsCreateBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes multisig transactions create bad request response has a 3xx status code +func (o *V1SafesMultisigTransactionsCreateBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes multisig transactions create bad request response has a 4xx status code +func (o *V1SafesMultisigTransactionsCreateBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes multisig transactions create bad request response has a 5xx status code +func (o *V1SafesMultisigTransactionsCreateBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes multisig transactions create bad request response a status code equal to that given +func (o *V1SafesMultisigTransactionsCreateBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 safes multisig transactions create bad request response +func (o *V1SafesMultisigTransactionsCreateBadRequest) Code() int { + return 400 +} + +func (o *V1SafesMultisigTransactionsCreateBadRequest) Error() string { + return fmt.Sprintf("[POST /v1/safes/{address}/multisig-transactions/][%d] v1SafesMultisigTransactionsCreateBadRequest", 400) +} + +func (o *V1SafesMultisigTransactionsCreateBadRequest) String() string { + return fmt.Sprintf("[POST /v1/safes/{address}/multisig-transactions/][%d] v1SafesMultisigTransactionsCreateBadRequest", 400) +} + +func (o *V1SafesMultisigTransactionsCreateBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1SafesMultisigTransactionsCreateUnprocessableEntity creates a V1SafesMultisigTransactionsCreateUnprocessableEntity with default headers values +func NewV1SafesMultisigTransactionsCreateUnprocessableEntity() *V1SafesMultisigTransactionsCreateUnprocessableEntity { + return &V1SafesMultisigTransactionsCreateUnprocessableEntity{} +} + +/* +V1SafesMultisigTransactionsCreateUnprocessableEntity describes a response with status code 422, with default header values. + +Invalid ethereum address/User is not an owner/Invalid safeTxHash/Invalid signature/Nonce already executed/Sender is not an owner +*/ +type V1SafesMultisigTransactionsCreateUnprocessableEntity struct { +} + +// IsSuccess returns true when this v1 safes multisig transactions create unprocessable entity response has a 2xx status code +func (o *V1SafesMultisigTransactionsCreateUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes multisig transactions create unprocessable entity response has a 3xx status code +func (o *V1SafesMultisigTransactionsCreateUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes multisig transactions create unprocessable entity response has a 4xx status code +func (o *V1SafesMultisigTransactionsCreateUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes multisig transactions create unprocessable entity response has a 5xx status code +func (o *V1SafesMultisigTransactionsCreateUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes multisig transactions create unprocessable entity response a status code equal to that given +func (o *V1SafesMultisigTransactionsCreateUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 safes multisig transactions create unprocessable entity response +func (o *V1SafesMultisigTransactionsCreateUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1SafesMultisigTransactionsCreateUnprocessableEntity) Error() string { + return fmt.Sprintf("[POST /v1/safes/{address}/multisig-transactions/][%d] v1SafesMultisigTransactionsCreateUnprocessableEntity", 422) +} + +func (o *V1SafesMultisigTransactionsCreateUnprocessableEntity) String() string { + return fmt.Sprintf("[POST /v1/safes/{address}/multisig-transactions/][%d] v1SafesMultisigTransactionsCreateUnprocessableEntity", 422) +} + +func (o *V1SafesMultisigTransactionsCreateUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/transactions/v1_safes_multisig_transactions_estimations_create_parameters.go b/utils/safe_api/client/transactions/v1_safes_multisig_transactions_estimations_create_parameters.go new file mode 100644 index 0000000..8a067b1 --- /dev/null +++ b/utils/safe_api/client/transactions/v1_safes_multisig_transactions_estimations_create_parameters.go @@ -0,0 +1,169 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// NewV1SafesMultisigTransactionsEstimationsCreateParams creates a new V1SafesMultisigTransactionsEstimationsCreateParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SafesMultisigTransactionsEstimationsCreateParams() *V1SafesMultisigTransactionsEstimationsCreateParams { + return &V1SafesMultisigTransactionsEstimationsCreateParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SafesMultisigTransactionsEstimationsCreateParamsWithTimeout creates a new V1SafesMultisigTransactionsEstimationsCreateParams object +// with the ability to set a timeout on a request. +func NewV1SafesMultisigTransactionsEstimationsCreateParamsWithTimeout(timeout time.Duration) *V1SafesMultisigTransactionsEstimationsCreateParams { + return &V1SafesMultisigTransactionsEstimationsCreateParams{ + timeout: timeout, + } +} + +// NewV1SafesMultisigTransactionsEstimationsCreateParamsWithContext creates a new V1SafesMultisigTransactionsEstimationsCreateParams object +// with the ability to set a context for a request. +func NewV1SafesMultisigTransactionsEstimationsCreateParamsWithContext(ctx context.Context) *V1SafesMultisigTransactionsEstimationsCreateParams { + return &V1SafesMultisigTransactionsEstimationsCreateParams{ + Context: ctx, + } +} + +// NewV1SafesMultisigTransactionsEstimationsCreateParamsWithHTTPClient creates a new V1SafesMultisigTransactionsEstimationsCreateParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SafesMultisigTransactionsEstimationsCreateParamsWithHTTPClient(client *http.Client) *V1SafesMultisigTransactionsEstimationsCreateParams { + return &V1SafesMultisigTransactionsEstimationsCreateParams{ + HTTPClient: client, + } +} + +/* +V1SafesMultisigTransactionsEstimationsCreateParams contains all the parameters to send to the API endpoint + + for the v1 safes multisig transactions estimations create operation. + + Typically these are written to a http.Request. +*/ +type V1SafesMultisigTransactionsEstimationsCreateParams struct { + + // Address. + Address string + + // Data. + Data *models.SafeMultisigTransactionEstimate + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 safes multisig transactions estimations create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesMultisigTransactionsEstimationsCreateParams) WithDefaults() *V1SafesMultisigTransactionsEstimationsCreateParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 safes multisig transactions estimations create params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesMultisigTransactionsEstimationsCreateParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 safes multisig transactions estimations create params +func (o *V1SafesMultisigTransactionsEstimationsCreateParams) WithTimeout(timeout time.Duration) *V1SafesMultisigTransactionsEstimationsCreateParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 safes multisig transactions estimations create params +func (o *V1SafesMultisigTransactionsEstimationsCreateParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 safes multisig transactions estimations create params +func (o *V1SafesMultisigTransactionsEstimationsCreateParams) WithContext(ctx context.Context) *V1SafesMultisigTransactionsEstimationsCreateParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 safes multisig transactions estimations create params +func (o *V1SafesMultisigTransactionsEstimationsCreateParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 safes multisig transactions estimations create params +func (o *V1SafesMultisigTransactionsEstimationsCreateParams) WithHTTPClient(client *http.Client) *V1SafesMultisigTransactionsEstimationsCreateParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 safes multisig transactions estimations create params +func (o *V1SafesMultisigTransactionsEstimationsCreateParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 safes multisig transactions estimations create params +func (o *V1SafesMultisigTransactionsEstimationsCreateParams) WithAddress(address string) *V1SafesMultisigTransactionsEstimationsCreateParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 safes multisig transactions estimations create params +func (o *V1SafesMultisigTransactionsEstimationsCreateParams) SetAddress(address string) { + o.Address = address +} + +// WithData adds the data to the v1 safes multisig transactions estimations create params +func (o *V1SafesMultisigTransactionsEstimationsCreateParams) WithData(data *models.SafeMultisigTransactionEstimate) *V1SafesMultisigTransactionsEstimationsCreateParams { + o.SetData(data) + return o +} + +// SetData adds the data to the v1 safes multisig transactions estimations create params +func (o *V1SafesMultisigTransactionsEstimationsCreateParams) SetData(data *models.SafeMultisigTransactionEstimate) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SafesMultisigTransactionsEstimationsCreateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/transactions/v1_safes_multisig_transactions_estimations_create_responses.go b/utils/safe_api/client/transactions/v1_safes_multisig_transactions_estimations_create_responses.go new file mode 100644 index 0000000..378e5b9 --- /dev/null +++ b/utils/safe_api/client/transactions/v1_safes_multisig_transactions_estimations_create_responses.go @@ -0,0 +1,292 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1SafesMultisigTransactionsEstimationsCreateReader is a Reader for the V1SafesMultisigTransactionsEstimationsCreate structure. +type V1SafesMultisigTransactionsEstimationsCreateReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SafesMultisigTransactionsEstimationsCreateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1SafesMultisigTransactionsEstimationsCreateOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1SafesMultisigTransactionsEstimationsCreateBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewV1SafesMultisigTransactionsEstimationsCreateNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 422: + result := NewV1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /v1/safes/{address}/multisig-transactions/estimations/] v1_safes_multisig-transactions_estimations_create", response, response.Code()) + } +} + +// NewV1SafesMultisigTransactionsEstimationsCreateOK creates a V1SafesMultisigTransactionsEstimationsCreateOK with default headers values +func NewV1SafesMultisigTransactionsEstimationsCreateOK() *V1SafesMultisigTransactionsEstimationsCreateOK { + return &V1SafesMultisigTransactionsEstimationsCreateOK{} +} + +/* +V1SafesMultisigTransactionsEstimationsCreateOK describes a response with status code 200, with default header values. + +V1SafesMultisigTransactionsEstimationsCreateOK v1 safes multisig transactions estimations create o k +*/ +type V1SafesMultisigTransactionsEstimationsCreateOK struct { + Payload *models.SafeMultisigTransactionEstimateResponse +} + +// IsSuccess returns true when this v1 safes multisig transactions estimations create o k response has a 2xx status code +func (o *V1SafesMultisigTransactionsEstimationsCreateOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 safes multisig transactions estimations create o k response has a 3xx status code +func (o *V1SafesMultisigTransactionsEstimationsCreateOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes multisig transactions estimations create o k response has a 4xx status code +func (o *V1SafesMultisigTransactionsEstimationsCreateOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 safes multisig transactions estimations create o k response has a 5xx status code +func (o *V1SafesMultisigTransactionsEstimationsCreateOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes multisig transactions estimations create o k response a status code equal to that given +func (o *V1SafesMultisigTransactionsEstimationsCreateOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 safes multisig transactions estimations create o k response +func (o *V1SafesMultisigTransactionsEstimationsCreateOK) Code() int { + return 200 +} + +func (o *V1SafesMultisigTransactionsEstimationsCreateOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/safes/{address}/multisig-transactions/estimations/][%d] v1SafesMultisigTransactionsEstimationsCreateOK %s", 200, payload) +} + +func (o *V1SafesMultisigTransactionsEstimationsCreateOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /v1/safes/{address}/multisig-transactions/estimations/][%d] v1SafesMultisigTransactionsEstimationsCreateOK %s", 200, payload) +} + +func (o *V1SafesMultisigTransactionsEstimationsCreateOK) GetPayload() *models.SafeMultisigTransactionEstimateResponse { + return o.Payload +} + +func (o *V1SafesMultisigTransactionsEstimationsCreateOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.SafeMultisigTransactionEstimateResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SafesMultisigTransactionsEstimationsCreateBadRequest creates a V1SafesMultisigTransactionsEstimationsCreateBadRequest with default headers values +func NewV1SafesMultisigTransactionsEstimationsCreateBadRequest() *V1SafesMultisigTransactionsEstimationsCreateBadRequest { + return &V1SafesMultisigTransactionsEstimationsCreateBadRequest{} +} + +/* +V1SafesMultisigTransactionsEstimationsCreateBadRequest describes a response with status code 400, with default header values. + +Data not valid +*/ +type V1SafesMultisigTransactionsEstimationsCreateBadRequest struct { +} + +// IsSuccess returns true when this v1 safes multisig transactions estimations create bad request response has a 2xx status code +func (o *V1SafesMultisigTransactionsEstimationsCreateBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes multisig transactions estimations create bad request response has a 3xx status code +func (o *V1SafesMultisigTransactionsEstimationsCreateBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes multisig transactions estimations create bad request response has a 4xx status code +func (o *V1SafesMultisigTransactionsEstimationsCreateBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes multisig transactions estimations create bad request response has a 5xx status code +func (o *V1SafesMultisigTransactionsEstimationsCreateBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes multisig transactions estimations create bad request response a status code equal to that given +func (o *V1SafesMultisigTransactionsEstimationsCreateBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 safes multisig transactions estimations create bad request response +func (o *V1SafesMultisigTransactionsEstimationsCreateBadRequest) Code() int { + return 400 +} + +func (o *V1SafesMultisigTransactionsEstimationsCreateBadRequest) Error() string { + return fmt.Sprintf("[POST /v1/safes/{address}/multisig-transactions/estimations/][%d] v1SafesMultisigTransactionsEstimationsCreateBadRequest", 400) +} + +func (o *V1SafesMultisigTransactionsEstimationsCreateBadRequest) String() string { + return fmt.Sprintf("[POST /v1/safes/{address}/multisig-transactions/estimations/][%d] v1SafesMultisigTransactionsEstimationsCreateBadRequest", 400) +} + +func (o *V1SafesMultisigTransactionsEstimationsCreateBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1SafesMultisigTransactionsEstimationsCreateNotFound creates a V1SafesMultisigTransactionsEstimationsCreateNotFound with default headers values +func NewV1SafesMultisigTransactionsEstimationsCreateNotFound() *V1SafesMultisigTransactionsEstimationsCreateNotFound { + return &V1SafesMultisigTransactionsEstimationsCreateNotFound{} +} + +/* +V1SafesMultisigTransactionsEstimationsCreateNotFound describes a response with status code 404, with default header values. + +Safe not found +*/ +type V1SafesMultisigTransactionsEstimationsCreateNotFound struct { +} + +// IsSuccess returns true when this v1 safes multisig transactions estimations create not found response has a 2xx status code +func (o *V1SafesMultisigTransactionsEstimationsCreateNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes multisig transactions estimations create not found response has a 3xx status code +func (o *V1SafesMultisigTransactionsEstimationsCreateNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes multisig transactions estimations create not found response has a 4xx status code +func (o *V1SafesMultisigTransactionsEstimationsCreateNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes multisig transactions estimations create not found response has a 5xx status code +func (o *V1SafesMultisigTransactionsEstimationsCreateNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes multisig transactions estimations create not found response a status code equal to that given +func (o *V1SafesMultisigTransactionsEstimationsCreateNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 safes multisig transactions estimations create not found response +func (o *V1SafesMultisigTransactionsEstimationsCreateNotFound) Code() int { + return 404 +} + +func (o *V1SafesMultisigTransactionsEstimationsCreateNotFound) Error() string { + return fmt.Sprintf("[POST /v1/safes/{address}/multisig-transactions/estimations/][%d] v1SafesMultisigTransactionsEstimationsCreateNotFound", 404) +} + +func (o *V1SafesMultisigTransactionsEstimationsCreateNotFound) String() string { + return fmt.Sprintf("[POST /v1/safes/{address}/multisig-transactions/estimations/][%d] v1SafesMultisigTransactionsEstimationsCreateNotFound", 404) +} + +func (o *V1SafesMultisigTransactionsEstimationsCreateNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity creates a V1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity with default headers values +func NewV1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity() *V1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity { + return &V1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity{} +} + +/* +V1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity describes a response with status code 422, with default header values. + +Tx not valid +*/ +type V1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity struct { +} + +// IsSuccess returns true when this v1 safes multisig transactions estimations create unprocessable entity response has a 2xx status code +func (o *V1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes multisig transactions estimations create unprocessable entity response has a 3xx status code +func (o *V1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes multisig transactions estimations create unprocessable entity response has a 4xx status code +func (o *V1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes multisig transactions estimations create unprocessable entity response has a 5xx status code +func (o *V1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes multisig transactions estimations create unprocessable entity response a status code equal to that given +func (o *V1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 safes multisig transactions estimations create unprocessable entity response +func (o *V1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity) Error() string { + return fmt.Sprintf("[POST /v1/safes/{address}/multisig-transactions/estimations/][%d] v1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity", 422) +} + +func (o *V1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity) String() string { + return fmt.Sprintf("[POST /v1/safes/{address}/multisig-transactions/estimations/][%d] v1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity", 422) +} + +func (o *V1SafesMultisigTransactionsEstimationsCreateUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/transactions/v1_safes_multisig_transactions_list_parameters.go b/utils/safe_api/client/transactions/v1_safes_multisig_transactions_list_parameters.go new file mode 100644 index 0000000..f67f9d5 --- /dev/null +++ b/utils/safe_api/client/transactions/v1_safes_multisig_transactions_list_parameters.go @@ -0,0 +1,1033 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewV1SafesMultisigTransactionsListParams creates a new V1SafesMultisigTransactionsListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SafesMultisigTransactionsListParams() *V1SafesMultisigTransactionsListParams { + return &V1SafesMultisigTransactionsListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SafesMultisigTransactionsListParamsWithTimeout creates a new V1SafesMultisigTransactionsListParams object +// with the ability to set a timeout on a request. +func NewV1SafesMultisigTransactionsListParamsWithTimeout(timeout time.Duration) *V1SafesMultisigTransactionsListParams { + return &V1SafesMultisigTransactionsListParams{ + timeout: timeout, + } +} + +// NewV1SafesMultisigTransactionsListParamsWithContext creates a new V1SafesMultisigTransactionsListParams object +// with the ability to set a context for a request. +func NewV1SafesMultisigTransactionsListParamsWithContext(ctx context.Context) *V1SafesMultisigTransactionsListParams { + return &V1SafesMultisigTransactionsListParams{ + Context: ctx, + } +} + +// NewV1SafesMultisigTransactionsListParamsWithHTTPClient creates a new V1SafesMultisigTransactionsListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SafesMultisigTransactionsListParamsWithHTTPClient(client *http.Client) *V1SafesMultisigTransactionsListParams { + return &V1SafesMultisigTransactionsListParams{ + HTTPClient: client, + } +} + +/* +V1SafesMultisigTransactionsListParams contains all the parameters to send to the API endpoint + + for the v1 safes multisig transactions list operation. + + Typically these are written to a http.Request. +*/ +type V1SafesMultisigTransactionsListParams struct { + + // Address. + Address string + + /* Executed. + + executed + */ + Executed *string + + /* ExecutionDateGte. + + execution_date__gte + */ + ExecutionDateGte *string + + /* ExecutionDateLte. + + execution_date__lte + */ + ExecutionDateLte *string + + /* Failed. + + failed + */ + Failed *string + + /* HasConfirmations. + + has_confirmations + */ + HasConfirmations *string + + /* Limit. + + Number of results to return per page. + */ + Limit *int64 + + /* ModifiedGt. + + modified__gt + */ + ModifiedGt *string + + /* ModifiedGte. + + modified__gte + */ + ModifiedGte *string + + /* ModifiedLt. + + modified__lt + */ + ModifiedLt *string + + /* ModifiedLte. + + modified__lte + */ + ModifiedLte *string + + /* Nonce. + + nonce + */ + Nonce *string + + /* NonceGt. + + nonce__gt + */ + NonceGt *string + + /* NonceGte. + + nonce__gte + */ + NonceGte *string + + /* NonceLt. + + nonce__lt + */ + NonceLt *string + + /* NonceLte. + + nonce__lte + */ + NonceLte *string + + /* Offset. + + The initial index from which to return the results. + */ + Offset *int64 + + /* Ordering. + + Which field to use when ordering the results. + */ + Ordering *string + + /* SafeTxHash. + + safe_tx_hash + */ + SafeTxHash *string + + /* SubmissionDateGte. + + submission_date__gte + */ + SubmissionDateGte *string + + /* SubmissionDateLte. + + submission_date__lte + */ + SubmissionDateLte *string + + /* To. + + to + */ + To *string + + /* TransactionHash. + + transaction_hash + */ + TransactionHash *string + + /* Trusted. + + trusted + */ + Trusted *string + + /* Value. + + value + */ + Value *string + + /* ValueGt. + + value__gt + */ + ValueGt *string + + /* ValueLt. + + value__lt + */ + ValueLt *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 safes multisig transactions list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesMultisigTransactionsListParams) WithDefaults() *V1SafesMultisigTransactionsListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 safes multisig transactions list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesMultisigTransactionsListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithTimeout(timeout time.Duration) *V1SafesMultisigTransactionsListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithContext(ctx context.Context) *V1SafesMultisigTransactionsListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithHTTPClient(client *http.Client) *V1SafesMultisigTransactionsListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAddress adds the address to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithAddress(address string) *V1SafesMultisigTransactionsListParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetAddress(address string) { + o.Address = address +} + +// WithExecuted adds the executed to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithExecuted(executed *string) *V1SafesMultisigTransactionsListParams { + o.SetExecuted(executed) + return o +} + +// SetExecuted adds the executed to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetExecuted(executed *string) { + o.Executed = executed +} + +// WithExecutionDateGte adds the executionDateGte to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithExecutionDateGte(executionDateGte *string) *V1SafesMultisigTransactionsListParams { + o.SetExecutionDateGte(executionDateGte) + return o +} + +// SetExecutionDateGte adds the executionDateGte to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetExecutionDateGte(executionDateGte *string) { + o.ExecutionDateGte = executionDateGte +} + +// WithExecutionDateLte adds the executionDateLte to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithExecutionDateLte(executionDateLte *string) *V1SafesMultisigTransactionsListParams { + o.SetExecutionDateLte(executionDateLte) + return o +} + +// SetExecutionDateLte adds the executionDateLte to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetExecutionDateLte(executionDateLte *string) { + o.ExecutionDateLte = executionDateLte +} + +// WithFailed adds the failed to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithFailed(failed *string) *V1SafesMultisigTransactionsListParams { + o.SetFailed(failed) + return o +} + +// SetFailed adds the failed to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetFailed(failed *string) { + o.Failed = failed +} + +// WithHasConfirmations adds the hasConfirmations to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithHasConfirmations(hasConfirmations *string) *V1SafesMultisigTransactionsListParams { + o.SetHasConfirmations(hasConfirmations) + return o +} + +// SetHasConfirmations adds the hasConfirmations to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetHasConfirmations(hasConfirmations *string) { + o.HasConfirmations = hasConfirmations +} + +// WithLimit adds the limit to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithLimit(limit *int64) *V1SafesMultisigTransactionsListParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithModifiedGt adds the modifiedGt to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithModifiedGt(modifiedGt *string) *V1SafesMultisigTransactionsListParams { + o.SetModifiedGt(modifiedGt) + return o +} + +// SetModifiedGt adds the modifiedGt to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetModifiedGt(modifiedGt *string) { + o.ModifiedGt = modifiedGt +} + +// WithModifiedGte adds the modifiedGte to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithModifiedGte(modifiedGte *string) *V1SafesMultisigTransactionsListParams { + o.SetModifiedGte(modifiedGte) + return o +} + +// SetModifiedGte adds the modifiedGte to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetModifiedGte(modifiedGte *string) { + o.ModifiedGte = modifiedGte +} + +// WithModifiedLt adds the modifiedLt to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithModifiedLt(modifiedLt *string) *V1SafesMultisigTransactionsListParams { + o.SetModifiedLt(modifiedLt) + return o +} + +// SetModifiedLt adds the modifiedLt to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetModifiedLt(modifiedLt *string) { + o.ModifiedLt = modifiedLt +} + +// WithModifiedLte adds the modifiedLte to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithModifiedLte(modifiedLte *string) *V1SafesMultisigTransactionsListParams { + o.SetModifiedLte(modifiedLte) + return o +} + +// SetModifiedLte adds the modifiedLte to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetModifiedLte(modifiedLte *string) { + o.ModifiedLte = modifiedLte +} + +// WithNonce adds the nonce to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithNonce(nonce *string) *V1SafesMultisigTransactionsListParams { + o.SetNonce(nonce) + return o +} + +// SetNonce adds the nonce to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetNonce(nonce *string) { + o.Nonce = nonce +} + +// WithNonceGt adds the nonceGt to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithNonceGt(nonceGt *string) *V1SafesMultisigTransactionsListParams { + o.SetNonceGt(nonceGt) + return o +} + +// SetNonceGt adds the nonceGt to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetNonceGt(nonceGt *string) { + o.NonceGt = nonceGt +} + +// WithNonceGte adds the nonceGte to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithNonceGte(nonceGte *string) *V1SafesMultisigTransactionsListParams { + o.SetNonceGte(nonceGte) + return o +} + +// SetNonceGte adds the nonceGte to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetNonceGte(nonceGte *string) { + o.NonceGte = nonceGte +} + +// WithNonceLt adds the nonceLt to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithNonceLt(nonceLt *string) *V1SafesMultisigTransactionsListParams { + o.SetNonceLt(nonceLt) + return o +} + +// SetNonceLt adds the nonceLt to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetNonceLt(nonceLt *string) { + o.NonceLt = nonceLt +} + +// WithNonceLte adds the nonceLte to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithNonceLte(nonceLte *string) *V1SafesMultisigTransactionsListParams { + o.SetNonceLte(nonceLte) + return o +} + +// SetNonceLte adds the nonceLte to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetNonceLte(nonceLte *string) { + o.NonceLte = nonceLte +} + +// WithOffset adds the offset to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithOffset(offset *int64) *V1SafesMultisigTransactionsListParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithOrdering adds the ordering to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithOrdering(ordering *string) *V1SafesMultisigTransactionsListParams { + o.SetOrdering(ordering) + return o +} + +// SetOrdering adds the ordering to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetOrdering(ordering *string) { + o.Ordering = ordering +} + +// WithSafeTxHash adds the safeTxHash to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithSafeTxHash(safeTxHash *string) *V1SafesMultisigTransactionsListParams { + o.SetSafeTxHash(safeTxHash) + return o +} + +// SetSafeTxHash adds the safeTxHash to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetSafeTxHash(safeTxHash *string) { + o.SafeTxHash = safeTxHash +} + +// WithSubmissionDateGte adds the submissionDateGte to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithSubmissionDateGte(submissionDateGte *string) *V1SafesMultisigTransactionsListParams { + o.SetSubmissionDateGte(submissionDateGte) + return o +} + +// SetSubmissionDateGte adds the submissionDateGte to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetSubmissionDateGte(submissionDateGte *string) { + o.SubmissionDateGte = submissionDateGte +} + +// WithSubmissionDateLte adds the submissionDateLte to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithSubmissionDateLte(submissionDateLte *string) *V1SafesMultisigTransactionsListParams { + o.SetSubmissionDateLte(submissionDateLte) + return o +} + +// SetSubmissionDateLte adds the submissionDateLte to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetSubmissionDateLte(submissionDateLte *string) { + o.SubmissionDateLte = submissionDateLte +} + +// WithTo adds the to to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithTo(to *string) *V1SafesMultisigTransactionsListParams { + o.SetTo(to) + return o +} + +// SetTo adds the to to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetTo(to *string) { + o.To = to +} + +// WithTransactionHash adds the transactionHash to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithTransactionHash(transactionHash *string) *V1SafesMultisigTransactionsListParams { + o.SetTransactionHash(transactionHash) + return o +} + +// SetTransactionHash adds the transactionHash to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetTransactionHash(transactionHash *string) { + o.TransactionHash = transactionHash +} + +// WithTrusted adds the trusted to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithTrusted(trusted *string) *V1SafesMultisigTransactionsListParams { + o.SetTrusted(trusted) + return o +} + +// SetTrusted adds the trusted to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetTrusted(trusted *string) { + o.Trusted = trusted +} + +// WithValue adds the value to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithValue(value *string) *V1SafesMultisigTransactionsListParams { + o.SetValue(value) + return o +} + +// SetValue adds the value to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetValue(value *string) { + o.Value = value +} + +// WithValueGt adds the valueGt to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithValueGt(valueGt *string) *V1SafesMultisigTransactionsListParams { + o.SetValueGt(valueGt) + return o +} + +// SetValueGt adds the valueGt to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetValueGt(valueGt *string) { + o.ValueGt = valueGt +} + +// WithValueLt adds the valueLt to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) WithValueLt(valueLt *string) *V1SafesMultisigTransactionsListParams { + o.SetValueLt(valueLt) + return o +} + +// SetValueLt adds the valueLt to the v1 safes multisig transactions list params +func (o *V1SafesMultisigTransactionsListParams) SetValueLt(valueLt *string) { + o.ValueLt = valueLt +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SafesMultisigTransactionsListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + + if o.Executed != nil { + + // query param executed + var qrExecuted string + + if o.Executed != nil { + qrExecuted = *o.Executed + } + qExecuted := qrExecuted + if qExecuted != "" { + + if err := r.SetQueryParam("executed", qExecuted); err != nil { + return err + } + } + } + + if o.ExecutionDateGte != nil { + + // query param execution_date__gte + var qrExecutionDateGte string + + if o.ExecutionDateGte != nil { + qrExecutionDateGte = *o.ExecutionDateGte + } + qExecutionDateGte := qrExecutionDateGte + if qExecutionDateGte != "" { + + if err := r.SetQueryParam("execution_date__gte", qExecutionDateGte); err != nil { + return err + } + } + } + + if o.ExecutionDateLte != nil { + + // query param execution_date__lte + var qrExecutionDateLte string + + if o.ExecutionDateLte != nil { + qrExecutionDateLte = *o.ExecutionDateLte + } + qExecutionDateLte := qrExecutionDateLte + if qExecutionDateLte != "" { + + if err := r.SetQueryParam("execution_date__lte", qExecutionDateLte); err != nil { + return err + } + } + } + + if o.Failed != nil { + + // query param failed + var qrFailed string + + if o.Failed != nil { + qrFailed = *o.Failed + } + qFailed := qrFailed + if qFailed != "" { + + if err := r.SetQueryParam("failed", qFailed); err != nil { + return err + } + } + } + + if o.HasConfirmations != nil { + + // query param has_confirmations + var qrHasConfirmations string + + if o.HasConfirmations != nil { + qrHasConfirmations = *o.HasConfirmations + } + qHasConfirmations := qrHasConfirmations + if qHasConfirmations != "" { + + if err := r.SetQueryParam("has_confirmations", qHasConfirmations); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.ModifiedGt != nil { + + // query param modified__gt + var qrModifiedGt string + + if o.ModifiedGt != nil { + qrModifiedGt = *o.ModifiedGt + } + qModifiedGt := qrModifiedGt + if qModifiedGt != "" { + + if err := r.SetQueryParam("modified__gt", qModifiedGt); err != nil { + return err + } + } + } + + if o.ModifiedGte != nil { + + // query param modified__gte + var qrModifiedGte string + + if o.ModifiedGte != nil { + qrModifiedGte = *o.ModifiedGte + } + qModifiedGte := qrModifiedGte + if qModifiedGte != "" { + + if err := r.SetQueryParam("modified__gte", qModifiedGte); err != nil { + return err + } + } + } + + if o.ModifiedLt != nil { + + // query param modified__lt + var qrModifiedLt string + + if o.ModifiedLt != nil { + qrModifiedLt = *o.ModifiedLt + } + qModifiedLt := qrModifiedLt + if qModifiedLt != "" { + + if err := r.SetQueryParam("modified__lt", qModifiedLt); err != nil { + return err + } + } + } + + if o.ModifiedLte != nil { + + // query param modified__lte + var qrModifiedLte string + + if o.ModifiedLte != nil { + qrModifiedLte = *o.ModifiedLte + } + qModifiedLte := qrModifiedLte + if qModifiedLte != "" { + + if err := r.SetQueryParam("modified__lte", qModifiedLte); err != nil { + return err + } + } + } + + if o.Nonce != nil { + + // query param nonce + var qrNonce string + + if o.Nonce != nil { + qrNonce = *o.Nonce + } + qNonce := qrNonce + if qNonce != "" { + + if err := r.SetQueryParam("nonce", qNonce); err != nil { + return err + } + } + } + + if o.NonceGt != nil { + + // query param nonce__gt + var qrNonceGt string + + if o.NonceGt != nil { + qrNonceGt = *o.NonceGt + } + qNonceGt := qrNonceGt + if qNonceGt != "" { + + if err := r.SetQueryParam("nonce__gt", qNonceGt); err != nil { + return err + } + } + } + + if o.NonceGte != nil { + + // query param nonce__gte + var qrNonceGte string + + if o.NonceGte != nil { + qrNonceGte = *o.NonceGte + } + qNonceGte := qrNonceGte + if qNonceGte != "" { + + if err := r.SetQueryParam("nonce__gte", qNonceGte); err != nil { + return err + } + } + } + + if o.NonceLt != nil { + + // query param nonce__lt + var qrNonceLt string + + if o.NonceLt != nil { + qrNonceLt = *o.NonceLt + } + qNonceLt := qrNonceLt + if qNonceLt != "" { + + if err := r.SetQueryParam("nonce__lt", qNonceLt); err != nil { + return err + } + } + } + + if o.NonceLte != nil { + + // query param nonce__lte + var qrNonceLte string + + if o.NonceLte != nil { + qrNonceLte = *o.NonceLte + } + qNonceLte := qrNonceLte + if qNonceLte != "" { + + if err := r.SetQueryParam("nonce__lte", qNonceLte); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Ordering != nil { + + // query param ordering + var qrOrdering string + + if o.Ordering != nil { + qrOrdering = *o.Ordering + } + qOrdering := qrOrdering + if qOrdering != "" { + + if err := r.SetQueryParam("ordering", qOrdering); err != nil { + return err + } + } + } + + if o.SafeTxHash != nil { + + // query param safe_tx_hash + var qrSafeTxHash string + + if o.SafeTxHash != nil { + qrSafeTxHash = *o.SafeTxHash + } + qSafeTxHash := qrSafeTxHash + if qSafeTxHash != "" { + + if err := r.SetQueryParam("safe_tx_hash", qSafeTxHash); err != nil { + return err + } + } + } + + if o.SubmissionDateGte != nil { + + // query param submission_date__gte + var qrSubmissionDateGte string + + if o.SubmissionDateGte != nil { + qrSubmissionDateGte = *o.SubmissionDateGte + } + qSubmissionDateGte := qrSubmissionDateGte + if qSubmissionDateGte != "" { + + if err := r.SetQueryParam("submission_date__gte", qSubmissionDateGte); err != nil { + return err + } + } + } + + if o.SubmissionDateLte != nil { + + // query param submission_date__lte + var qrSubmissionDateLte string + + if o.SubmissionDateLte != nil { + qrSubmissionDateLte = *o.SubmissionDateLte + } + qSubmissionDateLte := qrSubmissionDateLte + if qSubmissionDateLte != "" { + + if err := r.SetQueryParam("submission_date__lte", qSubmissionDateLte); err != nil { + return err + } + } + } + + if o.To != nil { + + // query param to + var qrTo string + + if o.To != nil { + qrTo = *o.To + } + qTo := qrTo + if qTo != "" { + + if err := r.SetQueryParam("to", qTo); err != nil { + return err + } + } + } + + if o.TransactionHash != nil { + + // query param transaction_hash + var qrTransactionHash string + + if o.TransactionHash != nil { + qrTransactionHash = *o.TransactionHash + } + qTransactionHash := qrTransactionHash + if qTransactionHash != "" { + + if err := r.SetQueryParam("transaction_hash", qTransactionHash); err != nil { + return err + } + } + } + + if o.Trusted != nil { + + // query param trusted + var qrTrusted string + + if o.Trusted != nil { + qrTrusted = *o.Trusted + } + qTrusted := qrTrusted + if qTrusted != "" { + + if err := r.SetQueryParam("trusted", qTrusted); err != nil { + return err + } + } + } + + if o.Value != nil { + + // query param value + var qrValue string + + if o.Value != nil { + qrValue = *o.Value + } + qValue := qrValue + if qValue != "" { + + if err := r.SetQueryParam("value", qValue); err != nil { + return err + } + } + } + + if o.ValueGt != nil { + + // query param value__gt + var qrValueGt string + + if o.ValueGt != nil { + qrValueGt = *o.ValueGt + } + qValueGt := qrValueGt + if qValueGt != "" { + + if err := r.SetQueryParam("value__gt", qValueGt); err != nil { + return err + } + } + } + + if o.ValueLt != nil { + + // query param value__lt + var qrValueLt string + + if o.ValueLt != nil { + qrValueLt = *o.ValueLt + } + qValueLt := qrValueLt + if qValueLt != "" { + + if err := r.SetQueryParam("value__lt", qValueLt); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/transactions/v1_safes_multisig_transactions_list_responses.go b/utils/safe_api/client/transactions/v1_safes_multisig_transactions_list_responses.go new file mode 100644 index 0000000..6f9b392 --- /dev/null +++ b/utils/safe_api/client/transactions/v1_safes_multisig_transactions_list_responses.go @@ -0,0 +1,401 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + models "omni-balance/utils/safe_api" +) + +// V1SafesMultisigTransactionsListReader is a Reader for the V1SafesMultisigTransactionsList structure. +type V1SafesMultisigTransactionsListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SafesMultisigTransactionsListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1SafesMultisigTransactionsListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1SafesMultisigTransactionsListBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 422: + result := NewV1SafesMultisigTransactionsListUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/safes/{address}/multisig-transactions/] v1_safes_multisig-transactions_list", response, response.Code()) + } +} + +// NewV1SafesMultisigTransactionsListOK creates a V1SafesMultisigTransactionsListOK with default headers values +func NewV1SafesMultisigTransactionsListOK() *V1SafesMultisigTransactionsListOK { + return &V1SafesMultisigTransactionsListOK{} +} + +/* +V1SafesMultisigTransactionsListOK describes a response with status code 200, with default header values. + +V1SafesMultisigTransactionsListOK v1 safes multisig transactions list o k +*/ +type V1SafesMultisigTransactionsListOK struct { + Payload *V1SafesMultisigTransactionsListOKBody +} + +// IsSuccess returns true when this v1 safes multisig transactions list o k response has a 2xx status code +func (o *V1SafesMultisigTransactionsListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 safes multisig transactions list o k response has a 3xx status code +func (o *V1SafesMultisigTransactionsListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes multisig transactions list o k response has a 4xx status code +func (o *V1SafesMultisigTransactionsListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 safes multisig transactions list o k response has a 5xx status code +func (o *V1SafesMultisigTransactionsListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes multisig transactions list o k response a status code equal to that given +func (o *V1SafesMultisigTransactionsListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 safes multisig transactions list o k response +func (o *V1SafesMultisigTransactionsListOK) Code() int { + return 200 +} + +func (o *V1SafesMultisigTransactionsListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/multisig-transactions/][%d] v1SafesMultisigTransactionsListOK %s", 200, payload) +} + +func (o *V1SafesMultisigTransactionsListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/multisig-transactions/][%d] v1SafesMultisigTransactionsListOK %s", 200, payload) +} + +func (o *V1SafesMultisigTransactionsListOK) GetPayload() *V1SafesMultisigTransactionsListOKBody { + return o.Payload +} + +func (o *V1SafesMultisigTransactionsListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(V1SafesMultisigTransactionsListOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SafesMultisigTransactionsListBadRequest creates a V1SafesMultisigTransactionsListBadRequest with default headers values +func NewV1SafesMultisigTransactionsListBadRequest() *V1SafesMultisigTransactionsListBadRequest { + return &V1SafesMultisigTransactionsListBadRequest{} +} + +/* +V1SafesMultisigTransactionsListBadRequest describes a response with status code 400, with default header values. + +Invalid data +*/ +type V1SafesMultisigTransactionsListBadRequest struct { +} + +// IsSuccess returns true when this v1 safes multisig transactions list bad request response has a 2xx status code +func (o *V1SafesMultisigTransactionsListBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes multisig transactions list bad request response has a 3xx status code +func (o *V1SafesMultisigTransactionsListBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes multisig transactions list bad request response has a 4xx status code +func (o *V1SafesMultisigTransactionsListBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes multisig transactions list bad request response has a 5xx status code +func (o *V1SafesMultisigTransactionsListBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes multisig transactions list bad request response a status code equal to that given +func (o *V1SafesMultisigTransactionsListBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 safes multisig transactions list bad request response +func (o *V1SafesMultisigTransactionsListBadRequest) Code() int { + return 400 +} + +func (o *V1SafesMultisigTransactionsListBadRequest) Error() string { + return fmt.Sprintf("[GET /v1/safes/{address}/multisig-transactions/][%d] v1SafesMultisigTransactionsListBadRequest", 400) +} + +func (o *V1SafesMultisigTransactionsListBadRequest) String() string { + return fmt.Sprintf("[GET /v1/safes/{address}/multisig-transactions/][%d] v1SafesMultisigTransactionsListBadRequest", 400) +} + +func (o *V1SafesMultisigTransactionsListBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1SafesMultisigTransactionsListUnprocessableEntity creates a V1SafesMultisigTransactionsListUnprocessableEntity with default headers values +func NewV1SafesMultisigTransactionsListUnprocessableEntity() *V1SafesMultisigTransactionsListUnprocessableEntity { + return &V1SafesMultisigTransactionsListUnprocessableEntity{} +} + +/* +V1SafesMultisigTransactionsListUnprocessableEntity describes a response with status code 422, with default header values. + +Invalid ethereum address +*/ +type V1SafesMultisigTransactionsListUnprocessableEntity struct { +} + +// IsSuccess returns true when this v1 safes multisig transactions list unprocessable entity response has a 2xx status code +func (o *V1SafesMultisigTransactionsListUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes multisig transactions list unprocessable entity response has a 3xx status code +func (o *V1SafesMultisigTransactionsListUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes multisig transactions list unprocessable entity response has a 4xx status code +func (o *V1SafesMultisigTransactionsListUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes multisig transactions list unprocessable entity response has a 5xx status code +func (o *V1SafesMultisigTransactionsListUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes multisig transactions list unprocessable entity response a status code equal to that given +func (o *V1SafesMultisigTransactionsListUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 safes multisig transactions list unprocessable entity response +func (o *V1SafesMultisigTransactionsListUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1SafesMultisigTransactionsListUnprocessableEntity) Error() string { + return fmt.Sprintf("[GET /v1/safes/{address}/multisig-transactions/][%d] v1SafesMultisigTransactionsListUnprocessableEntity", 422) +} + +func (o *V1SafesMultisigTransactionsListUnprocessableEntity) String() string { + return fmt.Sprintf("[GET /v1/safes/{address}/multisig-transactions/][%d] v1SafesMultisigTransactionsListUnprocessableEntity", 422) +} + +func (o *V1SafesMultisigTransactionsListUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +/* +V1SafesMultisigTransactionsListOKBody v1 safes multisig transactions list o k body +swagger:model V1SafesMultisigTransactionsListOKBody +*/ +type V1SafesMultisigTransactionsListOKBody struct { + + // count + // Required: true + Count *int64 `json:"count"` + + // next + // Format: uri + Next *strfmt.URI `json:"next,omitempty"` + + // previous + // Format: uri + Previous *strfmt.URI `json:"previous,omitempty"` + + // results + // Required: true + Results []*models.SafeMultisigTransactionResponse `json:"results"` +} + +// Validate validates this v1 safes multisig transactions list o k body +func (o *V1SafesMultisigTransactionsListOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateCount(formats); err != nil { + res = append(res, err) + } + + if err := o.validateNext(formats); err != nil { + res = append(res, err) + } + + if err := o.validatePrevious(formats); err != nil { + res = append(res, err) + } + + if err := o.validateResults(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V1SafesMultisigTransactionsListOKBody) validateCount(formats strfmt.Registry) error { + + if err := validate.Required("v1SafesMultisigTransactionsListOK"+"."+"count", "body", o.Count); err != nil { + return err + } + + return nil +} + +func (o *V1SafesMultisigTransactionsListOKBody) validateNext(formats strfmt.Registry) error { + if swag.IsZero(o.Next) { // not required + return nil + } + + if err := validate.FormatOf("v1SafesMultisigTransactionsListOK"+"."+"next", "body", "uri", o.Next.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V1SafesMultisigTransactionsListOKBody) validatePrevious(formats strfmt.Registry) error { + if swag.IsZero(o.Previous) { // not required + return nil + } + + if err := validate.FormatOf("v1SafesMultisigTransactionsListOK"+"."+"previous", "body", "uri", o.Previous.String(), formats); err != nil { + return err + } + + return nil +} + +func (o *V1SafesMultisigTransactionsListOKBody) validateResults(formats strfmt.Registry) error { + + if err := validate.Required("v1SafesMultisigTransactionsListOK"+"."+"results", "body", o.Results); err != nil { + return err + } + + for i := 0; i < len(o.Results); i++ { + if swag.IsZero(o.Results[i]) { // not required + continue + } + + if o.Results[i] != nil { + if err := o.Results[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v1SafesMultisigTransactionsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v1SafesMultisigTransactionsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this v1 safes multisig transactions list o k body based on the context it is used +func (o *V1SafesMultisigTransactionsListOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResults(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *V1SafesMultisigTransactionsListOKBody) contextValidateResults(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Results); i++ { + + if o.Results[i] != nil { + + if swag.IsZero(o.Results[i]) { // not required + return nil + } + + if err := o.Results[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("v1SafesMultisigTransactionsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("v1SafesMultisigTransactionsListOK" + "." + "results" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *V1SafesMultisigTransactionsListOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *V1SafesMultisigTransactionsListOKBody) UnmarshalBinary(b []byte) error { + var res V1SafesMultisigTransactionsListOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/utils/safe_api/client/transactions/v1_safes_transfers_list_parameters.go b/utils/safe_api/client/transactions/v1_safes_transfers_list_parameters.go new file mode 100644 index 0000000..e155f55 --- /dev/null +++ b/utils/safe_api/client/transactions/v1_safes_transfers_list_parameters.go @@ -0,0 +1,795 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewV1SafesTransfersListParams creates a new V1SafesTransfersListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1SafesTransfersListParams() *V1SafesTransfersListParams { + return &V1SafesTransfersListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1SafesTransfersListParamsWithTimeout creates a new V1SafesTransfersListParams object +// with the ability to set a timeout on a request. +func NewV1SafesTransfersListParamsWithTimeout(timeout time.Duration) *V1SafesTransfersListParams { + return &V1SafesTransfersListParams{ + timeout: timeout, + } +} + +// NewV1SafesTransfersListParamsWithContext creates a new V1SafesTransfersListParams object +// with the ability to set a context for a request. +func NewV1SafesTransfersListParamsWithContext(ctx context.Context) *V1SafesTransfersListParams { + return &V1SafesTransfersListParams{ + Context: ctx, + } +} + +// NewV1SafesTransfersListParamsWithHTTPClient creates a new V1SafesTransfersListParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1SafesTransfersListParamsWithHTTPClient(client *http.Client) *V1SafesTransfersListParams { + return &V1SafesTransfersListParams{ + HTTPClient: client, + } +} + +/* +V1SafesTransfersListParams contains all the parameters to send to the API endpoint + + for the v1 safes transfers list operation. + + Typically these are written to a http.Request. +*/ +type V1SafesTransfersListParams struct { + + /* From. + + _from + */ + From *string + + // Address. + Address string + + /* BlockNumber. + + block_number + */ + BlockNumber *string + + /* BlockNumberGt. + + block_number__gt + */ + BlockNumberGt *string + + /* BlockNumberLt. + + block_number__lt + */ + BlockNumberLt *string + + /* Erc20. + + erc20 + */ + Erc20 *string + + /* Erc721. + + erc721 + */ + Erc721 *string + + /* Ether. + + ether + */ + Ether *string + + /* ExecutionDateGt. + + execution_date__gt + */ + ExecutionDateGt *string + + /* ExecutionDateGte. + + execution_date__gte + */ + ExecutionDateGte *string + + /* ExecutionDateLt. + + execution_date__lt + */ + ExecutionDateLt *string + + /* ExecutionDateLte. + + execution_date__lte + */ + ExecutionDateLte *string + + /* Limit. + + Number of results to return per page. + */ + Limit *int64 + + /* Offset. + + The initial index from which to return the results. + */ + Offset *int64 + + /* To. + + to + */ + To *string + + /* TokenAddress. + + token_address + */ + TokenAddress *string + + /* TransactionHash. + + transaction_hash + */ + TransactionHash *string + + /* Value. + + value + */ + Value *string + + /* ValueGt. + + value__gt + */ + ValueGt *string + + /* ValueLt. + + value__lt + */ + ValueLt *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 safes transfers list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesTransfersListParams) WithDefaults() *V1SafesTransfersListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 safes transfers list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1SafesTransfersListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithTimeout(timeout time.Duration) *V1SafesTransfersListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithContext(ctx context.Context) *V1SafesTransfersListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithHTTPClient(client *http.Client) *V1SafesTransfersListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFrom adds the from to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithFrom(from *string) *V1SafesTransfersListParams { + o.SetFrom(from) + return o +} + +// SetFrom adds the from to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetFrom(from *string) { + o.From = from +} + +// WithAddress adds the address to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithAddress(address string) *V1SafesTransfersListParams { + o.SetAddress(address) + return o +} + +// SetAddress adds the address to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetAddress(address string) { + o.Address = address +} + +// WithBlockNumber adds the blockNumber to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithBlockNumber(blockNumber *string) *V1SafesTransfersListParams { + o.SetBlockNumber(blockNumber) + return o +} + +// SetBlockNumber adds the blockNumber to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetBlockNumber(blockNumber *string) { + o.BlockNumber = blockNumber +} + +// WithBlockNumberGt adds the blockNumberGt to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithBlockNumberGt(blockNumberGt *string) *V1SafesTransfersListParams { + o.SetBlockNumberGt(blockNumberGt) + return o +} + +// SetBlockNumberGt adds the blockNumberGt to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetBlockNumberGt(blockNumberGt *string) { + o.BlockNumberGt = blockNumberGt +} + +// WithBlockNumberLt adds the blockNumberLt to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithBlockNumberLt(blockNumberLt *string) *V1SafesTransfersListParams { + o.SetBlockNumberLt(blockNumberLt) + return o +} + +// SetBlockNumberLt adds the blockNumberLt to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetBlockNumberLt(blockNumberLt *string) { + o.BlockNumberLt = blockNumberLt +} + +// WithErc20 adds the erc20 to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithErc20(erc20 *string) *V1SafesTransfersListParams { + o.SetErc20(erc20) + return o +} + +// SetErc20 adds the erc20 to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetErc20(erc20 *string) { + o.Erc20 = erc20 +} + +// WithErc721 adds the erc721 to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithErc721(erc721 *string) *V1SafesTransfersListParams { + o.SetErc721(erc721) + return o +} + +// SetErc721 adds the erc721 to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetErc721(erc721 *string) { + o.Erc721 = erc721 +} + +// WithEther adds the ether to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithEther(ether *string) *V1SafesTransfersListParams { + o.SetEther(ether) + return o +} + +// SetEther adds the ether to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetEther(ether *string) { + o.Ether = ether +} + +// WithExecutionDateGt adds the executionDateGt to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithExecutionDateGt(executionDateGt *string) *V1SafesTransfersListParams { + o.SetExecutionDateGt(executionDateGt) + return o +} + +// SetExecutionDateGt adds the executionDateGt to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetExecutionDateGt(executionDateGt *string) { + o.ExecutionDateGt = executionDateGt +} + +// WithExecutionDateGte adds the executionDateGte to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithExecutionDateGte(executionDateGte *string) *V1SafesTransfersListParams { + o.SetExecutionDateGte(executionDateGte) + return o +} + +// SetExecutionDateGte adds the executionDateGte to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetExecutionDateGte(executionDateGte *string) { + o.ExecutionDateGte = executionDateGte +} + +// WithExecutionDateLt adds the executionDateLt to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithExecutionDateLt(executionDateLt *string) *V1SafesTransfersListParams { + o.SetExecutionDateLt(executionDateLt) + return o +} + +// SetExecutionDateLt adds the executionDateLt to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetExecutionDateLt(executionDateLt *string) { + o.ExecutionDateLt = executionDateLt +} + +// WithExecutionDateLte adds the executionDateLte to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithExecutionDateLte(executionDateLte *string) *V1SafesTransfersListParams { + o.SetExecutionDateLte(executionDateLte) + return o +} + +// SetExecutionDateLte adds the executionDateLte to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetExecutionDateLte(executionDateLte *string) { + o.ExecutionDateLte = executionDateLte +} + +// WithLimit adds the limit to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithLimit(limit *int64) *V1SafesTransfersListParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithOffset(offset *int64) *V1SafesTransfersListParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithTo adds the to to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithTo(to *string) *V1SafesTransfersListParams { + o.SetTo(to) + return o +} + +// SetTo adds the to to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetTo(to *string) { + o.To = to +} + +// WithTokenAddress adds the tokenAddress to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithTokenAddress(tokenAddress *string) *V1SafesTransfersListParams { + o.SetTokenAddress(tokenAddress) + return o +} + +// SetTokenAddress adds the tokenAddress to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetTokenAddress(tokenAddress *string) { + o.TokenAddress = tokenAddress +} + +// WithTransactionHash adds the transactionHash to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithTransactionHash(transactionHash *string) *V1SafesTransfersListParams { + o.SetTransactionHash(transactionHash) + return o +} + +// SetTransactionHash adds the transactionHash to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetTransactionHash(transactionHash *string) { + o.TransactionHash = transactionHash +} + +// WithValue adds the value to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithValue(value *string) *V1SafesTransfersListParams { + o.SetValue(value) + return o +} + +// SetValue adds the value to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetValue(value *string) { + o.Value = value +} + +// WithValueGt adds the valueGt to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithValueGt(valueGt *string) *V1SafesTransfersListParams { + o.SetValueGt(valueGt) + return o +} + +// SetValueGt adds the valueGt to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetValueGt(valueGt *string) { + o.ValueGt = valueGt +} + +// WithValueLt adds the valueLt to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) WithValueLt(valueLt *string) *V1SafesTransfersListParams { + o.SetValueLt(valueLt) + return o +} + +// SetValueLt adds the valueLt to the v1 safes transfers list params +func (o *V1SafesTransfersListParams) SetValueLt(valueLt *string) { + o.ValueLt = valueLt +} + +// WriteToRequest writes these params to a swagger request +func (o *V1SafesTransfersListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.From != nil { + + // query param _from + var qrFrom string + + if o.From != nil { + qrFrom = *o.From + } + qFrom := qrFrom + if qFrom != "" { + + if err := r.SetQueryParam("_from", qFrom); err != nil { + return err + } + } + } + + // path param address + if err := r.SetPathParam("address", o.Address); err != nil { + return err + } + + if o.BlockNumber != nil { + + // query param block_number + var qrBlockNumber string + + if o.BlockNumber != nil { + qrBlockNumber = *o.BlockNumber + } + qBlockNumber := qrBlockNumber + if qBlockNumber != "" { + + if err := r.SetQueryParam("block_number", qBlockNumber); err != nil { + return err + } + } + } + + if o.BlockNumberGt != nil { + + // query param block_number__gt + var qrBlockNumberGt string + + if o.BlockNumberGt != nil { + qrBlockNumberGt = *o.BlockNumberGt + } + qBlockNumberGt := qrBlockNumberGt + if qBlockNumberGt != "" { + + if err := r.SetQueryParam("block_number__gt", qBlockNumberGt); err != nil { + return err + } + } + } + + if o.BlockNumberLt != nil { + + // query param block_number__lt + var qrBlockNumberLt string + + if o.BlockNumberLt != nil { + qrBlockNumberLt = *o.BlockNumberLt + } + qBlockNumberLt := qrBlockNumberLt + if qBlockNumberLt != "" { + + if err := r.SetQueryParam("block_number__lt", qBlockNumberLt); err != nil { + return err + } + } + } + + if o.Erc20 != nil { + + // query param erc20 + var qrErc20 string + + if o.Erc20 != nil { + qrErc20 = *o.Erc20 + } + qErc20 := qrErc20 + if qErc20 != "" { + + if err := r.SetQueryParam("erc20", qErc20); err != nil { + return err + } + } + } + + if o.Erc721 != nil { + + // query param erc721 + var qrErc721 string + + if o.Erc721 != nil { + qrErc721 = *o.Erc721 + } + qErc721 := qrErc721 + if qErc721 != "" { + + if err := r.SetQueryParam("erc721", qErc721); err != nil { + return err + } + } + } + + if o.Ether != nil { + + // query param ether + var qrEther string + + if o.Ether != nil { + qrEther = *o.Ether + } + qEther := qrEther + if qEther != "" { + + if err := r.SetQueryParam("ether", qEther); err != nil { + return err + } + } + } + + if o.ExecutionDateGt != nil { + + // query param execution_date__gt + var qrExecutionDateGt string + + if o.ExecutionDateGt != nil { + qrExecutionDateGt = *o.ExecutionDateGt + } + qExecutionDateGt := qrExecutionDateGt + if qExecutionDateGt != "" { + + if err := r.SetQueryParam("execution_date__gt", qExecutionDateGt); err != nil { + return err + } + } + } + + if o.ExecutionDateGte != nil { + + // query param execution_date__gte + var qrExecutionDateGte string + + if o.ExecutionDateGte != nil { + qrExecutionDateGte = *o.ExecutionDateGte + } + qExecutionDateGte := qrExecutionDateGte + if qExecutionDateGte != "" { + + if err := r.SetQueryParam("execution_date__gte", qExecutionDateGte); err != nil { + return err + } + } + } + + if o.ExecutionDateLt != nil { + + // query param execution_date__lt + var qrExecutionDateLt string + + if o.ExecutionDateLt != nil { + qrExecutionDateLt = *o.ExecutionDateLt + } + qExecutionDateLt := qrExecutionDateLt + if qExecutionDateLt != "" { + + if err := r.SetQueryParam("execution_date__lt", qExecutionDateLt); err != nil { + return err + } + } + } + + if o.ExecutionDateLte != nil { + + // query param execution_date__lte + var qrExecutionDateLte string + + if o.ExecutionDateLte != nil { + qrExecutionDateLte = *o.ExecutionDateLte + } + qExecutionDateLte := qrExecutionDateLte + if qExecutionDateLte != "" { + + if err := r.SetQueryParam("execution_date__lte", qExecutionDateLte); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.To != nil { + + // query param to + var qrTo string + + if o.To != nil { + qrTo = *o.To + } + qTo := qrTo + if qTo != "" { + + if err := r.SetQueryParam("to", qTo); err != nil { + return err + } + } + } + + if o.TokenAddress != nil { + + // query param token_address + var qrTokenAddress string + + if o.TokenAddress != nil { + qrTokenAddress = *o.TokenAddress + } + qTokenAddress := qrTokenAddress + if qTokenAddress != "" { + + if err := r.SetQueryParam("token_address", qTokenAddress); err != nil { + return err + } + } + } + + if o.TransactionHash != nil { + + // query param transaction_hash + var qrTransactionHash string + + if o.TransactionHash != nil { + qrTransactionHash = *o.TransactionHash + } + qTransactionHash := qrTransactionHash + if qTransactionHash != "" { + + if err := r.SetQueryParam("transaction_hash", qTransactionHash); err != nil { + return err + } + } + } + + if o.Value != nil { + + // query param value + var qrValue string + + if o.Value != nil { + qrValue = *o.Value + } + qValue := qrValue + if qValue != "" { + + if err := r.SetQueryParam("value", qValue); err != nil { + return err + } + } + } + + if o.ValueGt != nil { + + // query param value__gt + var qrValueGt string + + if o.ValueGt != nil { + qrValueGt = *o.ValueGt + } + qValueGt := qrValueGt + if qValueGt != "" { + + if err := r.SetQueryParam("value__gt", qValueGt); err != nil { + return err + } + } + } + + if o.ValueLt != nil { + + // query param value__lt + var qrValueLt string + + if o.ValueLt != nil { + qrValueLt = *o.ValueLt + } + qValueLt := qrValueLt + if qValueLt != "" { + + if err := r.SetQueryParam("value__lt", qValueLt); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/transactions/v1_safes_transfers_list_responses.go b/utils/safe_api/client/transactions/v1_safes_transfers_list_responses.go new file mode 100644 index 0000000..ef0514b --- /dev/null +++ b/utils/safe_api/client/transactions/v1_safes_transfers_list_responses.go @@ -0,0 +1,166 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transactions + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1SafesTransfersListReader is a Reader for the V1SafesTransfersList structure. +type V1SafesTransfersListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1SafesTransfersListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1SafesTransfersListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 422: + result := NewV1SafesTransfersListUnprocessableEntity() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/safes/{address}/transfers/] v1_safes_transfers_list", response, response.Code()) + } +} + +// NewV1SafesTransfersListOK creates a V1SafesTransfersListOK with default headers values +func NewV1SafesTransfersListOK() *V1SafesTransfersListOK { + return &V1SafesTransfersListOK{} +} + +/* +V1SafesTransfersListOK describes a response with status code 200, with default header values. + +V1SafesTransfersListOK v1 safes transfers list o k +*/ +type V1SafesTransfersListOK struct { + Payload []*models.TransferWithTokenInfoResponse +} + +// IsSuccess returns true when this v1 safes transfers list o k response has a 2xx status code +func (o *V1SafesTransfersListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 safes transfers list o k response has a 3xx status code +func (o *V1SafesTransfersListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes transfers list o k response has a 4xx status code +func (o *V1SafesTransfersListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 safes transfers list o k response has a 5xx status code +func (o *V1SafesTransfersListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes transfers list o k response a status code equal to that given +func (o *V1SafesTransfersListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 safes transfers list o k response +func (o *V1SafesTransfersListOK) Code() int { + return 200 +} + +func (o *V1SafesTransfersListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/transfers/][%d] v1SafesTransfersListOK %s", 200, payload) +} + +func (o *V1SafesTransfersListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/safes/{address}/transfers/][%d] v1SafesTransfersListOK %s", 200, payload) +} + +func (o *V1SafesTransfersListOK) GetPayload() []*models.TransferWithTokenInfoResponse { + return o.Payload +} + +func (o *V1SafesTransfersListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1SafesTransfersListUnprocessableEntity creates a V1SafesTransfersListUnprocessableEntity with default headers values +func NewV1SafesTransfersListUnprocessableEntity() *V1SafesTransfersListUnprocessableEntity { + return &V1SafesTransfersListUnprocessableEntity{} +} + +/* +V1SafesTransfersListUnprocessableEntity describes a response with status code 422, with default header values. + +Safe address checksum not valid +*/ +type V1SafesTransfersListUnprocessableEntity struct { +} + +// IsSuccess returns true when this v1 safes transfers list unprocessable entity response has a 2xx status code +func (o *V1SafesTransfersListUnprocessableEntity) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 safes transfers list unprocessable entity response has a 3xx status code +func (o *V1SafesTransfersListUnprocessableEntity) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 safes transfers list unprocessable entity response has a 4xx status code +func (o *V1SafesTransfersListUnprocessableEntity) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 safes transfers list unprocessable entity response has a 5xx status code +func (o *V1SafesTransfersListUnprocessableEntity) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 safes transfers list unprocessable entity response a status code equal to that given +func (o *V1SafesTransfersListUnprocessableEntity) IsCode(code int) bool { + return code == 422 +} + +// Code gets the status code for the v1 safes transfers list unprocessable entity response +func (o *V1SafesTransfersListUnprocessableEntity) Code() int { + return 422 +} + +func (o *V1SafesTransfersListUnprocessableEntity) Error() string { + return fmt.Sprintf("[GET /v1/safes/{address}/transfers/][%d] v1SafesTransfersListUnprocessableEntity", 422) +} + +func (o *V1SafesTransfersListUnprocessableEntity) String() string { + return fmt.Sprintf("[GET /v1/safes/{address}/transfers/][%d] v1SafesTransfersListUnprocessableEntity", 422) +} + +func (o *V1SafesTransfersListUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/client/transfer/transfer_client.go b/utils/safe_api/client/transfer/transfer_client.go new file mode 100644 index 0000000..dcc5180 --- /dev/null +++ b/utils/safe_api/client/transfer/transfer_client.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transfer + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// New creates a new transfer API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +// New creates a new transfer API client with basic auth credentials. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - user: user for basic authentication header. +// - password: password for basic authentication header. +func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BasicAuth(user, password) + return &Client{transport: transport, formats: strfmt.Default} +} + +// New creates a new transfer API client with a bearer token for authentication. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - bearerToken: bearer token for Bearer authentication header. +func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) + return &Client{transport: transport, formats: strfmt.Default} +} + +/* +Client for transfer API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption may be used to customize the behavior of Client methods. +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + V1TransferRead(params *V1TransferReadParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1TransferReadOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +V1TransferRead :return: transfer filtered by transfer_id +*/ +func (a *Client) V1TransferRead(params *V1TransferReadParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*V1TransferReadOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewV1TransferReadParams() + } + op := &runtime.ClientOperation{ + ID: "v1_transfer_read", + Method: "GET", + PathPattern: "/v1/transfer/{transfer_id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &V1TransferReadReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*V1TransferReadOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for v1_transfer_read: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/utils/safe_api/client/transfer/v1_transfer_read_parameters.go b/utils/safe_api/client/transfer/v1_transfer_read_parameters.go new file mode 100644 index 0000000..c52efdd --- /dev/null +++ b/utils/safe_api/client/transfer/v1_transfer_read_parameters.go @@ -0,0 +1,148 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transfer + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewV1TransferReadParams creates a new V1TransferReadParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewV1TransferReadParams() *V1TransferReadParams { + return &V1TransferReadParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewV1TransferReadParamsWithTimeout creates a new V1TransferReadParams object +// with the ability to set a timeout on a request. +func NewV1TransferReadParamsWithTimeout(timeout time.Duration) *V1TransferReadParams { + return &V1TransferReadParams{ + timeout: timeout, + } +} + +// NewV1TransferReadParamsWithContext creates a new V1TransferReadParams object +// with the ability to set a context for a request. +func NewV1TransferReadParamsWithContext(ctx context.Context) *V1TransferReadParams { + return &V1TransferReadParams{ + Context: ctx, + } +} + +// NewV1TransferReadParamsWithHTTPClient creates a new V1TransferReadParams object +// with the ability to set a custom HTTPClient for a request. +func NewV1TransferReadParamsWithHTTPClient(client *http.Client) *V1TransferReadParams { + return &V1TransferReadParams{ + HTTPClient: client, + } +} + +/* +V1TransferReadParams contains all the parameters to send to the API endpoint + + for the v1 transfer read operation. + + Typically these are written to a http.Request. +*/ +type V1TransferReadParams struct { + + // TransferID. + TransferID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the v1 transfer read params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1TransferReadParams) WithDefaults() *V1TransferReadParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the v1 transfer read params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *V1TransferReadParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the v1 transfer read params +func (o *V1TransferReadParams) WithTimeout(timeout time.Duration) *V1TransferReadParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the v1 transfer read params +func (o *V1TransferReadParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the v1 transfer read params +func (o *V1TransferReadParams) WithContext(ctx context.Context) *V1TransferReadParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the v1 transfer read params +func (o *V1TransferReadParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the v1 transfer read params +func (o *V1TransferReadParams) WithHTTPClient(client *http.Client) *V1TransferReadParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the v1 transfer read params +func (o *V1TransferReadParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithTransferID adds the transferID to the v1 transfer read params +func (o *V1TransferReadParams) WithTransferID(transferID string) *V1TransferReadParams { + o.SetTransferID(transferID) + return o +} + +// SetTransferID adds the transferId to the v1 transfer read params +func (o *V1TransferReadParams) SetTransferID(transferID string) { + o.TransferID = transferID +} + +// WriteToRequest writes these params to a swagger request +func (o *V1TransferReadParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param transfer_id + if err := r.SetPathParam("transfer_id", o.TransferID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/utils/safe_api/client/transfer/v1_transfer_read_responses.go b/utils/safe_api/client/transfer/v1_transfer_read_responses.go new file mode 100644 index 0000000..3a92269 --- /dev/null +++ b/utils/safe_api/client/transfer/v1_transfer_read_responses.go @@ -0,0 +1,230 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package transfer + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + models "omni-balance/utils/safe_api" +) + +// V1TransferReadReader is a Reader for the V1TransferRead structure. +type V1TransferReadReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *V1TransferReadReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewV1TransferReadOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewV1TransferReadBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewV1TransferReadNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /v1/transfer/{transfer_id}] v1_transfer_read", response, response.Code()) + } +} + +// NewV1TransferReadOK creates a V1TransferReadOK with default headers values +func NewV1TransferReadOK() *V1TransferReadOK { + return &V1TransferReadOK{} +} + +/* +V1TransferReadOK describes a response with status code 200, with default header values. + +V1TransferReadOK v1 transfer read o k +*/ +type V1TransferReadOK struct { + Payload *models.TransferWithTokenInfoResponse +} + +// IsSuccess returns true when this v1 transfer read o k response has a 2xx status code +func (o *V1TransferReadOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this v1 transfer read o k response has a 3xx status code +func (o *V1TransferReadOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 transfer read o k response has a 4xx status code +func (o *V1TransferReadOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this v1 transfer read o k response has a 5xx status code +func (o *V1TransferReadOK) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 transfer read o k response a status code equal to that given +func (o *V1TransferReadOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the v1 transfer read o k response +func (o *V1TransferReadOK) Code() int { + return 200 +} + +func (o *V1TransferReadOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/transfer/{transfer_id}][%d] v1TransferReadOK %s", 200, payload) +} + +func (o *V1TransferReadOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /v1/transfer/{transfer_id}][%d] v1TransferReadOK %s", 200, payload) +} + +func (o *V1TransferReadOK) GetPayload() *models.TransferWithTokenInfoResponse { + return o.Payload +} + +func (o *V1TransferReadOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.TransferWithTokenInfoResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewV1TransferReadBadRequest creates a V1TransferReadBadRequest with default headers values +func NewV1TransferReadBadRequest() *V1TransferReadBadRequest { + return &V1TransferReadBadRequest{} +} + +/* +V1TransferReadBadRequest describes a response with status code 400, with default header values. + +Invalid transferId +*/ +type V1TransferReadBadRequest struct { +} + +// IsSuccess returns true when this v1 transfer read bad request response has a 2xx status code +func (o *V1TransferReadBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 transfer read bad request response has a 3xx status code +func (o *V1TransferReadBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 transfer read bad request response has a 4xx status code +func (o *V1TransferReadBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 transfer read bad request response has a 5xx status code +func (o *V1TransferReadBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 transfer read bad request response a status code equal to that given +func (o *V1TransferReadBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the v1 transfer read bad request response +func (o *V1TransferReadBadRequest) Code() int { + return 400 +} + +func (o *V1TransferReadBadRequest) Error() string { + return fmt.Sprintf("[GET /v1/transfer/{transfer_id}][%d] v1TransferReadBadRequest", 400) +} + +func (o *V1TransferReadBadRequest) String() string { + return fmt.Sprintf("[GET /v1/transfer/{transfer_id}][%d] v1TransferReadBadRequest", 400) +} + +func (o *V1TransferReadBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewV1TransferReadNotFound creates a V1TransferReadNotFound with default headers values +func NewV1TransferReadNotFound() *V1TransferReadNotFound { + return &V1TransferReadNotFound{} +} + +/* +V1TransferReadNotFound describes a response with status code 404, with default header values. + +Transfer does not exist +*/ +type V1TransferReadNotFound struct { +} + +// IsSuccess returns true when this v1 transfer read not found response has a 2xx status code +func (o *V1TransferReadNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this v1 transfer read not found response has a 3xx status code +func (o *V1TransferReadNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this v1 transfer read not found response has a 4xx status code +func (o *V1TransferReadNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this v1 transfer read not found response has a 5xx status code +func (o *V1TransferReadNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this v1 transfer read not found response a status code equal to that given +func (o *V1TransferReadNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the v1 transfer read not found response +func (o *V1TransferReadNotFound) Code() int { + return 404 +} + +func (o *V1TransferReadNotFound) Error() string { + return fmt.Sprintf("[GET /v1/transfer/{transfer_id}][%d] v1TransferReadNotFound", 404) +} + +func (o *V1TransferReadNotFound) String() string { + return fmt.Sprintf("[GET /v1/transfer/{transfer_id}][%d] v1TransferReadNotFound", 404) +} + +func (o *V1TransferReadNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/utils/safe_api/contract.go b/utils/safe_api/contract.go new file mode 100644 index 0000000..44687fe --- /dev/null +++ b/utils/safe_api/contract.go @@ -0,0 +1,220 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Contract contract +// +// swagger:model Contract +type Contract struct { + + // Address + // Required: true + Address *string `json:"address"` + + // contract abi + // Required: true + ContractAbi *ContractAbi `json:"contractAbi"` + + // Display name + // Required: true + // Min Length: 1 + DisplayName *string `json:"displayName"` + + // Logo uri + // Read Only: true + // Format: uri + LogoURI strfmt.URI `json:"logoUri,omitempty"` + + // Name + // Required: true + // Min Length: 1 + Name *string `json:"name"` + + // Trusted for delegate call + // Required: true + TrustedForDelegateCall *bool `json:"trustedForDelegateCall"` +} + +// Validate validates this contract +func (m *Contract) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAddress(formats); err != nil { + res = append(res, err) + } + + if err := m.validateContractAbi(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDisplayName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateLogoURI(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTrustedForDelegateCall(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Contract) validateAddress(formats strfmt.Registry) error { + + if err := validate.Required("address", "body", m.Address); err != nil { + return err + } + + return nil +} + +func (m *Contract) validateContractAbi(formats strfmt.Registry) error { + + if err := validate.Required("contractAbi", "body", m.ContractAbi); err != nil { + return err + } + + if m.ContractAbi != nil { + if err := m.ContractAbi.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("contractAbi") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("contractAbi") + } + return err + } + } + + return nil +} + +func (m *Contract) validateDisplayName(formats strfmt.Registry) error { + + if err := validate.Required("displayName", "body", m.DisplayName); err != nil { + return err + } + + if err := validate.MinLength("displayName", "body", *m.DisplayName, 1); err != nil { + return err + } + + return nil +} + +func (m *Contract) validateLogoURI(formats strfmt.Registry) error { + if swag.IsZero(m.LogoURI) { // not required + return nil + } + + if err := validate.FormatOf("logoUri", "body", "uri", m.LogoURI.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Contract) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { + return err + } + + return nil +} + +func (m *Contract) validateTrustedForDelegateCall(formats strfmt.Registry) error { + + if err := validate.Required("trustedForDelegateCall", "body", m.TrustedForDelegateCall); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this contract based on the context it is used +func (m *Contract) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateContractAbi(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateLogoURI(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Contract) contextValidateContractAbi(ctx context.Context, formats strfmt.Registry) error { + + if m.ContractAbi != nil { + + if err := m.ContractAbi.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("contractAbi") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("contractAbi") + } + return err + } + } + + return nil +} + +func (m *Contract) contextValidateLogoURI(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "logoUri", "body", strfmt.URI(m.LogoURI)); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Contract) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Contract) UnmarshalBinary(b []byte) error { + var res Contract + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/contract_abi.go b/utils/safe_api/contract_abi.go new file mode 100644 index 0000000..b1a05b0 --- /dev/null +++ b/utils/safe_api/contract_abi.go @@ -0,0 +1,110 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ContractAbi contract abi +// +// swagger:model ContractAbi +type ContractAbi struct { + + // abi + // Required: true + Abi []map[string]*string `json:"abi"` + + // Description + // Required: true + // Min Length: 1 + Description *string `json:"description"` + + // Relevance + // Required: true + Relevance *int64 `json:"relevance"` +} + +// Validate validates this contract abi +func (m *ContractAbi) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAbi(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDescription(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRelevance(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ContractAbi) validateAbi(formats strfmt.Registry) error { + + if err := validate.Required("abi", "body", m.Abi); err != nil { + return err + } + + return nil +} + +func (m *ContractAbi) validateDescription(formats strfmt.Registry) error { + + if err := validate.Required("description", "body", m.Description); err != nil { + return err + } + + if err := validate.MinLength("description", "body", *m.Description, 1); err != nil { + return err + } + + return nil +} + +func (m *ContractAbi) validateRelevance(formats strfmt.Registry) error { + + if err := validate.Required("relevance", "body", m.Relevance); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this contract abi based on context it is used +func (m *ContractAbi) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ContractAbi) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ContractAbi) UnmarshalBinary(b []byte) error { + var res ContractAbi + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/data_decoder.go b/utils/safe_api/data_decoder.go new file mode 100644 index 0000000..81bcc6f --- /dev/null +++ b/utils/safe_api/data_decoder.go @@ -0,0 +1,74 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// DataDecoder data decoder +// +// swagger:model DataDecoder +type DataDecoder struct { + + // Data + // Required: true + Data *string `json:"data"` + + // To + To *string `json:"to,omitempty"` +} + +// Validate validates this data decoder +func (m *DataDecoder) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DataDecoder) validateData(formats strfmt.Registry) error { + + if err := validate.Required("data", "body", m.Data); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this data decoder based on context it is used +func (m *DataDecoder) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DataDecoder) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DataDecoder) UnmarshalBinary(b []byte) error { + var res DataDecoder + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/delegate.go b/utils/safe_api/delegate.go new file mode 100644 index 0000000..74bdb4d --- /dev/null +++ b/utils/safe_api/delegate.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Delegate delegate +// +// swagger:model Delegate +type Delegate struct { + + // Delegate + // Required: true + Delegate *string `json:"delegate"` + + // Delegator + // Required: true + Delegator *string `json:"delegator"` + + // Label + // Required: true + // Max Length: 50 + // Min Length: 1 + Label *string `json:"label"` + + // Safe + Safe *string `json:"safe,omitempty"` + + // Signature + // Required: true + Signature *string `json:"signature"` +} + +// Validate validates this delegate +func (m *Delegate) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDelegate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDelegator(formats); err != nil { + res = append(res, err) + } + + if err := m.validateLabel(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSignature(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Delegate) validateDelegate(formats strfmt.Registry) error { + + if err := validate.Required("delegate", "body", m.Delegate); err != nil { + return err + } + + return nil +} + +func (m *Delegate) validateDelegator(formats strfmt.Registry) error { + + if err := validate.Required("delegator", "body", m.Delegator); err != nil { + return err + } + + return nil +} + +func (m *Delegate) validateLabel(formats strfmt.Registry) error { + + if err := validate.Required("label", "body", m.Label); err != nil { + return err + } + + if err := validate.MinLength("label", "body", *m.Label, 1); err != nil { + return err + } + + if err := validate.MaxLength("label", "body", *m.Label, 50); err != nil { + return err + } + + return nil +} + +func (m *Delegate) validateSignature(formats strfmt.Registry) error { + + if err := validate.Required("signature", "body", m.Signature); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this delegate based on context it is used +func (m *Delegate) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Delegate) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Delegate) UnmarshalBinary(b []byte) error { + var res Delegate + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/delegate_delete.go b/utils/safe_api/delegate_delete.go new file mode 100644 index 0000000..38b7eca --- /dev/null +++ b/utils/safe_api/delegate_delete.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// DelegateDelete delegate delete +// +// swagger:model DelegateDelete +type DelegateDelete struct { + + // Delegate + // Required: true + Delegate *string `json:"delegate"` + + // Delegator + // Required: true + Delegator *string `json:"delegator"` + + // Signature + // Required: true + Signature *string `json:"signature"` +} + +// Validate validates this delegate delete +func (m *DelegateDelete) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDelegate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDelegator(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSignature(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DelegateDelete) validateDelegate(formats strfmt.Registry) error { + + if err := validate.Required("delegate", "body", m.Delegate); err != nil { + return err + } + + return nil +} + +func (m *DelegateDelete) validateDelegator(formats strfmt.Registry) error { + + if err := validate.Required("delegator", "body", m.Delegator); err != nil { + return err + } + + return nil +} + +func (m *DelegateDelete) validateSignature(formats strfmt.Registry) error { + + if err := validate.Required("signature", "body", m.Signature); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this delegate delete based on context it is used +func (m *DelegateDelete) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DelegateDelete) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DelegateDelete) UnmarshalBinary(b []byte) error { + var res DelegateDelete + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/delegate_delete_serializer_v2.go b/utils/safe_api/delegate_delete_serializer_v2.go new file mode 100644 index 0000000..e163799 --- /dev/null +++ b/utils/safe_api/delegate_delete_serializer_v2.go @@ -0,0 +1,91 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// DelegateDeleteSerializerV2 delegate delete serializer v2 +// +// swagger:model DelegateDeleteSerializerV2 +type DelegateDeleteSerializerV2 struct { + + // Delegator + // Required: true + Delegator *string `json:"delegator"` + + // Safe + Safe *string `json:"safe,omitempty"` + + // Signature + // Required: true + Signature *string `json:"signature"` +} + +// Validate validates this delegate delete serializer v2 +func (m *DelegateDeleteSerializerV2) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDelegator(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSignature(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DelegateDeleteSerializerV2) validateDelegator(formats strfmt.Registry) error { + + if err := validate.Required("delegator", "body", m.Delegator); err != nil { + return err + } + + return nil +} + +func (m *DelegateDeleteSerializerV2) validateSignature(formats strfmt.Registry) error { + + if err := validate.Required("signature", "body", m.Signature); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this delegate delete serializer v2 based on context it is used +func (m *DelegateDeleteSerializerV2) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DelegateDeleteSerializerV2) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DelegateDeleteSerializerV2) UnmarshalBinary(b []byte) error { + var res DelegateDeleteSerializerV2 + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/delegate_serializer_v2.go b/utils/safe_api/delegate_serializer_v2.go new file mode 100644 index 0000000..4986ef3 --- /dev/null +++ b/utils/safe_api/delegate_serializer_v2.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// DelegateSerializerV2 delegate serializer v2 +// +// swagger:model DelegateSerializerV2 +type DelegateSerializerV2 struct { + + // Delegate + // Required: true + Delegate *string `json:"delegate"` + + // Delegator + // Required: true + Delegator *string `json:"delegator"` + + // Label + // Required: true + // Max Length: 50 + // Min Length: 1 + Label *string `json:"label"` + + // Safe + Safe *string `json:"safe,omitempty"` + + // Signature + // Required: true + Signature *string `json:"signature"` +} + +// Validate validates this delegate serializer v2 +func (m *DelegateSerializerV2) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDelegate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDelegator(formats); err != nil { + res = append(res, err) + } + + if err := m.validateLabel(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSignature(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DelegateSerializerV2) validateDelegate(formats strfmt.Registry) error { + + if err := validate.Required("delegate", "body", m.Delegate); err != nil { + return err + } + + return nil +} + +func (m *DelegateSerializerV2) validateDelegator(formats strfmt.Registry) error { + + if err := validate.Required("delegator", "body", m.Delegator); err != nil { + return err + } + + return nil +} + +func (m *DelegateSerializerV2) validateLabel(formats strfmt.Registry) error { + + if err := validate.Required("label", "body", m.Label); err != nil { + return err + } + + if err := validate.MinLength("label", "body", *m.Label, 1); err != nil { + return err + } + + if err := validate.MaxLength("label", "body", *m.Label, 50); err != nil { + return err + } + + return nil +} + +func (m *DelegateSerializerV2) validateSignature(formats strfmt.Registry) error { + + if err := validate.Required("signature", "body", m.Signature); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this delegate serializer v2 based on context it is used +func (m *DelegateSerializerV2) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DelegateSerializerV2) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DelegateSerializerV2) UnmarshalBinary(b []byte) error { + var res DelegateSerializerV2 + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/erc20_info.go b/utils/safe_api/erc20_info.go new file mode 100644 index 0000000..db2bd51 --- /dev/null +++ b/utils/safe_api/erc20_info.go @@ -0,0 +1,137 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Erc20Info erc20 info +// +// swagger:model Erc20Info +type Erc20Info struct { + + // Decimals + // Required: true + Decimals *int64 `json:"decimals"` + + // Logo uri + // Required: true + // Min Length: 1 + LogoURI *string `json:"logoUri"` + + // Name + // Required: true + // Min Length: 1 + Name *string `json:"name"` + + // Symbol + // Required: true + // Min Length: 1 + Symbol *string `json:"symbol"` +} + +// Validate validates this erc20 info +func (m *Erc20Info) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDecimals(formats); err != nil { + res = append(res, err) + } + + if err := m.validateLogoURI(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSymbol(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Erc20Info) validateDecimals(formats strfmt.Registry) error { + + if err := validate.Required("decimals", "body", m.Decimals); err != nil { + return err + } + + return nil +} + +func (m *Erc20Info) validateLogoURI(formats strfmt.Registry) error { + + if err := validate.Required("logoUri", "body", m.LogoURI); err != nil { + return err + } + + if err := validate.MinLength("logoUri", "body", *m.LogoURI, 1); err != nil { + return err + } + + return nil +} + +func (m *Erc20Info) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { + return err + } + + return nil +} + +func (m *Erc20Info) validateSymbol(formats strfmt.Registry) error { + + if err := validate.Required("symbol", "body", m.Symbol); err != nil { + return err + } + + if err := validate.MinLength("symbol", "body", *m.Symbol, 1); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this erc20 info based on context it is used +func (m *Erc20Info) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Erc20Info) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Erc20Info) UnmarshalBinary(b []byte) error { + var res Erc20Info + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/ethereum_tx_with_transfers_response.go b/utils/safe_api/ethereum_tx_with_transfers_response.go new file mode 100644 index 0000000..c6f8ef8 --- /dev/null +++ b/utils/safe_api/ethereum_tx_with_transfers_response.go @@ -0,0 +1,248 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// EthereumTxWithTransfersResponse ethereum tx with transfers response +// +// swagger:model EthereumTxWithTransfersResponse +type EthereumTxWithTransfersResponse struct { + + // Block number + // Read Only: true + BlockNumber int64 `json:"blockNumber,omitempty"` + + // Data + // Required: true + Data *string `json:"data"` + + // Execution date + // Required: true + // Format: date-time + ExecutionDate *strfmt.DateTime `json:"executionDate"` + + // From + // Required: true + From *string `json:"from"` + + // To + // Required: true + To *string `json:"to"` + + // transfers + // Required: true + Transfers []*TransferWithTokenInfoResponse `json:"transfers"` + + // Tx hash + // Required: true + TxHash *string `json:"txHash"` + + // Tx type + // Read Only: true + TxType string `json:"txType,omitempty"` +} + +// Validate validates this ethereum tx with transfers response +func (m *EthereumTxWithTransfersResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateData(formats); err != nil { + res = append(res, err) + } + + if err := m.validateExecutionDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateFrom(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTo(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTransfers(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTxHash(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *EthereumTxWithTransfersResponse) validateData(formats strfmt.Registry) error { + + if err := validate.Required("data", "body", m.Data); err != nil { + return err + } + + return nil +} + +func (m *EthereumTxWithTransfersResponse) validateExecutionDate(formats strfmt.Registry) error { + + if err := validate.Required("executionDate", "body", m.ExecutionDate); err != nil { + return err + } + + if err := validate.FormatOf("executionDate", "body", "date-time", m.ExecutionDate.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *EthereumTxWithTransfersResponse) validateFrom(formats strfmt.Registry) error { + + if err := validate.Required("from", "body", m.From); err != nil { + return err + } + + return nil +} + +func (m *EthereumTxWithTransfersResponse) validateTo(formats strfmt.Registry) error { + + if err := validate.Required("to", "body", m.To); err != nil { + return err + } + + return nil +} + +func (m *EthereumTxWithTransfersResponse) validateTransfers(formats strfmt.Registry) error { + + if err := validate.Required("transfers", "body", m.Transfers); err != nil { + return err + } + + for i := 0; i < len(m.Transfers); i++ { + if swag.IsZero(m.Transfers[i]) { // not required + continue + } + + if m.Transfers[i] != nil { + if err := m.Transfers[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("transfers" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("transfers" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *EthereumTxWithTransfersResponse) validateTxHash(formats strfmt.Registry) error { + + if err := validate.Required("txHash", "body", m.TxHash); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this ethereum tx with transfers response based on the context it is used +func (m *EthereumTxWithTransfersResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateBlockNumber(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateTransfers(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateTxType(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *EthereumTxWithTransfersResponse) contextValidateBlockNumber(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "blockNumber", "body", int64(m.BlockNumber)); err != nil { + return err + } + + return nil +} + +func (m *EthereumTxWithTransfersResponse) contextValidateTransfers(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Transfers); i++ { + + if m.Transfers[i] != nil { + + if swag.IsZero(m.Transfers[i]) { // not required + return nil + } + + if err := m.Transfers[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("transfers" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("transfers" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *EthereumTxWithTransfersResponse) contextValidateTxType(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "txType", "body", string(m.TxType)); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *EthereumTxWithTransfersResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *EthereumTxWithTransfersResponse) UnmarshalBinary(b []byte) error { + var res EthereumTxWithTransfersResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/firebase_device.go b/utils/safe_api/firebase_device.go new file mode 100644 index 0000000..7096b1a --- /dev/null +++ b/utils/safe_api/firebase_device.go @@ -0,0 +1,256 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// FirebaseDevice firebase device +// +// swagger:model FirebaseDevice +type FirebaseDevice struct { + + // Build number + // Required: true + // Minimum: 0 + BuildNumber *int64 `json:"buildNumber"` + + // Bundle + // Required: true + // Max Length: 100 + // Min Length: 1 + Bundle *string `json:"bundle"` + + // Cloud messaging token + // Required: true + // Max Length: 200 + // Min Length: 100 + CloudMessagingToken *string `json:"cloudMessagingToken"` + + // Device type + // Required: true + // Enum: ["ANDROID","IOS","WEB"] + DeviceType *string `json:"deviceType"` + + // safes + // Required: true + Safes []string `json:"safes"` + + // signatures + Signatures []string `json:"signatures"` + + // Timestamp + Timestamp int64 `json:"timestamp,omitempty"` + + // Uuid + // Format: uuid + UUID *strfmt.UUID `json:"uuid,omitempty"` + + // Version + // Required: true + // Max Length: 100 + // Min Length: 1 + Version *string `json:"version"` +} + +// Validate validates this firebase device +func (m *FirebaseDevice) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateBuildNumber(formats); err != nil { + res = append(res, err) + } + + if err := m.validateBundle(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCloudMessagingToken(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDeviceType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafes(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUUID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVersion(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *FirebaseDevice) validateBuildNumber(formats strfmt.Registry) error { + + if err := validate.Required("buildNumber", "body", m.BuildNumber); err != nil { + return err + } + + if err := validate.MinimumInt("buildNumber", "body", *m.BuildNumber, 0, false); err != nil { + return err + } + + return nil +} + +func (m *FirebaseDevice) validateBundle(formats strfmt.Registry) error { + + if err := validate.Required("bundle", "body", m.Bundle); err != nil { + return err + } + + if err := validate.MinLength("bundle", "body", *m.Bundle, 1); err != nil { + return err + } + + if err := validate.MaxLength("bundle", "body", *m.Bundle, 100); err != nil { + return err + } + + return nil +} + +func (m *FirebaseDevice) validateCloudMessagingToken(formats strfmt.Registry) error { + + if err := validate.Required("cloudMessagingToken", "body", m.CloudMessagingToken); err != nil { + return err + } + + if err := validate.MinLength("cloudMessagingToken", "body", *m.CloudMessagingToken, 100); err != nil { + return err + } + + if err := validate.MaxLength("cloudMessagingToken", "body", *m.CloudMessagingToken, 200); err != nil { + return err + } + + return nil +} + +var firebaseDeviceTypeDeviceTypePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["ANDROID","IOS","WEB"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + firebaseDeviceTypeDeviceTypePropEnum = append(firebaseDeviceTypeDeviceTypePropEnum, v) + } +} + +const ( + + // FirebaseDeviceDeviceTypeANDROID captures enum value "ANDROID" + FirebaseDeviceDeviceTypeANDROID string = "ANDROID" + + // FirebaseDeviceDeviceTypeIOS captures enum value "IOS" + FirebaseDeviceDeviceTypeIOS string = "IOS" + + // FirebaseDeviceDeviceTypeWEB captures enum value "WEB" + FirebaseDeviceDeviceTypeWEB string = "WEB" +) + +// prop value enum +func (m *FirebaseDevice) validateDeviceTypeEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, firebaseDeviceTypeDeviceTypePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *FirebaseDevice) validateDeviceType(formats strfmt.Registry) error { + + if err := validate.Required("deviceType", "body", m.DeviceType); err != nil { + return err + } + + // value enum + if err := m.validateDeviceTypeEnum("deviceType", "body", *m.DeviceType); err != nil { + return err + } + + return nil +} + +func (m *FirebaseDevice) validateSafes(formats strfmt.Registry) error { + + if err := validate.Required("safes", "body", m.Safes); err != nil { + return err + } + + return nil +} + +func (m *FirebaseDevice) validateUUID(formats strfmt.Registry) error { + if swag.IsZero(m.UUID) { // not required + return nil + } + + if err := validate.FormatOf("uuid", "body", "uuid", m.UUID.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *FirebaseDevice) validateVersion(formats strfmt.Registry) error { + + if err := validate.Required("version", "body", m.Version); err != nil { + return err + } + + if err := validate.MinLength("version", "body", *m.Version, 1); err != nil { + return err + } + + if err := validate.MaxLength("version", "body", *m.Version, 100); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this firebase device based on context it is used +func (m *FirebaseDevice) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *FirebaseDevice) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *FirebaseDevice) UnmarshalBinary(b []byte) error { + var res FirebaseDevice + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/firebase_device_serializer_with_owners_response.go b/utils/safe_api/firebase_device_serializer_with_owners_response.go new file mode 100644 index 0000000..11699af --- /dev/null +++ b/utils/safe_api/firebase_device_serializer_with_owners_response.go @@ -0,0 +1,290 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// FirebaseDeviceSerializerWithOwnersResponse firebase device serializer with owners response +// +// swagger:model FirebaseDeviceSerializerWithOwnersResponse +type FirebaseDeviceSerializerWithOwnersResponse struct { + + // Build number + // Required: true + // Minimum: 0 + BuildNumber *int64 `json:"buildNumber"` + + // Bundle + // Required: true + // Max Length: 100 + // Min Length: 1 + Bundle *string `json:"bundle"` + + // Cloud messaging token + // Required: true + // Max Length: 200 + // Min Length: 100 + CloudMessagingToken *string `json:"cloudMessagingToken"` + + // Device type + // Required: true + // Enum: ["ANDROID","IOS","WEB"] + DeviceType *string `json:"deviceType"` + + // owners not registered + // Required: true + OwnersNotRegistered []string `json:"ownersNotRegistered"` + + // owners registered + // Required: true + OwnersRegistered []string `json:"ownersRegistered"` + + // safes + // Required: true + Safes []string `json:"safes"` + + // signatures + Signatures []string `json:"signatures"` + + // Timestamp + Timestamp int64 `json:"timestamp,omitempty"` + + // Uuid + // Format: uuid + UUID *strfmt.UUID `json:"uuid,omitempty"` + + // Version + // Required: true + // Max Length: 100 + // Min Length: 1 + Version *string `json:"version"` +} + +// Validate validates this firebase device serializer with owners response +func (m *FirebaseDeviceSerializerWithOwnersResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateBuildNumber(formats); err != nil { + res = append(res, err) + } + + if err := m.validateBundle(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCloudMessagingToken(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDeviceType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOwnersNotRegistered(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOwnersRegistered(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafes(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUUID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVersion(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *FirebaseDeviceSerializerWithOwnersResponse) validateBuildNumber(formats strfmt.Registry) error { + + if err := validate.Required("buildNumber", "body", m.BuildNumber); err != nil { + return err + } + + if err := validate.MinimumInt("buildNumber", "body", *m.BuildNumber, 0, false); err != nil { + return err + } + + return nil +} + +func (m *FirebaseDeviceSerializerWithOwnersResponse) validateBundle(formats strfmt.Registry) error { + + if err := validate.Required("bundle", "body", m.Bundle); err != nil { + return err + } + + if err := validate.MinLength("bundle", "body", *m.Bundle, 1); err != nil { + return err + } + + if err := validate.MaxLength("bundle", "body", *m.Bundle, 100); err != nil { + return err + } + + return nil +} + +func (m *FirebaseDeviceSerializerWithOwnersResponse) validateCloudMessagingToken(formats strfmt.Registry) error { + + if err := validate.Required("cloudMessagingToken", "body", m.CloudMessagingToken); err != nil { + return err + } + + if err := validate.MinLength("cloudMessagingToken", "body", *m.CloudMessagingToken, 100); err != nil { + return err + } + + if err := validate.MaxLength("cloudMessagingToken", "body", *m.CloudMessagingToken, 200); err != nil { + return err + } + + return nil +} + +var firebaseDeviceSerializerWithOwnersResponseTypeDeviceTypePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["ANDROID","IOS","WEB"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + firebaseDeviceSerializerWithOwnersResponseTypeDeviceTypePropEnum = append(firebaseDeviceSerializerWithOwnersResponseTypeDeviceTypePropEnum, v) + } +} + +const ( + + // FirebaseDeviceSerializerWithOwnersResponseDeviceTypeANDROID captures enum value "ANDROID" + FirebaseDeviceSerializerWithOwnersResponseDeviceTypeANDROID string = "ANDROID" + + // FirebaseDeviceSerializerWithOwnersResponseDeviceTypeIOS captures enum value "IOS" + FirebaseDeviceSerializerWithOwnersResponseDeviceTypeIOS string = "IOS" + + // FirebaseDeviceSerializerWithOwnersResponseDeviceTypeWEB captures enum value "WEB" + FirebaseDeviceSerializerWithOwnersResponseDeviceTypeWEB string = "WEB" +) + +// prop value enum +func (m *FirebaseDeviceSerializerWithOwnersResponse) validateDeviceTypeEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, firebaseDeviceSerializerWithOwnersResponseTypeDeviceTypePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *FirebaseDeviceSerializerWithOwnersResponse) validateDeviceType(formats strfmt.Registry) error { + + if err := validate.Required("deviceType", "body", m.DeviceType); err != nil { + return err + } + + // value enum + if err := m.validateDeviceTypeEnum("deviceType", "body", *m.DeviceType); err != nil { + return err + } + + return nil +} + +func (m *FirebaseDeviceSerializerWithOwnersResponse) validateOwnersNotRegistered(formats strfmt.Registry) error { + + if err := validate.Required("ownersNotRegistered", "body", m.OwnersNotRegistered); err != nil { + return err + } + + return nil +} + +func (m *FirebaseDeviceSerializerWithOwnersResponse) validateOwnersRegistered(formats strfmt.Registry) error { + + if err := validate.Required("ownersRegistered", "body", m.OwnersRegistered); err != nil { + return err + } + + return nil +} + +func (m *FirebaseDeviceSerializerWithOwnersResponse) validateSafes(formats strfmt.Registry) error { + + if err := validate.Required("safes", "body", m.Safes); err != nil { + return err + } + + return nil +} + +func (m *FirebaseDeviceSerializerWithOwnersResponse) validateUUID(formats strfmt.Registry) error { + if swag.IsZero(m.UUID) { // not required + return nil + } + + if err := validate.FormatOf("uuid", "body", "uuid", m.UUID.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *FirebaseDeviceSerializerWithOwnersResponse) validateVersion(formats strfmt.Registry) error { + + if err := validate.Required("version", "body", m.Version); err != nil { + return err + } + + if err := validate.MinLength("version", "body", *m.Version, 1); err != nil { + return err + } + + if err := validate.MaxLength("version", "body", *m.Version, 100); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this firebase device serializer with owners response based on context it is used +func (m *FirebaseDeviceSerializerWithOwnersResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *FirebaseDeviceSerializerWithOwnersResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *FirebaseDeviceSerializerWithOwnersResponse) UnmarshalBinary(b []byte) error { + var res FirebaseDeviceSerializerWithOwnersResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/indexing_status.go b/utils/safe_api/indexing_status.go new file mode 100644 index 0000000..8c2c55c --- /dev/null +++ b/utils/safe_api/indexing_status.go @@ -0,0 +1,156 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// IndexingStatus indexing status +// +// swagger:model IndexingStatus +type IndexingStatus struct { + + // Current block number + // Required: true + CurrentBlockNumber *int64 `json:"currentBlockNumber"` + + // Erc20 block number + // Required: true + Erc20BlockNumber *int64 `json:"erc20BlockNumber"` + + // Erc20 synced + // Required: true + Erc20Synced *bool `json:"erc20Synced"` + + // Master copies block number + // Required: true + MasterCopiesBlockNumber *int64 `json:"masterCopiesBlockNumber"` + + // Master copies synced + // Required: true + MasterCopiesSynced *bool `json:"masterCopiesSynced"` + + // Synced + // Required: true + Synced *bool `json:"synced"` +} + +// Validate validates this indexing status +func (m *IndexingStatus) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCurrentBlockNumber(formats); err != nil { + res = append(res, err) + } + + if err := m.validateErc20BlockNumber(formats); err != nil { + res = append(res, err) + } + + if err := m.validateErc20Synced(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMasterCopiesBlockNumber(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMasterCopiesSynced(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSynced(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *IndexingStatus) validateCurrentBlockNumber(formats strfmt.Registry) error { + + if err := validate.Required("currentBlockNumber", "body", m.CurrentBlockNumber); err != nil { + return err + } + + return nil +} + +func (m *IndexingStatus) validateErc20BlockNumber(formats strfmt.Registry) error { + + if err := validate.Required("erc20BlockNumber", "body", m.Erc20BlockNumber); err != nil { + return err + } + + return nil +} + +func (m *IndexingStatus) validateErc20Synced(formats strfmt.Registry) error { + + if err := validate.Required("erc20Synced", "body", m.Erc20Synced); err != nil { + return err + } + + return nil +} + +func (m *IndexingStatus) validateMasterCopiesBlockNumber(formats strfmt.Registry) error { + + if err := validate.Required("masterCopiesBlockNumber", "body", m.MasterCopiesBlockNumber); err != nil { + return err + } + + return nil +} + +func (m *IndexingStatus) validateMasterCopiesSynced(formats strfmt.Registry) error { + + if err := validate.Required("masterCopiesSynced", "body", m.MasterCopiesSynced); err != nil { + return err + } + + return nil +} + +func (m *IndexingStatus) validateSynced(formats strfmt.Registry) error { + + if err := validate.Required("synced", "body", m.Synced); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this indexing status based on context it is used +func (m *IndexingStatus) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *IndexingStatus) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *IndexingStatus) UnmarshalBinary(b []byte) error { + var res IndexingStatus + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/master_copy_response.go b/utils/safe_api/master_copy_response.go new file mode 100644 index 0000000..4a9c3da --- /dev/null +++ b/utils/safe_api/master_copy_response.go @@ -0,0 +1,166 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// MasterCopyResponse master copy response +// +// swagger:model MasterCopyResponse +type MasterCopyResponse struct { + + // Address + // Required: true + Address *string `json:"address"` + + // Deployed block number + // Required: true + DeployedBlockNumber *int64 `json:"deployedBlockNumber"` + + // Deployer + // Required: true + // Min Length: 1 + Deployer *string `json:"deployer"` + + // L2 + // Required: true + L2 *bool `json:"l2"` + + // Last indexed block number + // Required: true + LastIndexedBlockNumber *int64 `json:"lastIndexedBlockNumber"` + + // Version + // Required: true + // Min Length: 1 + Version *string `json:"version"` +} + +// Validate validates this master copy response +func (m *MasterCopyResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAddress(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDeployedBlockNumber(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDeployer(formats); err != nil { + res = append(res, err) + } + + if err := m.validateL2(formats); err != nil { + res = append(res, err) + } + + if err := m.validateLastIndexedBlockNumber(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVersion(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *MasterCopyResponse) validateAddress(formats strfmt.Registry) error { + + if err := validate.Required("address", "body", m.Address); err != nil { + return err + } + + return nil +} + +func (m *MasterCopyResponse) validateDeployedBlockNumber(formats strfmt.Registry) error { + + if err := validate.Required("deployedBlockNumber", "body", m.DeployedBlockNumber); err != nil { + return err + } + + return nil +} + +func (m *MasterCopyResponse) validateDeployer(formats strfmt.Registry) error { + + if err := validate.Required("deployer", "body", m.Deployer); err != nil { + return err + } + + if err := validate.MinLength("deployer", "body", *m.Deployer, 1); err != nil { + return err + } + + return nil +} + +func (m *MasterCopyResponse) validateL2(formats strfmt.Registry) error { + + if err := validate.Required("l2", "body", m.L2); err != nil { + return err + } + + return nil +} + +func (m *MasterCopyResponse) validateLastIndexedBlockNumber(formats strfmt.Registry) error { + + if err := validate.Required("lastIndexedBlockNumber", "body", m.LastIndexedBlockNumber); err != nil { + return err + } + + return nil +} + +func (m *MasterCopyResponse) validateVersion(formats strfmt.Registry) error { + + if err := validate.Required("version", "body", m.Version); err != nil { + return err + } + + if err := validate.MinLength("version", "body", *m.Version, 1); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this master copy response based on context it is used +func (m *MasterCopyResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *MasterCopyResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MasterCopyResponse) UnmarshalBinary(b []byte) error { + var res MasterCopyResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/modules_response.go b/utils/safe_api/modules_response.go new file mode 100644 index 0000000..2c3930b --- /dev/null +++ b/utils/safe_api/modules_response.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ModulesResponse modules response +// +// swagger:model ModulesResponse +type ModulesResponse struct { + + // safes + // Required: true + Safes []string `json:"safes"` +} + +// Validate validates this modules response +func (m *ModulesResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSafes(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ModulesResponse) validateSafes(formats strfmt.Registry) error { + + if err := validate.Required("safes", "body", m.Safes); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this modules response based on context it is used +func (m *ModulesResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModulesResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModulesResponse) UnmarshalBinary(b []byte) error { + var res ModulesResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/owner_response.go b/utils/safe_api/owner_response.go new file mode 100644 index 0000000..31123d6 --- /dev/null +++ b/utils/safe_api/owner_response.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// OwnerResponse owner response +// +// swagger:model OwnerResponse +type OwnerResponse struct { + + // safes + // Required: true + Safes []string `json:"safes"` +} + +// Validate validates this owner response +func (m *OwnerResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSafes(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *OwnerResponse) validateSafes(formats strfmt.Registry) error { + + if err := validate.Required("safes", "body", m.Safes); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this owner response based on context it is used +func (m *OwnerResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *OwnerResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *OwnerResponse) UnmarshalBinary(b []byte) error { + var res OwnerResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_balance_response.go b/utils/safe_api/safe_balance_response.go new file mode 100644 index 0000000..0afa41f --- /dev/null +++ b/utils/safe_api/safe_balance_response.go @@ -0,0 +1,152 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeBalanceResponse safe balance response +// +// swagger:model SafeBalanceResponse +type SafeBalanceResponse struct { + + // Balance + // Required: true + // Min Length: 1 + Balance *string `json:"balance"` + + // token + // Required: true + Token *Erc20Info `json:"token"` + + // Token address + // Required: true + // Min Length: 1 + TokenAddress *string `json:"tokenAddress"` +} + +// Validate validates this safe balance response +func (m *SafeBalanceResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateBalance(formats); err != nil { + res = append(res, err) + } + + if err := m.validateToken(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTokenAddress(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeBalanceResponse) validateBalance(formats strfmt.Registry) error { + + if err := validate.Required("balance", "body", m.Balance); err != nil { + return err + } + + if err := validate.MinLength("balance", "body", *m.Balance, 1); err != nil { + return err + } + + return nil +} + +func (m *SafeBalanceResponse) validateToken(formats strfmt.Registry) error { + + if err := validate.Required("token", "body", m.Token); err != nil { + return err + } + + if m.Token != nil { + if err := m.Token.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("token") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("token") + } + return err + } + } + + return nil +} + +func (m *SafeBalanceResponse) validateTokenAddress(formats strfmt.Registry) error { + + if err := validate.Required("tokenAddress", "body", m.TokenAddress); err != nil { + return err + } + + if err := validate.MinLength("tokenAddress", "body", *m.TokenAddress, 1); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this safe balance response based on the context it is used +func (m *SafeBalanceResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateToken(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeBalanceResponse) contextValidateToken(ctx context.Context, formats strfmt.Registry) error { + + if m.Token != nil { + + if err := m.Token.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("token") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("token") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SafeBalanceResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeBalanceResponse) UnmarshalBinary(b []byte) error { + var res SafeBalanceResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_collectible_response.go b/utils/safe_api/safe_collectible_response.go new file mode 100644 index 0000000..797a13a --- /dev/null +++ b/utils/safe_api/safe_collectible_response.go @@ -0,0 +1,269 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeCollectibleResponse safe collectible response +// +// swagger:model SafeCollectibleResponse +type SafeCollectibleResponse struct { + + // Address + // Required: true + // Min Length: 1 + Address *string `json:"address"` + + // Description + // Required: true + // Min Length: 1 + Description *string `json:"description"` + + // Id + // Required: true + // Min Length: 1 + ID *string `json:"id"` + + // Image uri + // Required: true + // Min Length: 1 + ImageURI *string `json:"imageUri"` + + // Logo uri + // Required: true + // Min Length: 1 + LogoURI *string `json:"logoUri"` + + // Metadata + // Required: true + Metadata map[string]*string `json:"metadata"` + + // Name + // Required: true + // Min Length: 1 + Name *string `json:"name"` + + // Token name + // Required: true + // Min Length: 1 + TokenName *string `json:"tokenName"` + + // Token symbol + // Required: true + // Min Length: 1 + TokenSymbol *string `json:"tokenSymbol"` + + // Uri + // Required: true + // Min Length: 1 + URI *string `json:"uri"` +} + +// Validate validates this safe collectible response +func (m *SafeCollectibleResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAddress(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDescription(formats); err != nil { + res = append(res, err) + } + + if err := m.validateID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateImageURI(formats); err != nil { + res = append(res, err) + } + + if err := m.validateLogoURI(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMetadata(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTokenName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTokenSymbol(formats); err != nil { + res = append(res, err) + } + + if err := m.validateURI(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeCollectibleResponse) validateAddress(formats strfmt.Registry) error { + + if err := validate.Required("address", "body", m.Address); err != nil { + return err + } + + if err := validate.MinLength("address", "body", *m.Address, 1); err != nil { + return err + } + + return nil +} + +func (m *SafeCollectibleResponse) validateDescription(formats strfmt.Registry) error { + + if err := validate.Required("description", "body", m.Description); err != nil { + return err + } + + if err := validate.MinLength("description", "body", *m.Description, 1); err != nil { + return err + } + + return nil +} + +func (m *SafeCollectibleResponse) validateID(formats strfmt.Registry) error { + + if err := validate.Required("id", "body", m.ID); err != nil { + return err + } + + if err := validate.MinLength("id", "body", *m.ID, 1); err != nil { + return err + } + + return nil +} + +func (m *SafeCollectibleResponse) validateImageURI(formats strfmt.Registry) error { + + if err := validate.Required("imageUri", "body", m.ImageURI); err != nil { + return err + } + + if err := validate.MinLength("imageUri", "body", *m.ImageURI, 1); err != nil { + return err + } + + return nil +} + +func (m *SafeCollectibleResponse) validateLogoURI(formats strfmt.Registry) error { + + if err := validate.Required("logoUri", "body", m.LogoURI); err != nil { + return err + } + + if err := validate.MinLength("logoUri", "body", *m.LogoURI, 1); err != nil { + return err + } + + return nil +} + +func (m *SafeCollectibleResponse) validateMetadata(formats strfmt.Registry) error { + + if err := validate.Required("metadata", "body", m.Metadata); err != nil { + return err + } + + return nil +} + +func (m *SafeCollectibleResponse) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { + return err + } + + return nil +} + +func (m *SafeCollectibleResponse) validateTokenName(formats strfmt.Registry) error { + + if err := validate.Required("tokenName", "body", m.TokenName); err != nil { + return err + } + + if err := validate.MinLength("tokenName", "body", *m.TokenName, 1); err != nil { + return err + } + + return nil +} + +func (m *SafeCollectibleResponse) validateTokenSymbol(formats strfmt.Registry) error { + + if err := validate.Required("tokenSymbol", "body", m.TokenSymbol); err != nil { + return err + } + + if err := validate.MinLength("tokenSymbol", "body", *m.TokenSymbol, 1); err != nil { + return err + } + + return nil +} + +func (m *SafeCollectibleResponse) validateURI(formats strfmt.Registry) error { + + if err := validate.Required("uri", "body", m.URI); err != nil { + return err + } + + if err := validate.MinLength("uri", "body", *m.URI, 1); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this safe collectible response based on context it is used +func (m *SafeCollectibleResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SafeCollectibleResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeCollectibleResponse) UnmarshalBinary(b []byte) error { + var res SafeCollectibleResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_creation_info_response.go b/utils/safe_api/safe_creation_info_response.go new file mode 100644 index 0000000..35e177c --- /dev/null +++ b/utils/safe_api/safe_creation_info_response.go @@ -0,0 +1,232 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeCreationInfoResponse safe creation info response +// +// swagger:model SafeCreationInfoResponse +type SafeCreationInfoResponse struct { + + // Created + // Required: true + // Format: date-time + Created *strfmt.DateTime `json:"created"` + + // Creator + // Required: true + Creator *string `json:"creator"` + + // Data decoded + // Read Only: true + DataDecoded string `json:"dataDecoded,omitempty"` + + // Factory address + // Required: true + FactoryAddress *string `json:"factoryAddress"` + + // Master copy + // Required: true + MasterCopy *string `json:"masterCopy"` + + // Setup data + // Required: true + SetupData *string `json:"setupData"` + + // Transaction hash + // Required: true + TransactionHash *string `json:"transactionHash"` + + // user operation + // Required: true + UserOperation *UserOperationWithSafeOperationResponse `json:"userOperation"` +} + +// Validate validates this safe creation info response +func (m *SafeCreationInfoResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCreated(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCreator(formats); err != nil { + res = append(res, err) + } + + if err := m.validateFactoryAddress(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMasterCopy(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSetupData(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTransactionHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUserOperation(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeCreationInfoResponse) validateCreated(formats strfmt.Registry) error { + + if err := validate.Required("created", "body", m.Created); err != nil { + return err + } + + if err := validate.FormatOf("created", "body", "date-time", m.Created.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeCreationInfoResponse) validateCreator(formats strfmt.Registry) error { + + if err := validate.Required("creator", "body", m.Creator); err != nil { + return err + } + + return nil +} + +func (m *SafeCreationInfoResponse) validateFactoryAddress(formats strfmt.Registry) error { + + if err := validate.Required("factoryAddress", "body", m.FactoryAddress); err != nil { + return err + } + + return nil +} + +func (m *SafeCreationInfoResponse) validateMasterCopy(formats strfmt.Registry) error { + + if err := validate.Required("masterCopy", "body", m.MasterCopy); err != nil { + return err + } + + return nil +} + +func (m *SafeCreationInfoResponse) validateSetupData(formats strfmt.Registry) error { + + if err := validate.Required("setupData", "body", m.SetupData); err != nil { + return err + } + + return nil +} + +func (m *SafeCreationInfoResponse) validateTransactionHash(formats strfmt.Registry) error { + + if err := validate.Required("transactionHash", "body", m.TransactionHash); err != nil { + return err + } + + return nil +} + +func (m *SafeCreationInfoResponse) validateUserOperation(formats strfmt.Registry) error { + + if err := validate.Required("userOperation", "body", m.UserOperation); err != nil { + return err + } + + if m.UserOperation != nil { + if err := m.UserOperation.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("userOperation") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("userOperation") + } + return err + } + } + + return nil +} + +// ContextValidate validate this safe creation info response based on the context it is used +func (m *SafeCreationInfoResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDataDecoded(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateUserOperation(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeCreationInfoResponse) contextValidateDataDecoded(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "dataDecoded", "body", string(m.DataDecoded)); err != nil { + return err + } + + return nil +} + +func (m *SafeCreationInfoResponse) contextValidateUserOperation(ctx context.Context, formats strfmt.Registry) error { + + if m.UserOperation != nil { + + if err := m.UserOperation.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("userOperation") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("userOperation") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SafeCreationInfoResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeCreationInfoResponse) UnmarshalBinary(b []byte) error { + var res SafeCreationInfoResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_delegate_delete.go b/utils/safe_api/safe_delegate_delete.go new file mode 100644 index 0000000..d2d866e --- /dev/null +++ b/utils/safe_api/safe_delegate_delete.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeDelegateDelete safe delegate delete +// +// swagger:model SafeDelegateDelete +type SafeDelegateDelete struct { + + // Delegate + // Required: true + Delegate *string `json:"delegate"` + + // Safe + // Required: true + Safe *string `json:"safe"` + + // Signature + // Required: true + Signature *string `json:"signature"` +} + +// Validate validates this safe delegate delete +func (m *SafeDelegateDelete) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDelegate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafe(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSignature(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeDelegateDelete) validateDelegate(formats strfmt.Registry) error { + + if err := validate.Required("delegate", "body", m.Delegate); err != nil { + return err + } + + return nil +} + +func (m *SafeDelegateDelete) validateSafe(formats strfmt.Registry) error { + + if err := validate.Required("safe", "body", m.Safe); err != nil { + return err + } + + return nil +} + +func (m *SafeDelegateDelete) validateSignature(formats strfmt.Registry) error { + + if err := validate.Required("signature", "body", m.Signature); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this safe delegate delete based on context it is used +func (m *SafeDelegateDelete) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SafeDelegateDelete) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeDelegateDelete) UnmarshalBinary(b []byte) error { + var res SafeDelegateDelete + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_delegate_response.go b/utils/safe_api/safe_delegate_response.go new file mode 100644 index 0000000..a4da305 --- /dev/null +++ b/utils/safe_api/safe_delegate_response.go @@ -0,0 +1,132 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeDelegateResponse safe delegate response +// +// swagger:model SafeDelegateResponse +type SafeDelegateResponse struct { + + // Delegate + // Required: true + Delegate *string `json:"delegate"` + + // Delegator + // Required: true + Delegator *string `json:"delegator"` + + // Label + // Required: true + // Max Length: 50 + // Min Length: 1 + Label *string `json:"label"` + + // Safe + // Required: true + Safe *string `json:"safe"` +} + +// Validate validates this safe delegate response +func (m *SafeDelegateResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDelegate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDelegator(formats); err != nil { + res = append(res, err) + } + + if err := m.validateLabel(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafe(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeDelegateResponse) validateDelegate(formats strfmt.Registry) error { + + if err := validate.Required("delegate", "body", m.Delegate); err != nil { + return err + } + + return nil +} + +func (m *SafeDelegateResponse) validateDelegator(formats strfmt.Registry) error { + + if err := validate.Required("delegator", "body", m.Delegator); err != nil { + return err + } + + return nil +} + +func (m *SafeDelegateResponse) validateLabel(formats strfmt.Registry) error { + + if err := validate.Required("label", "body", m.Label); err != nil { + return err + } + + if err := validate.MinLength("label", "body", *m.Label, 1); err != nil { + return err + } + + if err := validate.MaxLength("label", "body", *m.Label, 50); err != nil { + return err + } + + return nil +} + +func (m *SafeDelegateResponse) validateSafe(formats strfmt.Registry) error { + + if err := validate.Required("safe", "body", m.Safe); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this safe delegate response based on context it is used +func (m *SafeDelegateResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SafeDelegateResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeDelegateResponse) UnmarshalBinary(b []byte) error { + var res SafeDelegateResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_deployment.go b/utils/safe_api/safe_deployment.go new file mode 100644 index 0000000..d5350e6 --- /dev/null +++ b/utils/safe_api/safe_deployment.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeDeployment safe deployment +// +// swagger:model SafeDeployment +type SafeDeployment struct { + + // contracts + // Required: true + Contracts []*SafeDeploymentContract `json:"contracts"` + + // Version + // Required: true + // Max Length: 10 + // Min Length: 1 + Version *string `json:"version"` +} + +// Validate validates this safe deployment +func (m *SafeDeployment) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateContracts(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVersion(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeDeployment) validateContracts(formats strfmt.Registry) error { + + if err := validate.Required("contracts", "body", m.Contracts); err != nil { + return err + } + + for i := 0; i < len(m.Contracts); i++ { + if swag.IsZero(m.Contracts[i]) { // not required + continue + } + + if m.Contracts[i] != nil { + if err := m.Contracts[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("contracts" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("contracts" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *SafeDeployment) validateVersion(formats strfmt.Registry) error { + + if err := validate.Required("version", "body", m.Version); err != nil { + return err + } + + if err := validate.MinLength("version", "body", *m.Version, 1); err != nil { + return err + } + + if err := validate.MaxLength("version", "body", *m.Version, 10); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this safe deployment based on the context it is used +func (m *SafeDeployment) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateContracts(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeDeployment) contextValidateContracts(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Contracts); i++ { + + if m.Contracts[i] != nil { + + if swag.IsZero(m.Contracts[i]) { // not required + return nil + } + + if err := m.Contracts[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("contracts" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("contracts" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SafeDeployment) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeDeployment) UnmarshalBinary(b []byte) error { + var res SafeDeployment + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_deployment_contract.go b/utils/safe_api/safe_deployment_contract.go new file mode 100644 index 0000000..630ad8c --- /dev/null +++ b/utils/safe_api/safe_deployment_contract.go @@ -0,0 +1,93 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeDeploymentContract safe deployment contract +// +// swagger:model SafeDeploymentContract +type SafeDeploymentContract struct { + + // Address + // Required: true + Address *string `json:"address"` + + // Contract name + // Required: true + // Min Length: 1 + ContractName *string `json:"contractName"` +} + +// Validate validates this safe deployment contract +func (m *SafeDeploymentContract) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAddress(formats); err != nil { + res = append(res, err) + } + + if err := m.validateContractName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeDeploymentContract) validateAddress(formats strfmt.Registry) error { + + if err := validate.Required("address", "body", m.Address); err != nil { + return err + } + + return nil +} + +func (m *SafeDeploymentContract) validateContractName(formats strfmt.Registry) error { + + if err := validate.Required("contractName", "body", m.ContractName); err != nil { + return err + } + + if err := validate.MinLength("contractName", "body", *m.ContractName, 1); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this safe deployment contract based on context it is used +func (m *SafeDeploymentContract) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SafeDeploymentContract) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeDeploymentContract) UnmarshalBinary(b []byte) error { + var res SafeDeploymentContract + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_info_response.go b/utils/safe_api/safe_info_response.go new file mode 100644 index 0000000..93ca438 --- /dev/null +++ b/utils/safe_api/safe_info_response.go @@ -0,0 +1,212 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeInfoResponse safe info response +// +// swagger:model SafeInfoResponse +type SafeInfoResponse struct { + + // Address + // Required: true + Address *string `json:"address"` + + // Fallback handler + // Required: true + FallbackHandler *string `json:"fallbackHandler"` + + // Guard + // Required: true + Guard *string `json:"guard"` + + // Master copy + // Required: true + MasterCopy *string `json:"masterCopy"` + + // modules + // Required: true + Modules []string `json:"modules"` + + // Nonce + // Required: true + Nonce *int64 `json:"nonce"` + + // owners + // Required: true + Owners []string `json:"owners"` + + // Threshold + // Required: true + Threshold *int64 `json:"threshold"` + + // Version + // Required: true + // Min Length: 1 + Version *string `json:"version"` +} + +// Validate validates this safe info response +func (m *SafeInfoResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAddress(formats); err != nil { + res = append(res, err) + } + + if err := m.validateFallbackHandler(formats); err != nil { + res = append(res, err) + } + + if err := m.validateGuard(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMasterCopy(formats); err != nil { + res = append(res, err) + } + + if err := m.validateModules(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNonce(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOwners(formats); err != nil { + res = append(res, err) + } + + if err := m.validateThreshold(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVersion(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeInfoResponse) validateAddress(formats strfmt.Registry) error { + + if err := validate.Required("address", "body", m.Address); err != nil { + return err + } + + return nil +} + +func (m *SafeInfoResponse) validateFallbackHandler(formats strfmt.Registry) error { + + if err := validate.Required("fallbackHandler", "body", m.FallbackHandler); err != nil { + return err + } + + return nil +} + +func (m *SafeInfoResponse) validateGuard(formats strfmt.Registry) error { + + if err := validate.Required("guard", "body", m.Guard); err != nil { + return err + } + + return nil +} + +func (m *SafeInfoResponse) validateMasterCopy(formats strfmt.Registry) error { + + if err := validate.Required("masterCopy", "body", m.MasterCopy); err != nil { + return err + } + + return nil +} + +func (m *SafeInfoResponse) validateModules(formats strfmt.Registry) error { + + if err := validate.Required("modules", "body", m.Modules); err != nil { + return err + } + + return nil +} + +func (m *SafeInfoResponse) validateNonce(formats strfmt.Registry) error { + + if err := validate.Required("nonce", "body", m.Nonce); err != nil { + return err + } + + return nil +} + +func (m *SafeInfoResponse) validateOwners(formats strfmt.Registry) error { + + if err := validate.Required("owners", "body", m.Owners); err != nil { + return err + } + + return nil +} + +func (m *SafeInfoResponse) validateThreshold(formats strfmt.Registry) error { + + if err := validate.Required("threshold", "body", m.Threshold); err != nil { + return err + } + + return nil +} + +func (m *SafeInfoResponse) validateVersion(formats strfmt.Registry) error { + + if err := validate.Required("version", "body", m.Version); err != nil { + return err + } + + if err := validate.MinLength("version", "body", *m.Version, 1); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this safe info response based on context it is used +func (m *SafeInfoResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SafeInfoResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeInfoResponse) UnmarshalBinary(b []byte) error { + var res SafeInfoResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_message.go b/utils/safe_api/safe_message.go new file mode 100644 index 0000000..cef74e7 --- /dev/null +++ b/utils/safe_api/safe_message.go @@ -0,0 +1,108 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeMessage safe message +// +// swagger:model SafeMessage +type SafeMessage struct { + + // Message + // Required: true + Message interface{} `json:"message"` + + // Safe app id + // Minimum: 0 + SafeAppID *int64 `json:"safeAppId,omitempty"` + + // Signature + // Required: true + Signature *string `json:"signature"` +} + +// Validate validates this safe message +func (m *SafeMessage) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateMessage(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafeAppID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSignature(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeMessage) validateMessage(formats strfmt.Registry) error { + + if m.Message == nil { + return errors.Required("message", "body", nil) + } + + return nil +} + +func (m *SafeMessage) validateSafeAppID(formats strfmt.Registry) error { + if swag.IsZero(m.SafeAppID) { // not required + return nil + } + + if err := validate.MinimumInt("safeAppId", "body", *m.SafeAppID, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeMessage) validateSignature(formats strfmt.Registry) error { + + if err := validate.Required("signature", "body", m.Signature); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this safe message based on context it is used +func (m *SafeMessage) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SafeMessage) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeMessage) UnmarshalBinary(b []byte) error { + var res SafeMessage + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_message_response.go b/utils/safe_api/safe_message_response.go new file mode 100644 index 0000000..6e2b09a --- /dev/null +++ b/utils/safe_api/safe_message_response.go @@ -0,0 +1,222 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeMessageResponse safe message response +// +// swagger:model SafeMessageResponse +type SafeMessageResponse struct { + + // Confirmations + // Read Only: true + Confirmations string `json:"confirmations,omitempty"` + + // Created + // Required: true + // Format: date-time + Created *strfmt.DateTime `json:"created"` + + // Message + // Required: true + Message interface{} `json:"message"` + + // Message hash + // Required: true + MessageHash *string `json:"messageHash"` + + // Modified + // Required: true + // Format: date-time + Modified *strfmt.DateTime `json:"modified"` + + // Prepared signature + // Read Only: true + PreparedSignature string `json:"preparedSignature,omitempty"` + + // Proposed by + // Required: true + ProposedBy *string `json:"proposedBy"` + + // Safe + // Required: true + Safe *string `json:"safe"` + + // Safe app id + // Required: true + SafeAppID *int64 `json:"safeAppId"` +} + +// Validate validates this safe message response +func (m *SafeMessageResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCreated(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMessage(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMessageHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateModified(formats); err != nil { + res = append(res, err) + } + + if err := m.validateProposedBy(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafe(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafeAppID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeMessageResponse) validateCreated(formats strfmt.Registry) error { + + if err := validate.Required("created", "body", m.Created); err != nil { + return err + } + + if err := validate.FormatOf("created", "body", "date-time", m.Created.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeMessageResponse) validateMessage(formats strfmt.Registry) error { + + if m.Message == nil { + return errors.Required("message", "body", nil) + } + + return nil +} + +func (m *SafeMessageResponse) validateMessageHash(formats strfmt.Registry) error { + + if err := validate.Required("messageHash", "body", m.MessageHash); err != nil { + return err + } + + return nil +} + +func (m *SafeMessageResponse) validateModified(formats strfmt.Registry) error { + + if err := validate.Required("modified", "body", m.Modified); err != nil { + return err + } + + if err := validate.FormatOf("modified", "body", "date-time", m.Modified.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeMessageResponse) validateProposedBy(formats strfmt.Registry) error { + + if err := validate.Required("proposedBy", "body", m.ProposedBy); err != nil { + return err + } + + return nil +} + +func (m *SafeMessageResponse) validateSafe(formats strfmt.Registry) error { + + if err := validate.Required("safe", "body", m.Safe); err != nil { + return err + } + + return nil +} + +func (m *SafeMessageResponse) validateSafeAppID(formats strfmt.Registry) error { + + if err := validate.Required("safeAppId", "body", m.SafeAppID); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this safe message response based on the context it is used +func (m *SafeMessageResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateConfirmations(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidatePreparedSignature(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeMessageResponse) contextValidateConfirmations(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "confirmations", "body", string(m.Confirmations)); err != nil { + return err + } + + return nil +} + +func (m *SafeMessageResponse) contextValidatePreparedSignature(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "preparedSignature", "body", string(m.PreparedSignature)); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SafeMessageResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeMessageResponse) UnmarshalBinary(b []byte) error { + var res SafeMessageResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_message_signature.go b/utils/safe_api/safe_message_signature.go new file mode 100644 index 0000000..89e1c76 --- /dev/null +++ b/utils/safe_api/safe_message_signature.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeMessageSignature safe message signature +// +// swagger:model SafeMessageSignature +type SafeMessageSignature struct { + + // Signature + // Required: true + Signature *string `json:"signature"` +} + +// Validate validates this safe message signature +func (m *SafeMessageSignature) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSignature(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeMessageSignature) validateSignature(formats strfmt.Registry) error { + + if err := validate.Required("signature", "body", m.Signature); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this safe message signature based on context it is used +func (m *SafeMessageSignature) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SafeMessageSignature) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeMessageSignature) UnmarshalBinary(b []byte) error { + var res SafeMessageSignature + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_module_transaction_response.go b/utils/safe_api/safe_module_transaction_response.go new file mode 100644 index 0000000..29ffe2b --- /dev/null +++ b/utils/safe_api/safe_module_transaction_response.go @@ -0,0 +1,347 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeModuleTransactionResponse safe module transaction response +// +// swagger:model SafeModuleTransactionResponse +type SafeModuleTransactionResponse struct { + + // Block number + // Read Only: true + BlockNumber int64 `json:"blockNumber,omitempty"` + + // Created + // Read Only: true + // Format: date-time + Created strfmt.DateTime `json:"created,omitempty"` + + // Data + // Required: true + Data *string `json:"data"` + + // Data decoded + // Read Only: true + DataDecoded string `json:"dataDecoded,omitempty"` + + // Execution date + // Required: true + // Format: date-time + ExecutionDate *strfmt.DateTime `json:"executionDate"` + + // Is successful + // Read Only: true + IsSuccessful *bool `json:"isSuccessful,omitempty"` + + // Module + // Required: true + // Min Length: 1 + Module *string `json:"module"` + + // Module transaction id + // + // Internally calculated parameter to uniquely identify a moduleTransaction + // `ModuleTransactionId = i+tx_hash+trace_address` + // Read Only: true + ModuleTransactionID string `json:"moduleTransactionId,omitempty"` + + // Operation + // Required: true + // Enum: [0,1,2] + Operation *int64 `json:"operation"` + + // Safe + // Required: true + // Min Length: 1 + Safe *string `json:"safe"` + + // To + // Required: true + // Min Length: 1 + To *string `json:"to"` + + // Transaction hash + // Read Only: true + TransactionHash string `json:"transactionHash,omitempty"` + + // Value + // Required: true + Value *string `json:"value"` +} + +// Validate validates this safe module transaction response +func (m *SafeModuleTransactionResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCreated(formats); err != nil { + res = append(res, err) + } + + if err := m.validateData(formats); err != nil { + res = append(res, err) + } + + if err := m.validateExecutionDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateModule(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOperation(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafe(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTo(formats); err != nil { + res = append(res, err) + } + + if err := m.validateValue(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeModuleTransactionResponse) validateCreated(formats strfmt.Registry) error { + if swag.IsZero(m.Created) { // not required + return nil + } + + if err := validate.FormatOf("created", "body", "date-time", m.Created.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionResponse) validateData(formats strfmt.Registry) error { + + if err := validate.Required("data", "body", m.Data); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionResponse) validateExecutionDate(formats strfmt.Registry) error { + + if err := validate.Required("executionDate", "body", m.ExecutionDate); err != nil { + return err + } + + if err := validate.FormatOf("executionDate", "body", "date-time", m.ExecutionDate.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionResponse) validateModule(formats strfmt.Registry) error { + + if err := validate.Required("module", "body", m.Module); err != nil { + return err + } + + if err := validate.MinLength("module", "body", *m.Module, 1); err != nil { + return err + } + + return nil +} + +var safeModuleTransactionResponseTypeOperationPropEnum []interface{} + +func init() { + var res []int64 + if err := json.Unmarshal([]byte(`[0,1,2]`), &res); err != nil { + panic(err) + } + for _, v := range res { + safeModuleTransactionResponseTypeOperationPropEnum = append(safeModuleTransactionResponseTypeOperationPropEnum, v) + } +} + +// prop value enum +func (m *SafeModuleTransactionResponse) validateOperationEnum(path, location string, value int64) error { + if err := validate.EnumCase(path, location, value, safeModuleTransactionResponseTypeOperationPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *SafeModuleTransactionResponse) validateOperation(formats strfmt.Registry) error { + + if err := validate.Required("operation", "body", m.Operation); err != nil { + return err + } + + // value enum + if err := m.validateOperationEnum("operation", "body", *m.Operation); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionResponse) validateSafe(formats strfmt.Registry) error { + + if err := validate.Required("safe", "body", m.Safe); err != nil { + return err + } + + if err := validate.MinLength("safe", "body", *m.Safe, 1); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionResponse) validateTo(formats strfmt.Registry) error { + + if err := validate.Required("to", "body", m.To); err != nil { + return err + } + + if err := validate.MinLength("to", "body", *m.To, 1); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionResponse) validateValue(formats strfmt.Registry) error { + + if err := validate.Required("value", "body", m.Value); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this safe module transaction response based on the context it is used +func (m *SafeModuleTransactionResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateBlockNumber(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateCreated(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateDataDecoded(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateIsSuccessful(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateModuleTransactionID(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateTransactionHash(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeModuleTransactionResponse) contextValidateBlockNumber(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "blockNumber", "body", int64(m.BlockNumber)); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionResponse) contextValidateCreated(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "created", "body", strfmt.DateTime(m.Created)); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionResponse) contextValidateDataDecoded(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "dataDecoded", "body", string(m.DataDecoded)); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionResponse) contextValidateIsSuccessful(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "isSuccessful", "body", m.IsSuccessful); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionResponse) contextValidateModuleTransactionID(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "moduleTransactionId", "body", string(m.ModuleTransactionID)); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionResponse) contextValidateTransactionHash(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "transactionHash", "body", string(m.TransactionHash)); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SafeModuleTransactionResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeModuleTransactionResponse) UnmarshalBinary(b []byte) error { + var res SafeModuleTransactionResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_module_transaction_with_transfers_response.go b/utils/safe_api/safe_module_transaction_with_transfers_response.go new file mode 100644 index 0000000..509587a --- /dev/null +++ b/utils/safe_api/safe_module_transaction_with_transfers_response.go @@ -0,0 +1,429 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeModuleTransactionWithTransfersResponse safe module transaction with transfers response +// +// swagger:model SafeModuleTransactionWithTransfersResponse +type SafeModuleTransactionWithTransfersResponse struct { + + // Block number + // Read Only: true + BlockNumber int64 `json:"blockNumber,omitempty"` + + // Created + // Read Only: true + // Format: date-time + Created strfmt.DateTime `json:"created,omitempty"` + + // Data + // Required: true + Data *string `json:"data"` + + // Data decoded + // Read Only: true + DataDecoded string `json:"dataDecoded,omitempty"` + + // Execution date + // Required: true + // Format: date-time + ExecutionDate *strfmt.DateTime `json:"executionDate"` + + // Is successful + // Read Only: true + IsSuccessful *bool `json:"isSuccessful,omitempty"` + + // Module + // Required: true + // Min Length: 1 + Module *string `json:"module"` + + // Module transaction id + // + // Internally calculated parameter to uniquely identify a moduleTransaction + // `ModuleTransactionId = i+tx_hash+trace_address` + // Read Only: true + ModuleTransactionID string `json:"moduleTransactionId,omitempty"` + + // Operation + // Required: true + // Enum: [0,1,2] + Operation *int64 `json:"operation"` + + // Safe + // Required: true + // Min Length: 1 + Safe *string `json:"safe"` + + // To + // Required: true + // Min Length: 1 + To *string `json:"to"` + + // Transaction hash + // Read Only: true + TransactionHash string `json:"transactionHash,omitempty"` + + // transfers + // Required: true + Transfers []*TransferWithTokenInfoResponse `json:"transfers"` + + // Tx type + // Read Only: true + TxType string `json:"txType,omitempty"` + + // Value + // Required: true + Value *string `json:"value"` +} + +// Validate validates this safe module transaction with transfers response +func (m *SafeModuleTransactionWithTransfersResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCreated(formats); err != nil { + res = append(res, err) + } + + if err := m.validateData(formats); err != nil { + res = append(res, err) + } + + if err := m.validateExecutionDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateModule(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOperation(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafe(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTo(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTransfers(formats); err != nil { + res = append(res, err) + } + + if err := m.validateValue(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeModuleTransactionWithTransfersResponse) validateCreated(formats strfmt.Registry) error { + if swag.IsZero(m.Created) { // not required + return nil + } + + if err := validate.FormatOf("created", "body", "date-time", m.Created.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionWithTransfersResponse) validateData(formats strfmt.Registry) error { + + if err := validate.Required("data", "body", m.Data); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionWithTransfersResponse) validateExecutionDate(formats strfmt.Registry) error { + + if err := validate.Required("executionDate", "body", m.ExecutionDate); err != nil { + return err + } + + if err := validate.FormatOf("executionDate", "body", "date-time", m.ExecutionDate.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionWithTransfersResponse) validateModule(formats strfmt.Registry) error { + + if err := validate.Required("module", "body", m.Module); err != nil { + return err + } + + if err := validate.MinLength("module", "body", *m.Module, 1); err != nil { + return err + } + + return nil +} + +var safeModuleTransactionWithTransfersResponseTypeOperationPropEnum []interface{} + +func init() { + var res []int64 + if err := json.Unmarshal([]byte(`[0,1,2]`), &res); err != nil { + panic(err) + } + for _, v := range res { + safeModuleTransactionWithTransfersResponseTypeOperationPropEnum = append(safeModuleTransactionWithTransfersResponseTypeOperationPropEnum, v) + } +} + +// prop value enum +func (m *SafeModuleTransactionWithTransfersResponse) validateOperationEnum(path, location string, value int64) error { + if err := validate.EnumCase(path, location, value, safeModuleTransactionWithTransfersResponseTypeOperationPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *SafeModuleTransactionWithTransfersResponse) validateOperation(formats strfmt.Registry) error { + + if err := validate.Required("operation", "body", m.Operation); err != nil { + return err + } + + // value enum + if err := m.validateOperationEnum("operation", "body", *m.Operation); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionWithTransfersResponse) validateSafe(formats strfmt.Registry) error { + + if err := validate.Required("safe", "body", m.Safe); err != nil { + return err + } + + if err := validate.MinLength("safe", "body", *m.Safe, 1); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionWithTransfersResponse) validateTo(formats strfmt.Registry) error { + + if err := validate.Required("to", "body", m.To); err != nil { + return err + } + + if err := validate.MinLength("to", "body", *m.To, 1); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionWithTransfersResponse) validateTransfers(formats strfmt.Registry) error { + + if err := validate.Required("transfers", "body", m.Transfers); err != nil { + return err + } + + for i := 0; i < len(m.Transfers); i++ { + if swag.IsZero(m.Transfers[i]) { // not required + continue + } + + if m.Transfers[i] != nil { + if err := m.Transfers[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("transfers" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("transfers" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *SafeModuleTransactionWithTransfersResponse) validateValue(formats strfmt.Registry) error { + + if err := validate.Required("value", "body", m.Value); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this safe module transaction with transfers response based on the context it is used +func (m *SafeModuleTransactionWithTransfersResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateBlockNumber(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateCreated(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateDataDecoded(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateIsSuccessful(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateModuleTransactionID(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateTransactionHash(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateTransfers(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateTxType(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeModuleTransactionWithTransfersResponse) contextValidateBlockNumber(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "blockNumber", "body", int64(m.BlockNumber)); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionWithTransfersResponse) contextValidateCreated(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "created", "body", strfmt.DateTime(m.Created)); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionWithTransfersResponse) contextValidateDataDecoded(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "dataDecoded", "body", string(m.DataDecoded)); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionWithTransfersResponse) contextValidateIsSuccessful(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "isSuccessful", "body", m.IsSuccessful); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionWithTransfersResponse) contextValidateModuleTransactionID(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "moduleTransactionId", "body", string(m.ModuleTransactionID)); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionWithTransfersResponse) contextValidateTransactionHash(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "transactionHash", "body", string(m.TransactionHash)); err != nil { + return err + } + + return nil +} + +func (m *SafeModuleTransactionWithTransfersResponse) contextValidateTransfers(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Transfers); i++ { + + if m.Transfers[i] != nil { + + if swag.IsZero(m.Transfers[i]) { // not required + return nil + } + + if err := m.Transfers[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("transfers" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("transfers" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *SafeModuleTransactionWithTransfersResponse) contextValidateTxType(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "txType", "body", string(m.TxType)); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SafeModuleTransactionWithTransfersResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeModuleTransactionWithTransfersResponse) UnmarshalBinary(b []byte) error { + var res SafeModuleTransactionWithTransfersResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_multisig_confirmation.go b/utils/safe_api/safe_multisig_confirmation.go new file mode 100644 index 0000000..e40db0c --- /dev/null +++ b/utils/safe_api/safe_multisig_confirmation.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeMultisigConfirmation safe multisig confirmation +// +// swagger:model SafeMultisigConfirmation +type SafeMultisigConfirmation struct { + + // Signature + // Required: true + Signature *string `json:"signature"` +} + +// Validate validates this safe multisig confirmation +func (m *SafeMultisigConfirmation) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSignature(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeMultisigConfirmation) validateSignature(formats strfmt.Registry) error { + + if err := validate.Required("signature", "body", m.Signature); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this safe multisig confirmation based on context it is used +func (m *SafeMultisigConfirmation) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SafeMultisigConfirmation) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeMultisigConfirmation) UnmarshalBinary(b []byte) error { + var res SafeMultisigConfirmation + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_multisig_confirmation_response.go b/utils/safe_api/safe_multisig_confirmation_response.go new file mode 100644 index 0000000..1536a91 --- /dev/null +++ b/utils/safe_api/safe_multisig_confirmation_response.go @@ -0,0 +1,157 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeMultisigConfirmationResponse +// Filters confirmations queryset +// :param obj: MultisigConfirmation instance +// :return: Serialized queryset +// +// swagger:model SafeMultisigConfirmationResponse +type SafeMultisigConfirmationResponse struct { + + // Owner + // Required: true + // Min Length: 1 + Owner *string `json:"owner"` + + // Signature + // Required: true + Signature *string `json:"signature"` + + // Signature type + // Read Only: true + SignatureType string `json:"signatureType,omitempty"` + + // Submission date + // Required: true + // Format: date-time + SubmissionDate *strfmt.DateTime `json:"submissionDate"` + + // Transaction hash + // Read Only: true + TransactionHash string `json:"transactionHash,omitempty"` +} + +// Validate validates this safe multisig confirmation response +func (m *SafeMultisigConfirmationResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateOwner(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSignature(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSubmissionDate(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeMultisigConfirmationResponse) validateOwner(formats strfmt.Registry) error { + + if err := validate.Required("owner", "body", m.Owner); err != nil { + return err + } + + if err := validate.MinLength("owner", "body", *m.Owner, 1); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigConfirmationResponse) validateSignature(formats strfmt.Registry) error { + + if err := validate.Required("signature", "body", m.Signature); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigConfirmationResponse) validateSubmissionDate(formats strfmt.Registry) error { + + if err := validate.Required("submissionDate", "body", m.SubmissionDate); err != nil { + return err + } + + if err := validate.FormatOf("submissionDate", "body", "date-time", m.SubmissionDate.String(), formats); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this safe multisig confirmation response based on the context it is used +func (m *SafeMultisigConfirmationResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSignatureType(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateTransactionHash(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeMultisigConfirmationResponse) contextValidateSignatureType(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "signatureType", "body", string(m.SignatureType)); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigConfirmationResponse) contextValidateTransactionHash(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "transactionHash", "body", string(m.TransactionHash)); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SafeMultisigConfirmationResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeMultisigConfirmationResponse) UnmarshalBinary(b []byte) error { + var res SafeMultisigConfirmationResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_multisig_transaction.go b/utils/safe_api/safe_multisig_transaction.go new file mode 100644 index 0000000..d2f6b3e --- /dev/null +++ b/utils/safe_api/safe_multisig_transaction.go @@ -0,0 +1,291 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeMultisigTransaction safe multisig transaction +// +// swagger:model SafeMultisigTransaction +type SafeMultisigTransaction struct { + + // Base gas + // Required: true + // Minimum: 0 + BaseGas *int64 `json:"baseGas"` + + // Contract transaction hash + // Required: true + ContractTransactionHash *string `json:"contractTransactionHash"` + + // Data + Data *string `json:"data,omitempty"` + + // Gas price + // Required: true + // Minimum: 0 + GasPrice *int64 `json:"gasPrice"` + + // Gas token + GasToken *string `json:"gasToken,omitempty"` + + // Nonce + // Required: true + // Minimum: 0 + Nonce *int64 `json:"nonce"` + + // Operation + // Required: true + // Minimum: 0 + Operation *int64 `json:"operation"` + + // Origin + // Max Length: 200 + // Min Length: 1 + Origin *string `json:"origin,omitempty"` + + // Refund receiver + RefundReceiver *string `json:"refundReceiver,omitempty"` + + // Safe + // Required: true + Safe *string `json:"safe"` + + // Safe tx gas + // Required: true + // Minimum: 0 + SafeTxGas *int64 `json:"safeTxGas"` + + // Sender + // Required: true + Sender *string `json:"sender"` + + // Signature + Signature *string `json:"signature,omitempty"` + + // To + // Required: true + To *string `json:"to"` + + // Value + // Required: true + // Minimum: 0 + Value *int64 `json:"value"` +} + +// Validate validates this safe multisig transaction +func (m *SafeMultisigTransaction) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateBaseGas(formats); err != nil { + res = append(res, err) + } + + if err := m.validateContractTransactionHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateGasPrice(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNonce(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOperation(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOrigin(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafe(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafeTxGas(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSender(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTo(formats); err != nil { + res = append(res, err) + } + + if err := m.validateValue(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeMultisigTransaction) validateBaseGas(formats strfmt.Registry) error { + + if err := validate.Required("baseGas", "body", m.BaseGas); err != nil { + return err + } + + if err := validate.MinimumInt("baseGas", "body", *m.BaseGas, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransaction) validateContractTransactionHash(formats strfmt.Registry) error { + + if err := validate.Required("contractTransactionHash", "body", m.ContractTransactionHash); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransaction) validateGasPrice(formats strfmt.Registry) error { + + if err := validate.Required("gasPrice", "body", m.GasPrice); err != nil { + return err + } + + if err := validate.MinimumInt("gasPrice", "body", *m.GasPrice, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransaction) validateNonce(formats strfmt.Registry) error { + + if err := validate.Required("nonce", "body", m.Nonce); err != nil { + return err + } + + if err := validate.MinimumInt("nonce", "body", *m.Nonce, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransaction) validateOperation(formats strfmt.Registry) error { + + if err := validate.Required("operation", "body", m.Operation); err != nil { + return err + } + + if err := validate.MinimumInt("operation", "body", *m.Operation, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransaction) validateOrigin(formats strfmt.Registry) error { + if swag.IsZero(m.Origin) { // not required + return nil + } + + if err := validate.MinLength("origin", "body", *m.Origin, 1); err != nil { + return err + } + + if err := validate.MaxLength("origin", "body", *m.Origin, 200); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransaction) validateSafe(formats strfmt.Registry) error { + + if err := validate.Required("safe", "body", m.Safe); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransaction) validateSafeTxGas(formats strfmt.Registry) error { + + if err := validate.Required("safeTxGas", "body", m.SafeTxGas); err != nil { + return err + } + + if err := validate.MinimumInt("safeTxGas", "body", *m.SafeTxGas, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransaction) validateSender(formats strfmt.Registry) error { + + if err := validate.Required("sender", "body", m.Sender); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransaction) validateTo(formats strfmt.Registry) error { + + if err := validate.Required("to", "body", m.To); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransaction) validateValue(formats strfmt.Registry) error { + + if err := validate.Required("value", "body", m.Value); err != nil { + return err + } + + if err := validate.MinimumInt("value", "body", *m.Value, 0, false); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this safe multisig transaction based on context it is used +func (m *SafeMultisigTransaction) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SafeMultisigTransaction) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeMultisigTransaction) UnmarshalBinary(b []byte) error { + var res SafeMultisigTransaction + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_multisig_transaction_delete.go b/utils/safe_api/safe_multisig_transaction_delete.go new file mode 100644 index 0000000..0e725f1 --- /dev/null +++ b/utils/safe_api/safe_multisig_transaction_delete.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeMultisigTransactionDelete safe multisig transaction delete +// +// swagger:model SafeMultisigTransactionDelete +type SafeMultisigTransactionDelete struct { + + // Safe tx hash + // Required: true + SafeTxHash *string `json:"safeTxHash"` + + // Signature + // Required: true + Signature *string `json:"signature"` +} + +// Validate validates this safe multisig transaction delete +func (m *SafeMultisigTransactionDelete) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSafeTxHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSignature(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeMultisigTransactionDelete) validateSafeTxHash(formats strfmt.Registry) error { + + if err := validate.Required("safeTxHash", "body", m.SafeTxHash); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionDelete) validateSignature(formats strfmt.Registry) error { + + if err := validate.Required("signature", "body", m.Signature); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this safe multisig transaction delete based on context it is used +func (m *SafeMultisigTransactionDelete) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SafeMultisigTransactionDelete) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeMultisigTransactionDelete) UnmarshalBinary(b []byte) error { + var res SafeMultisigTransactionDelete + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_multisig_transaction_estimate.go b/utils/safe_api/safe_multisig_transaction_estimate.go new file mode 100644 index 0000000..d83bd5e --- /dev/null +++ b/utils/safe_api/safe_multisig_transaction_estimate.go @@ -0,0 +1,118 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeMultisigTransactionEstimate safe multisig transaction estimate +// +// swagger:model SafeMultisigTransactionEstimate +type SafeMultisigTransactionEstimate struct { + + // Data + Data *string `json:"data,omitempty"` + + // Operation + // Required: true + // Minimum: 0 + Operation *int64 `json:"operation"` + + // To + // Required: true + To *string `json:"to"` + + // Value + // Required: true + // Minimum: 0 + Value *int64 `json:"value"` +} + +// Validate validates this safe multisig transaction estimate +func (m *SafeMultisigTransactionEstimate) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateOperation(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTo(formats); err != nil { + res = append(res, err) + } + + if err := m.validateValue(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeMultisigTransactionEstimate) validateOperation(formats strfmt.Registry) error { + + if err := validate.Required("operation", "body", m.Operation); err != nil { + return err + } + + if err := validate.MinimumInt("operation", "body", *m.Operation, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionEstimate) validateTo(formats strfmt.Registry) error { + + if err := validate.Required("to", "body", m.To); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionEstimate) validateValue(formats strfmt.Registry) error { + + if err := validate.Required("value", "body", m.Value); err != nil { + return err + } + + if err := validate.MinimumInt("value", "body", *m.Value, 0, false); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this safe multisig transaction estimate based on context it is used +func (m *SafeMultisigTransactionEstimate) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SafeMultisigTransactionEstimate) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeMultisigTransactionEstimate) UnmarshalBinary(b []byte) error { + var res SafeMultisigTransactionEstimate + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_multisig_transaction_estimate_response.go b/utils/safe_api/safe_multisig_transaction_estimate_response.go new file mode 100644 index 0000000..8215b78 --- /dev/null +++ b/utils/safe_api/safe_multisig_transaction_estimate_response.go @@ -0,0 +1,76 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeMultisigTransactionEstimateResponse safe multisig transaction estimate response +// +// swagger:model SafeMultisigTransactionEstimateResponse +type SafeMultisigTransactionEstimateResponse struct { + + // Safe tx gas + // Required: true + // Min Length: 1 + SafeTxGas *string `json:"safeTxGas"` +} + +// Validate validates this safe multisig transaction estimate response +func (m *SafeMultisigTransactionEstimateResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSafeTxGas(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeMultisigTransactionEstimateResponse) validateSafeTxGas(formats strfmt.Registry) error { + + if err := validate.Required("safeTxGas", "body", m.SafeTxGas); err != nil { + return err + } + + if err := validate.MinLength("safeTxGas", "body", *m.SafeTxGas, 1); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this safe multisig transaction estimate response based on context it is used +func (m *SafeMultisigTransactionEstimateResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SafeMultisigTransactionEstimateResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeMultisigTransactionEstimateResponse) UnmarshalBinary(b []byte) error { + var res SafeMultisigTransactionEstimateResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_multisig_transaction_response.go b/utils/safe_api/safe_multisig_transaction_response.go new file mode 100644 index 0000000..db1d01a --- /dev/null +++ b/utils/safe_api/safe_multisig_transaction_response.go @@ -0,0 +1,626 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeMultisigTransactionResponse safe multisig transaction response +// +// swagger:model SafeMultisigTransactionResponse +type SafeMultisigTransactionResponse struct { + + // Base gas + // Required: true + // Minimum: 0 + BaseGas *int64 `json:"baseGas"` + + // Block number + // Read Only: true + BlockNumber int64 `json:"blockNumber,omitempty"` + + // confirmations + Confirmations *SafeMultisigConfirmationResponse `json:"confirmations,omitempty"` + + // Confirmations required + // Required: true + ConfirmationsRequired *int64 `json:"confirmationsRequired"` + + // Data + Data *string `json:"data,omitempty"` + + // Data decoded + // Read Only: true + DataDecoded string `json:"dataDecoded,omitempty"` + + // Eth gas price + // Read Only: true + EthGasPrice string `json:"ethGasPrice,omitempty"` + + // Execution date + // Required: true + // Format: date-time + ExecutionDate *strfmt.DateTime `json:"executionDate"` + + // Executor + // Read Only: true + Executor string `json:"executor,omitempty"` + + // Fee + // Read Only: true + Fee int64 `json:"fee,omitempty"` + + // Gas price + // Required: true + // Min Length: 1 + GasPrice *string `json:"gasPrice"` + + // Gas token + GasToken *string `json:"gasToken,omitempty"` + + // Gas used + // Read Only: true + GasUsed int64 `json:"gasUsed,omitempty"` + + // Is executed + // Required: true + IsExecuted *bool `json:"isExecuted"` + + // Is successful + // Read Only: true + IsSuccessful *bool `json:"isSuccessful,omitempty"` + + // Max fee per gas + // Read Only: true + MaxFeePerGas string `json:"maxFeePerGas,omitempty"` + + // Max priority fee per gas + // Read Only: true + MaxPriorityFeePerGas string `json:"maxPriorityFeePerGas,omitempty"` + + // Modified + // Required: true + // Format: date-time + Modified *strfmt.DateTime `json:"modified"` + + // Nonce + // Required: true + // Minimum: 0 + Nonce *int64 `json:"nonce"` + + // Operation + // Required: true + // Minimum: 0 + Operation *int64 `json:"operation"` + + // Origin + // Read Only: true + Origin string `json:"origin,omitempty"` + + // Proposer + // Required: true + Proposer *string `json:"proposer"` + + // Refund receiver + RefundReceiver *string `json:"refundReceiver,omitempty"` + + // Safe + // Required: true + Safe *string `json:"safe"` + + // Safe tx gas + // Required: true + // Minimum: 0 + SafeTxGas *int64 `json:"safeTxGas"` + + // Safe tx hash + // Required: true + SafeTxHash *string `json:"safeTxHash"` + + // Signatures + Signatures *string `json:"signatures,omitempty"` + + // Submission date + // Required: true + // Format: date-time + SubmissionDate *strfmt.DateTime `json:"submissionDate"` + + // To + // Required: true + To *string `json:"to"` + + // Transaction hash + // Required: true + TransactionHash *string `json:"transactionHash"` + + // Trusted + // Required: true + Trusted *bool `json:"trusted"` + + // Value + // Required: true + // Min Length: 1 + Value *string `json:"value"` +} + +// Validate validates this safe multisig transaction response +func (m *SafeMultisigTransactionResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateBaseGas(formats); err != nil { + res = append(res, err) + } + + if err := m.validateConfirmations(formats); err != nil { + res = append(res, err) + } + + if err := m.validateConfirmationsRequired(formats); err != nil { + res = append(res, err) + } + + if err := m.validateExecutionDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateGasPrice(formats); err != nil { + res = append(res, err) + } + + if err := m.validateIsExecuted(formats); err != nil { + res = append(res, err) + } + + if err := m.validateModified(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNonce(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOperation(formats); err != nil { + res = append(res, err) + } + + if err := m.validateProposer(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafe(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafeTxGas(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafeTxHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSubmissionDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTo(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTransactionHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTrusted(formats); err != nil { + res = append(res, err) + } + + if err := m.validateValue(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeMultisigTransactionResponse) validateBaseGas(formats strfmt.Registry) error { + + if err := validate.Required("baseGas", "body", m.BaseGas); err != nil { + return err + } + + if err := validate.MinimumInt("baseGas", "body", *m.BaseGas, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) validateConfirmations(formats strfmt.Registry) error { + if swag.IsZero(m.Confirmations) { // not required + return nil + } + + if m.Confirmations != nil { + if err := m.Confirmations.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("confirmations") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("confirmations") + } + return err + } + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) validateConfirmationsRequired(formats strfmt.Registry) error { + + if err := validate.Required("confirmationsRequired", "body", m.ConfirmationsRequired); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) validateExecutionDate(formats strfmt.Registry) error { + + if err := validate.Required("executionDate", "body", m.ExecutionDate); err != nil { + return err + } + + if err := validate.FormatOf("executionDate", "body", "date-time", m.ExecutionDate.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) validateGasPrice(formats strfmt.Registry) error { + + if err := validate.Required("gasPrice", "body", m.GasPrice); err != nil { + return err + } + + if err := validate.MinLength("gasPrice", "body", *m.GasPrice, 1); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) validateIsExecuted(formats strfmt.Registry) error { + + if err := validate.Required("isExecuted", "body", m.IsExecuted); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) validateModified(formats strfmt.Registry) error { + + if err := validate.Required("modified", "body", m.Modified); err != nil { + return err + } + + if err := validate.FormatOf("modified", "body", "date-time", m.Modified.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) validateNonce(formats strfmt.Registry) error { + + if err := validate.Required("nonce", "body", m.Nonce); err != nil { + return err + } + + if err := validate.MinimumInt("nonce", "body", *m.Nonce, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) validateOperation(formats strfmt.Registry) error { + + if err := validate.Required("operation", "body", m.Operation); err != nil { + return err + } + + if err := validate.MinimumInt("operation", "body", *m.Operation, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) validateProposer(formats strfmt.Registry) error { + + if err := validate.Required("proposer", "body", m.Proposer); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) validateSafe(formats strfmt.Registry) error { + + if err := validate.Required("safe", "body", m.Safe); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) validateSafeTxGas(formats strfmt.Registry) error { + + if err := validate.Required("safeTxGas", "body", m.SafeTxGas); err != nil { + return err + } + + if err := validate.MinimumInt("safeTxGas", "body", *m.SafeTxGas, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) validateSafeTxHash(formats strfmt.Registry) error { + + if err := validate.Required("safeTxHash", "body", m.SafeTxHash); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) validateSubmissionDate(formats strfmt.Registry) error { + + if err := validate.Required("submissionDate", "body", m.SubmissionDate); err != nil { + return err + } + + if err := validate.FormatOf("submissionDate", "body", "date-time", m.SubmissionDate.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) validateTo(formats strfmt.Registry) error { + + if err := validate.Required("to", "body", m.To); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) validateTransactionHash(formats strfmt.Registry) error { + + if err := validate.Required("transactionHash", "body", m.TransactionHash); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) validateTrusted(formats strfmt.Registry) error { + + if err := validate.Required("trusted", "body", m.Trusted); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) validateValue(formats strfmt.Registry) error { + + if err := validate.Required("value", "body", m.Value); err != nil { + return err + } + + if err := validate.MinLength("value", "body", *m.Value, 1); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this safe multisig transaction response based on the context it is used +func (m *SafeMultisigTransactionResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateBlockNumber(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateConfirmations(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateDataDecoded(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateEthGasPrice(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateExecutor(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateFee(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateGasUsed(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateIsSuccessful(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateMaxFeePerGas(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateMaxPriorityFeePerGas(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateOrigin(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeMultisigTransactionResponse) contextValidateBlockNumber(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "blockNumber", "body", int64(m.BlockNumber)); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) contextValidateConfirmations(ctx context.Context, formats strfmt.Registry) error { + + if m.Confirmations != nil { + + if swag.IsZero(m.Confirmations) { // not required + return nil + } + + if err := m.Confirmations.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("confirmations") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("confirmations") + } + return err + } + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) contextValidateDataDecoded(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "dataDecoded", "body", string(m.DataDecoded)); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) contextValidateEthGasPrice(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "ethGasPrice", "body", string(m.EthGasPrice)); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) contextValidateExecutor(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "executor", "body", string(m.Executor)); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) contextValidateFee(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "fee", "body", int64(m.Fee)); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) contextValidateGasUsed(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "gasUsed", "body", int64(m.GasUsed)); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) contextValidateIsSuccessful(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "isSuccessful", "body", m.IsSuccessful); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) contextValidateMaxFeePerGas(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "maxFeePerGas", "body", string(m.MaxFeePerGas)); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) contextValidateMaxPriorityFeePerGas(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "maxPriorityFeePerGas", "body", string(m.MaxPriorityFeePerGas)); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionResponse) contextValidateOrigin(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "origin", "body", string(m.Origin)); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SafeMultisigTransactionResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeMultisigTransactionResponse) UnmarshalBinary(b []byte) error { + var res SafeMultisigTransactionResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_multisig_transaction_with_transfers_response.go b/utils/safe_api/safe_multisig_transaction_with_transfers_response.go new file mode 100644 index 0000000..a11231f --- /dev/null +++ b/utils/safe_api/safe_multisig_transaction_with_transfers_response.go @@ -0,0 +1,708 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeMultisigTransactionWithTransfersResponse safe multisig transaction with transfers response +// +// swagger:model SafeMultisigTransactionWithTransfersResponse +type SafeMultisigTransactionWithTransfersResponse struct { + + // Base gas + // Required: true + // Minimum: 0 + BaseGas *int64 `json:"baseGas"` + + // Block number + // Read Only: true + BlockNumber int64 `json:"blockNumber,omitempty"` + + // confirmations + Confirmations *SafeMultisigConfirmationResponse `json:"confirmations,omitempty"` + + // Confirmations required + // Required: true + ConfirmationsRequired *int64 `json:"confirmationsRequired"` + + // Data + Data *string `json:"data,omitempty"` + + // Data decoded + // Read Only: true + DataDecoded string `json:"dataDecoded,omitempty"` + + // Eth gas price + // Read Only: true + EthGasPrice string `json:"ethGasPrice,omitempty"` + + // Execution date + // Required: true + // Format: date-time + ExecutionDate *strfmt.DateTime `json:"executionDate"` + + // Executor + // Read Only: true + Executor string `json:"executor,omitempty"` + + // Fee + // Read Only: true + Fee int64 `json:"fee,omitempty"` + + // Gas price + // Required: true + // Min Length: 1 + GasPrice *string `json:"gasPrice"` + + // Gas token + GasToken *string `json:"gasToken,omitempty"` + + // Gas used + // Read Only: true + GasUsed int64 `json:"gasUsed,omitempty"` + + // Is executed + // Required: true + IsExecuted *bool `json:"isExecuted"` + + // Is successful + // Read Only: true + IsSuccessful *bool `json:"isSuccessful,omitempty"` + + // Max fee per gas + // Read Only: true + MaxFeePerGas string `json:"maxFeePerGas,omitempty"` + + // Max priority fee per gas + // Read Only: true + MaxPriorityFeePerGas string `json:"maxPriorityFeePerGas,omitempty"` + + // Modified + // Required: true + // Format: date-time + Modified *strfmt.DateTime `json:"modified"` + + // Nonce + // Required: true + // Minimum: 0 + Nonce *int64 `json:"nonce"` + + // Operation + // Required: true + // Minimum: 0 + Operation *int64 `json:"operation"` + + // Origin + // Read Only: true + Origin string `json:"origin,omitempty"` + + // Proposer + // Required: true + Proposer *string `json:"proposer"` + + // Refund receiver + RefundReceiver *string `json:"refundReceiver,omitempty"` + + // Safe + // Required: true + Safe *string `json:"safe"` + + // Safe tx gas + // Required: true + // Minimum: 0 + SafeTxGas *int64 `json:"safeTxGas"` + + // Safe tx hash + // Required: true + SafeTxHash *string `json:"safeTxHash"` + + // Signatures + Signatures *string `json:"signatures,omitempty"` + + // Submission date + // Required: true + // Format: date-time + SubmissionDate *strfmt.DateTime `json:"submissionDate"` + + // To + // Required: true + To *string `json:"to"` + + // Transaction hash + // Required: true + TransactionHash *string `json:"transactionHash"` + + // transfers + // Required: true + Transfers []*TransferWithTokenInfoResponse `json:"transfers"` + + // Trusted + // Required: true + Trusted *bool `json:"trusted"` + + // Tx type + // Read Only: true + TxType string `json:"txType,omitempty"` + + // Value + // Required: true + // Min Length: 1 + Value *string `json:"value"` +} + +// Validate validates this safe multisig transaction with transfers response +func (m *SafeMultisigTransactionWithTransfersResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateBaseGas(formats); err != nil { + res = append(res, err) + } + + if err := m.validateConfirmations(formats); err != nil { + res = append(res, err) + } + + if err := m.validateConfirmationsRequired(formats); err != nil { + res = append(res, err) + } + + if err := m.validateExecutionDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateGasPrice(formats); err != nil { + res = append(res, err) + } + + if err := m.validateIsExecuted(formats); err != nil { + res = append(res, err) + } + + if err := m.validateModified(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNonce(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOperation(formats); err != nil { + res = append(res, err) + } + + if err := m.validateProposer(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafe(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafeTxGas(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafeTxHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSubmissionDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTo(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTransactionHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTransfers(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTrusted(formats); err != nil { + res = append(res, err) + } + + if err := m.validateValue(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateBaseGas(formats strfmt.Registry) error { + + if err := validate.Required("baseGas", "body", m.BaseGas); err != nil { + return err + } + + if err := validate.MinimumInt("baseGas", "body", *m.BaseGas, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateConfirmations(formats strfmt.Registry) error { + if swag.IsZero(m.Confirmations) { // not required + return nil + } + + if m.Confirmations != nil { + if err := m.Confirmations.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("confirmations") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("confirmations") + } + return err + } + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateConfirmationsRequired(formats strfmt.Registry) error { + + if err := validate.Required("confirmationsRequired", "body", m.ConfirmationsRequired); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateExecutionDate(formats strfmt.Registry) error { + + if err := validate.Required("executionDate", "body", m.ExecutionDate); err != nil { + return err + } + + if err := validate.FormatOf("executionDate", "body", "date-time", m.ExecutionDate.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateGasPrice(formats strfmt.Registry) error { + + if err := validate.Required("gasPrice", "body", m.GasPrice); err != nil { + return err + } + + if err := validate.MinLength("gasPrice", "body", *m.GasPrice, 1); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateIsExecuted(formats strfmt.Registry) error { + + if err := validate.Required("isExecuted", "body", m.IsExecuted); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateModified(formats strfmt.Registry) error { + + if err := validate.Required("modified", "body", m.Modified); err != nil { + return err + } + + if err := validate.FormatOf("modified", "body", "date-time", m.Modified.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateNonce(formats strfmt.Registry) error { + + if err := validate.Required("nonce", "body", m.Nonce); err != nil { + return err + } + + if err := validate.MinimumInt("nonce", "body", *m.Nonce, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateOperation(formats strfmt.Registry) error { + + if err := validate.Required("operation", "body", m.Operation); err != nil { + return err + } + + if err := validate.MinimumInt("operation", "body", *m.Operation, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateProposer(formats strfmt.Registry) error { + + if err := validate.Required("proposer", "body", m.Proposer); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateSafe(formats strfmt.Registry) error { + + if err := validate.Required("safe", "body", m.Safe); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateSafeTxGas(formats strfmt.Registry) error { + + if err := validate.Required("safeTxGas", "body", m.SafeTxGas); err != nil { + return err + } + + if err := validate.MinimumInt("safeTxGas", "body", *m.SafeTxGas, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateSafeTxHash(formats strfmt.Registry) error { + + if err := validate.Required("safeTxHash", "body", m.SafeTxHash); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateSubmissionDate(formats strfmt.Registry) error { + + if err := validate.Required("submissionDate", "body", m.SubmissionDate); err != nil { + return err + } + + if err := validate.FormatOf("submissionDate", "body", "date-time", m.SubmissionDate.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateTo(formats strfmt.Registry) error { + + if err := validate.Required("to", "body", m.To); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateTransactionHash(formats strfmt.Registry) error { + + if err := validate.Required("transactionHash", "body", m.TransactionHash); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateTransfers(formats strfmt.Registry) error { + + if err := validate.Required("transfers", "body", m.Transfers); err != nil { + return err + } + + for i := 0; i < len(m.Transfers); i++ { + if swag.IsZero(m.Transfers[i]) { // not required + continue + } + + if m.Transfers[i] != nil { + if err := m.Transfers[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("transfers" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("transfers" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateTrusted(formats strfmt.Registry) error { + + if err := validate.Required("trusted", "body", m.Trusted); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) validateValue(formats strfmt.Registry) error { + + if err := validate.Required("value", "body", m.Value); err != nil { + return err + } + + if err := validate.MinLength("value", "body", *m.Value, 1); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this safe multisig transaction with transfers response based on the context it is used +func (m *SafeMultisigTransactionWithTransfersResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateBlockNumber(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateConfirmations(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateDataDecoded(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateEthGasPrice(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateExecutor(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateFee(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateGasUsed(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateIsSuccessful(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateMaxFeePerGas(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateMaxPriorityFeePerGas(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateOrigin(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateTransfers(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateTxType(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) contextValidateBlockNumber(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "blockNumber", "body", int64(m.BlockNumber)); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) contextValidateConfirmations(ctx context.Context, formats strfmt.Registry) error { + + if m.Confirmations != nil { + + if swag.IsZero(m.Confirmations) { // not required + return nil + } + + if err := m.Confirmations.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("confirmations") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("confirmations") + } + return err + } + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) contextValidateDataDecoded(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "dataDecoded", "body", string(m.DataDecoded)); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) contextValidateEthGasPrice(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "ethGasPrice", "body", string(m.EthGasPrice)); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) contextValidateExecutor(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "executor", "body", string(m.Executor)); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) contextValidateFee(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "fee", "body", int64(m.Fee)); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) contextValidateGasUsed(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "gasUsed", "body", int64(m.GasUsed)); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) contextValidateIsSuccessful(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "isSuccessful", "body", m.IsSuccessful); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) contextValidateMaxFeePerGas(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "maxFeePerGas", "body", string(m.MaxFeePerGas)); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) contextValidateMaxPriorityFeePerGas(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "maxPriorityFeePerGas", "body", string(m.MaxPriorityFeePerGas)); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) contextValidateOrigin(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "origin", "body", string(m.Origin)); err != nil { + return err + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) contextValidateTransfers(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Transfers); i++ { + + if m.Transfers[i] != nil { + + if swag.IsZero(m.Transfers[i]) { // not required + return nil + } + + if err := m.Transfers[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("transfers" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("transfers" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *SafeMultisigTransactionWithTransfersResponse) contextValidateTxType(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "txType", "body", string(m.TxType)); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SafeMultisigTransactionWithTransfersResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeMultisigTransactionWithTransfersResponse) UnmarshalBinary(b []byte) error { + var res SafeMultisigTransactionWithTransfersResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_operation.go b/utils/safe_api/safe_operation.go new file mode 100644 index 0000000..bd668fb --- /dev/null +++ b/utils/safe_api/safe_operation.go @@ -0,0 +1,332 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeOperation safe operation +// +// swagger:model SafeOperation +type SafeOperation struct { + + // Call data + // Required: true + CallData *string `json:"callData"` + + // Call gas limit + // Required: true + // Minimum: 0 + CallGasLimit *int64 `json:"callGasLimit"` + + // Entry point + // Required: true + EntryPoint *string `json:"entryPoint"` + + // Init code + // Required: true + InitCode *string `json:"initCode"` + + // Max fee per gas + // Required: true + // Minimum: 0 + MaxFeePerGas *int64 `json:"maxFeePerGas"` + + // Max priority fee per gas + // Required: true + // Minimum: 0 + MaxPriorityFeePerGas *int64 `json:"maxPriorityFeePerGas"` + + // Module address + // Required: true + ModuleAddress *string `json:"moduleAddress"` + + // Nonce + // Required: true + // Minimum: 0 + Nonce *int64 `json:"nonce"` + + // Paymaster and data + // Required: true + PaymasterAndData *string `json:"paymasterAndData"` + + // Pre verification gas + // Required: true + // Minimum: 0 + PreVerificationGas *int64 `json:"preVerificationGas"` + + // Signature + // Required: true + Signature *string `json:"signature"` + + // Valid after + // Required: true + // Format: date-time + ValidAfter *strfmt.DateTime `json:"validAfter"` + + // Valid until + // Required: true + // Format: date-time + ValidUntil *strfmt.DateTime `json:"validUntil"` + + // Verification gas limit + // Required: true + // Minimum: 0 + VerificationGasLimit *int64 `json:"verificationGasLimit"` +} + +// Validate validates this safe operation +func (m *SafeOperation) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCallData(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCallGasLimit(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEntryPoint(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInitCode(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMaxFeePerGas(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMaxPriorityFeePerGas(formats); err != nil { + res = append(res, err) + } + + if err := m.validateModuleAddress(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNonce(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePaymasterAndData(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePreVerificationGas(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSignature(formats); err != nil { + res = append(res, err) + } + + if err := m.validateValidAfter(formats); err != nil { + res = append(res, err) + } + + if err := m.validateValidUntil(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVerificationGasLimit(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeOperation) validateCallData(formats strfmt.Registry) error { + + if err := validate.Required("callData", "body", m.CallData); err != nil { + return err + } + + return nil +} + +func (m *SafeOperation) validateCallGasLimit(formats strfmt.Registry) error { + + if err := validate.Required("callGasLimit", "body", m.CallGasLimit); err != nil { + return err + } + + if err := validate.MinimumInt("callGasLimit", "body", *m.CallGasLimit, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeOperation) validateEntryPoint(formats strfmt.Registry) error { + + if err := validate.Required("entryPoint", "body", m.EntryPoint); err != nil { + return err + } + + return nil +} + +func (m *SafeOperation) validateInitCode(formats strfmt.Registry) error { + + if err := validate.Required("initCode", "body", m.InitCode); err != nil { + return err + } + + return nil +} + +func (m *SafeOperation) validateMaxFeePerGas(formats strfmt.Registry) error { + + if err := validate.Required("maxFeePerGas", "body", m.MaxFeePerGas); err != nil { + return err + } + + if err := validate.MinimumInt("maxFeePerGas", "body", *m.MaxFeePerGas, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeOperation) validateMaxPriorityFeePerGas(formats strfmt.Registry) error { + + if err := validate.Required("maxPriorityFeePerGas", "body", m.MaxPriorityFeePerGas); err != nil { + return err + } + + if err := validate.MinimumInt("maxPriorityFeePerGas", "body", *m.MaxPriorityFeePerGas, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeOperation) validateModuleAddress(formats strfmt.Registry) error { + + if err := validate.Required("moduleAddress", "body", m.ModuleAddress); err != nil { + return err + } + + return nil +} + +func (m *SafeOperation) validateNonce(formats strfmt.Registry) error { + + if err := validate.Required("nonce", "body", m.Nonce); err != nil { + return err + } + + if err := validate.MinimumInt("nonce", "body", *m.Nonce, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeOperation) validatePaymasterAndData(formats strfmt.Registry) error { + + if err := validate.Required("paymasterAndData", "body", m.PaymasterAndData); err != nil { + return err + } + + return nil +} + +func (m *SafeOperation) validatePreVerificationGas(formats strfmt.Registry) error { + + if err := validate.Required("preVerificationGas", "body", m.PreVerificationGas); err != nil { + return err + } + + if err := validate.MinimumInt("preVerificationGas", "body", *m.PreVerificationGas, 0, false); err != nil { + return err + } + + return nil +} + +func (m *SafeOperation) validateSignature(formats strfmt.Registry) error { + + if err := validate.Required("signature", "body", m.Signature); err != nil { + return err + } + + return nil +} + +func (m *SafeOperation) validateValidAfter(formats strfmt.Registry) error { + + if err := validate.Required("validAfter", "body", m.ValidAfter); err != nil { + return err + } + + if err := validate.FormatOf("validAfter", "body", "date-time", m.ValidAfter.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeOperation) validateValidUntil(formats strfmt.Registry) error { + + if err := validate.Required("validUntil", "body", m.ValidUntil); err != nil { + return err + } + + if err := validate.FormatOf("validUntil", "body", "date-time", m.ValidUntil.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeOperation) validateVerificationGasLimit(formats strfmt.Registry) error { + + if err := validate.Required("verificationGasLimit", "body", m.VerificationGasLimit); err != nil { + return err + } + + if err := validate.MinimumInt("verificationGasLimit", "body", *m.VerificationGasLimit, 0, false); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this safe operation based on context it is used +func (m *SafeOperation) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SafeOperation) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeOperation) UnmarshalBinary(b []byte) error { + var res SafeOperation + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_operation_response.go b/utils/safe_api/safe_operation_response.go new file mode 100644 index 0000000..66a995c --- /dev/null +++ b/utils/safe_api/safe_operation_response.go @@ -0,0 +1,215 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeOperationResponse safe operation response +// +// swagger:model SafeOperationResponse +type SafeOperationResponse struct { + + // Confirmations + // Read Only: true + Confirmations string `json:"confirmations,omitempty"` + + // Created + // Required: true + // Format: date-time + Created *strfmt.DateTime `json:"created"` + + // Modified + // Required: true + // Format: date-time + Modified *strfmt.DateTime `json:"modified"` + + // Module address + // Required: true + ModuleAddress *string `json:"moduleAddress"` + + // Prepared signature + // Read Only: true + PreparedSignature string `json:"preparedSignature,omitempty"` + + // Safe operation hash + // Required: true + SafeOperationHash *string `json:"safeOperationHash"` + + // Valid after + // Required: true + // Format: date-time + ValidAfter *strfmt.DateTime `json:"validAfter"` + + // Valid until + // Required: true + // Format: date-time + ValidUntil *strfmt.DateTime `json:"validUntil"` +} + +// Validate validates this safe operation response +func (m *SafeOperationResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCreated(formats); err != nil { + res = append(res, err) + } + + if err := m.validateModified(formats); err != nil { + res = append(res, err) + } + + if err := m.validateModuleAddress(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafeOperationHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateValidAfter(formats); err != nil { + res = append(res, err) + } + + if err := m.validateValidUntil(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeOperationResponse) validateCreated(formats strfmt.Registry) error { + + if err := validate.Required("created", "body", m.Created); err != nil { + return err + } + + if err := validate.FormatOf("created", "body", "date-time", m.Created.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeOperationResponse) validateModified(formats strfmt.Registry) error { + + if err := validate.Required("modified", "body", m.Modified); err != nil { + return err + } + + if err := validate.FormatOf("modified", "body", "date-time", m.Modified.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeOperationResponse) validateModuleAddress(formats strfmt.Registry) error { + + if err := validate.Required("moduleAddress", "body", m.ModuleAddress); err != nil { + return err + } + + return nil +} + +func (m *SafeOperationResponse) validateSafeOperationHash(formats strfmt.Registry) error { + + if err := validate.Required("safeOperationHash", "body", m.SafeOperationHash); err != nil { + return err + } + + return nil +} + +func (m *SafeOperationResponse) validateValidAfter(formats strfmt.Registry) error { + + if err := validate.Required("validAfter", "body", m.ValidAfter); err != nil { + return err + } + + if err := validate.FormatOf("validAfter", "body", "date-time", m.ValidAfter.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeOperationResponse) validateValidUntil(formats strfmt.Registry) error { + + if err := validate.Required("validUntil", "body", m.ValidUntil); err != nil { + return err + } + + if err := validate.FormatOf("validUntil", "body", "date-time", m.ValidUntil.String(), formats); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this safe operation response based on the context it is used +func (m *SafeOperationResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateConfirmations(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidatePreparedSignature(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeOperationResponse) contextValidateConfirmations(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "confirmations", "body", string(m.Confirmations)); err != nil { + return err + } + + return nil +} + +func (m *SafeOperationResponse) contextValidatePreparedSignature(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "preparedSignature", "body", string(m.PreparedSignature)); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SafeOperationResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeOperationResponse) UnmarshalBinary(b []byte) error { + var res SafeOperationResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/safe_operation_with_user_operation_response.go b/utils/safe_api/safe_operation_with_user_operation_response.go new file mode 100644 index 0000000..51a6647 --- /dev/null +++ b/utils/safe_api/safe_operation_with_user_operation_response.go @@ -0,0 +1,266 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SafeOperationWithUserOperationResponse safe operation with user operation response +// +// swagger:model SafeOperationWithUserOperationResponse +type SafeOperationWithUserOperationResponse struct { + + // Confirmations + // Read Only: true + Confirmations string `json:"confirmations,omitempty"` + + // Created + // Required: true + // Format: date-time + Created *strfmt.DateTime `json:"created"` + + // Modified + // Required: true + // Format: date-time + Modified *strfmt.DateTime `json:"modified"` + + // Module address + // Required: true + ModuleAddress *string `json:"moduleAddress"` + + // Prepared signature + // Read Only: true + PreparedSignature string `json:"preparedSignature,omitempty"` + + // Safe operation hash + // Required: true + SafeOperationHash *string `json:"safeOperationHash"` + + // user operation + UserOperation *UserOperationResponse `json:"userOperation,omitempty"` + + // Valid after + // Required: true + // Format: date-time + ValidAfter *strfmt.DateTime `json:"validAfter"` + + // Valid until + // Required: true + // Format: date-time + ValidUntil *strfmt.DateTime `json:"validUntil"` +} + +// Validate validates this safe operation with user operation response +func (m *SafeOperationWithUserOperationResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCreated(formats); err != nil { + res = append(res, err) + } + + if err := m.validateModified(formats); err != nil { + res = append(res, err) + } + + if err := m.validateModuleAddress(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafeOperationHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUserOperation(formats); err != nil { + res = append(res, err) + } + + if err := m.validateValidAfter(formats); err != nil { + res = append(res, err) + } + + if err := m.validateValidUntil(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeOperationWithUserOperationResponse) validateCreated(formats strfmt.Registry) error { + + if err := validate.Required("created", "body", m.Created); err != nil { + return err + } + + if err := validate.FormatOf("created", "body", "date-time", m.Created.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeOperationWithUserOperationResponse) validateModified(formats strfmt.Registry) error { + + if err := validate.Required("modified", "body", m.Modified); err != nil { + return err + } + + if err := validate.FormatOf("modified", "body", "date-time", m.Modified.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeOperationWithUserOperationResponse) validateModuleAddress(formats strfmt.Registry) error { + + if err := validate.Required("moduleAddress", "body", m.ModuleAddress); err != nil { + return err + } + + return nil +} + +func (m *SafeOperationWithUserOperationResponse) validateSafeOperationHash(formats strfmt.Registry) error { + + if err := validate.Required("safeOperationHash", "body", m.SafeOperationHash); err != nil { + return err + } + + return nil +} + +func (m *SafeOperationWithUserOperationResponse) validateUserOperation(formats strfmt.Registry) error { + if swag.IsZero(m.UserOperation) { // not required + return nil + } + + if m.UserOperation != nil { + if err := m.UserOperation.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("userOperation") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("userOperation") + } + return err + } + } + + return nil +} + +func (m *SafeOperationWithUserOperationResponse) validateValidAfter(formats strfmt.Registry) error { + + if err := validate.Required("validAfter", "body", m.ValidAfter); err != nil { + return err + } + + if err := validate.FormatOf("validAfter", "body", "date-time", m.ValidAfter.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *SafeOperationWithUserOperationResponse) validateValidUntil(formats strfmt.Registry) error { + + if err := validate.Required("validUntil", "body", m.ValidUntil); err != nil { + return err + } + + if err := validate.FormatOf("validUntil", "body", "date-time", m.ValidUntil.String(), formats); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this safe operation with user operation response based on the context it is used +func (m *SafeOperationWithUserOperationResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateConfirmations(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidatePreparedSignature(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateUserOperation(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SafeOperationWithUserOperationResponse) contextValidateConfirmations(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "confirmations", "body", string(m.Confirmations)); err != nil { + return err + } + + return nil +} + +func (m *SafeOperationWithUserOperationResponse) contextValidatePreparedSignature(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "preparedSignature", "body", string(m.PreparedSignature)); err != nil { + return err + } + + return nil +} + +func (m *SafeOperationWithUserOperationResponse) contextValidateUserOperation(ctx context.Context, formats strfmt.Registry) error { + + if m.UserOperation != nil { + + if swag.IsZero(m.UserOperation) { // not required + return nil + } + + if err := m.UserOperation.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("userOperation") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("userOperation") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SafeOperationWithUserOperationResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SafeOperationWithUserOperationResponse) UnmarshalBinary(b []byte) error { + var res SafeOperationWithUserOperationResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/token_info_response.go b/utils/safe_api/token_info_response.go new file mode 100644 index 0000000..e25b327 --- /dev/null +++ b/utils/safe_api/token_info_response.go @@ -0,0 +1,188 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// TokenInfoResponse token info response +// +// swagger:model TokenInfoResponse +type TokenInfoResponse struct { + + // Address + // Required: true + Address *string `json:"address"` + + // Decimals + // Required: true + Decimals *int64 `json:"decimals"` + + // Logo uri + // Read Only: true + LogoURI string `json:"logoUri,omitempty"` + + // Name + // Required: true + // Min Length: 1 + Name *string `json:"name"` + + // Symbol + // Required: true + // Min Length: 1 + Symbol *string `json:"symbol"` + + // Trusted + // Required: true + Trusted *bool `json:"trusted"` + + // Type + // Read Only: true + Type string `json:"type,omitempty"` +} + +// Validate validates this token info response +func (m *TokenInfoResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAddress(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDecimals(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSymbol(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTrusted(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *TokenInfoResponse) validateAddress(formats strfmt.Registry) error { + + if err := validate.Required("address", "body", m.Address); err != nil { + return err + } + + return nil +} + +func (m *TokenInfoResponse) validateDecimals(formats strfmt.Registry) error { + + if err := validate.Required("decimals", "body", m.Decimals); err != nil { + return err + } + + return nil +} + +func (m *TokenInfoResponse) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + if err := validate.MinLength("name", "body", *m.Name, 1); err != nil { + return err + } + + return nil +} + +func (m *TokenInfoResponse) validateSymbol(formats strfmt.Registry) error { + + if err := validate.Required("symbol", "body", m.Symbol); err != nil { + return err + } + + if err := validate.MinLength("symbol", "body", *m.Symbol, 1); err != nil { + return err + } + + return nil +} + +func (m *TokenInfoResponse) validateTrusted(formats strfmt.Registry) error { + + if err := validate.Required("trusted", "body", m.Trusted); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this token info response based on the context it is used +func (m *TokenInfoResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateLogoURI(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateType(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *TokenInfoResponse) contextValidateLogoURI(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "logoUri", "body", string(m.LogoURI)); err != nil { + return err + } + + return nil +} + +func (m *TokenInfoResponse) contextValidateType(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "type", "body", string(m.Type)); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *TokenInfoResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *TokenInfoResponse) UnmarshalBinary(b []byte) error { + var res TokenInfoResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/transfer_with_token_info_response.go b/utils/safe_api/transfer_with_token_info_response.go new file mode 100644 index 0000000..64e0be4 --- /dev/null +++ b/utils/safe_api/transfer_with_token_info_response.go @@ -0,0 +1,283 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// TransferWithTokenInfoResponse transfer with token info response +// +// swagger:model TransferWithTokenInfoResponse +type TransferWithTokenInfoResponse struct { + + // Block number + // Required: true + BlockNumber *int64 `json:"blockNumber"` + + // Execution date + // Required: true + // Format: date-time + ExecutionDate *strfmt.DateTime `json:"executionDate"` + + // From + // Required: true + From *string `json:"from"` + + // To + // Required: true + To *string `json:"to"` + + // Token address + TokenAddress *string `json:"tokenAddress,omitempty"` + + // Token id + // Required: true + // Min Length: 1 + TokenID *string `json:"tokenId"` + + // token info + // Required: true + TokenInfo *TokenInfoResponse `json:"tokenInfo"` + + // Transaction hash + // Required: true + TransactionHash *string `json:"transactionHash"` + + // Transfer id + // + // Internally calculated parameter to uniquely identify a transfer + // Token transfers are calculated as `transferId = e+tx_hash+log_index` + // Ether transfers are calculated as `transferId = i+tx_hash+trace_address` + // Read Only: true + TransferID string `json:"transferId,omitempty"` + + // Type + // Read Only: true + Type string `json:"type,omitempty"` + + // Value + // Required: true + // Min Length: 1 + Value *string `json:"value"` +} + +// Validate validates this transfer with token info response +func (m *TransferWithTokenInfoResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateBlockNumber(formats); err != nil { + res = append(res, err) + } + + if err := m.validateExecutionDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateFrom(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTo(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTokenID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTokenInfo(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTransactionHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateValue(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *TransferWithTokenInfoResponse) validateBlockNumber(formats strfmt.Registry) error { + + if err := validate.Required("blockNumber", "body", m.BlockNumber); err != nil { + return err + } + + return nil +} + +func (m *TransferWithTokenInfoResponse) validateExecutionDate(formats strfmt.Registry) error { + + if err := validate.Required("executionDate", "body", m.ExecutionDate); err != nil { + return err + } + + if err := validate.FormatOf("executionDate", "body", "date-time", m.ExecutionDate.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *TransferWithTokenInfoResponse) validateFrom(formats strfmt.Registry) error { + + if err := validate.Required("from", "body", m.From); err != nil { + return err + } + + return nil +} + +func (m *TransferWithTokenInfoResponse) validateTo(formats strfmt.Registry) error { + + if err := validate.Required("to", "body", m.To); err != nil { + return err + } + + return nil +} + +func (m *TransferWithTokenInfoResponse) validateTokenID(formats strfmt.Registry) error { + + if err := validate.Required("tokenId", "body", m.TokenID); err != nil { + return err + } + + if err := validate.MinLength("tokenId", "body", *m.TokenID, 1); err != nil { + return err + } + + return nil +} + +func (m *TransferWithTokenInfoResponse) validateTokenInfo(formats strfmt.Registry) error { + + if err := validate.Required("tokenInfo", "body", m.TokenInfo); err != nil { + return err + } + + if m.TokenInfo != nil { + if err := m.TokenInfo.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("tokenInfo") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("tokenInfo") + } + return err + } + } + + return nil +} + +func (m *TransferWithTokenInfoResponse) validateTransactionHash(formats strfmt.Registry) error { + + if err := validate.Required("transactionHash", "body", m.TransactionHash); err != nil { + return err + } + + return nil +} + +func (m *TransferWithTokenInfoResponse) validateValue(formats strfmt.Registry) error { + + if err := validate.Required("value", "body", m.Value); err != nil { + return err + } + + if err := validate.MinLength("value", "body", *m.Value, 1); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this transfer with token info response based on the context it is used +func (m *TransferWithTokenInfoResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateTokenInfo(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateTransferID(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateType(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *TransferWithTokenInfoResponse) contextValidateTokenInfo(ctx context.Context, formats strfmt.Registry) error { + + if m.TokenInfo != nil { + + if err := m.TokenInfo.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("tokenInfo") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("tokenInfo") + } + return err + } + } + + return nil +} + +func (m *TransferWithTokenInfoResponse) contextValidateTransferID(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "transferId", "body", string(m.TransferID)); err != nil { + return err + } + + return nil +} + +func (m *TransferWithTokenInfoResponse) contextValidateType(ctx context.Context, formats strfmt.Registry) error { + + if err := validate.ReadOnly(ctx, "type", "body", string(m.Type)); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *TransferWithTokenInfoResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *TransferWithTokenInfoResponse) UnmarshalBinary(b []byte) error { + var res TransferWithTokenInfoResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/user_operation_response.go b/utils/safe_api/user_operation_response.go new file mode 100644 index 0000000..1f82b6a --- /dev/null +++ b/utils/safe_api/user_operation_response.go @@ -0,0 +1,339 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// UserOperationResponse user operation response +// +// swagger:model UserOperationResponse +type UserOperationResponse struct { + + // Call data + // Required: true + CallData *string `json:"callData"` + + // Call gas limit + // Required: true + // Minimum: 0 + CallGasLimit *int64 `json:"callGasLimit"` + + // Entry point + // Required: true + EntryPoint *string `json:"entryPoint"` + + // Ethereum tx hash + // Required: true + EthereumTxHash *string `json:"ethereumTxHash"` + + // Init code + // Required: true + InitCode *string `json:"initCode"` + + // Max fee per gas + // Required: true + // Minimum: 0 + MaxFeePerGas *int64 `json:"maxFeePerGas"` + + // Max priority fee per gas + // Required: true + // Minimum: 0 + MaxPriorityFeePerGas *int64 `json:"maxPriorityFeePerGas"` + + // Nonce + // Required: true + // Minimum: 0 + Nonce *int64 `json:"nonce"` + + // Paymaster + // Required: true + Paymaster *string `json:"paymaster"` + + // Paymaster data + // Required: true + PaymasterData *string `json:"paymasterData"` + + // Pre verification gas + // Required: true + // Minimum: 0 + PreVerificationGas *int64 `json:"preVerificationGas"` + + // Sender + // Required: true + Sender *string `json:"sender"` + + // Signature + // Required: true + Signature *string `json:"signature"` + + // User operation hash + // Required: true + UserOperationHash *string `json:"userOperationHash"` + + // Verification gas limit + // Required: true + // Minimum: 0 + VerificationGasLimit *int64 `json:"verificationGasLimit"` +} + +// Validate validates this user operation response +func (m *UserOperationResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCallData(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCallGasLimit(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEntryPoint(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEthereumTxHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInitCode(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMaxFeePerGas(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMaxPriorityFeePerGas(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNonce(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePaymaster(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePaymasterData(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePreVerificationGas(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSender(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSignature(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUserOperationHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVerificationGasLimit(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UserOperationResponse) validateCallData(formats strfmt.Registry) error { + + if err := validate.Required("callData", "body", m.CallData); err != nil { + return err + } + + return nil +} + +func (m *UserOperationResponse) validateCallGasLimit(formats strfmt.Registry) error { + + if err := validate.Required("callGasLimit", "body", m.CallGasLimit); err != nil { + return err + } + + if err := validate.MinimumInt("callGasLimit", "body", *m.CallGasLimit, 0, false); err != nil { + return err + } + + return nil +} + +func (m *UserOperationResponse) validateEntryPoint(formats strfmt.Registry) error { + + if err := validate.Required("entryPoint", "body", m.EntryPoint); err != nil { + return err + } + + return nil +} + +func (m *UserOperationResponse) validateEthereumTxHash(formats strfmt.Registry) error { + + if err := validate.Required("ethereumTxHash", "body", m.EthereumTxHash); err != nil { + return err + } + + return nil +} + +func (m *UserOperationResponse) validateInitCode(formats strfmt.Registry) error { + + if err := validate.Required("initCode", "body", m.InitCode); err != nil { + return err + } + + return nil +} + +func (m *UserOperationResponse) validateMaxFeePerGas(formats strfmt.Registry) error { + + if err := validate.Required("maxFeePerGas", "body", m.MaxFeePerGas); err != nil { + return err + } + + if err := validate.MinimumInt("maxFeePerGas", "body", *m.MaxFeePerGas, 0, false); err != nil { + return err + } + + return nil +} + +func (m *UserOperationResponse) validateMaxPriorityFeePerGas(formats strfmt.Registry) error { + + if err := validate.Required("maxPriorityFeePerGas", "body", m.MaxPriorityFeePerGas); err != nil { + return err + } + + if err := validate.MinimumInt("maxPriorityFeePerGas", "body", *m.MaxPriorityFeePerGas, 0, false); err != nil { + return err + } + + return nil +} + +func (m *UserOperationResponse) validateNonce(formats strfmt.Registry) error { + + if err := validate.Required("nonce", "body", m.Nonce); err != nil { + return err + } + + if err := validate.MinimumInt("nonce", "body", *m.Nonce, 0, false); err != nil { + return err + } + + return nil +} + +func (m *UserOperationResponse) validatePaymaster(formats strfmt.Registry) error { + + if err := validate.Required("paymaster", "body", m.Paymaster); err != nil { + return err + } + + return nil +} + +func (m *UserOperationResponse) validatePaymasterData(formats strfmt.Registry) error { + + if err := validate.Required("paymasterData", "body", m.PaymasterData); err != nil { + return err + } + + return nil +} + +func (m *UserOperationResponse) validatePreVerificationGas(formats strfmt.Registry) error { + + if err := validate.Required("preVerificationGas", "body", m.PreVerificationGas); err != nil { + return err + } + + if err := validate.MinimumInt("preVerificationGas", "body", *m.PreVerificationGas, 0, false); err != nil { + return err + } + + return nil +} + +func (m *UserOperationResponse) validateSender(formats strfmt.Registry) error { + + if err := validate.Required("sender", "body", m.Sender); err != nil { + return err + } + + return nil +} + +func (m *UserOperationResponse) validateSignature(formats strfmt.Registry) error { + + if err := validate.Required("signature", "body", m.Signature); err != nil { + return err + } + + return nil +} + +func (m *UserOperationResponse) validateUserOperationHash(formats strfmt.Registry) error { + + if err := validate.Required("userOperationHash", "body", m.UserOperationHash); err != nil { + return err + } + + return nil +} + +func (m *UserOperationResponse) validateVerificationGasLimit(formats strfmt.Registry) error { + + if err := validate.Required("verificationGasLimit", "body", m.VerificationGasLimit); err != nil { + return err + } + + if err := validate.MinimumInt("verificationGasLimit", "body", *m.VerificationGasLimit, 0, false); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this user operation response based on context it is used +func (m *UserOperationResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *UserOperationResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UserOperationResponse) UnmarshalBinary(b []byte) error { + var res UserOperationResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/safe_api/user_operation_with_safe_operation_response.go b/utils/safe_api/user_operation_with_safe_operation_response.go new file mode 100644 index 0000000..23572bb --- /dev/null +++ b/utils/safe_api/user_operation_with_safe_operation_response.go @@ -0,0 +1,395 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package safe_api + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// UserOperationWithSafeOperationResponse user operation with safe operation response +// +// swagger:model UserOperationWithSafeOperationResponse +type UserOperationWithSafeOperationResponse struct { + + // Call data + // Required: true + CallData *string `json:"callData"` + + // Call gas limit + // Required: true + // Minimum: 0 + CallGasLimit *int64 `json:"callGasLimit"` + + // Entry point + // Required: true + EntryPoint *string `json:"entryPoint"` + + // Ethereum tx hash + // Required: true + EthereumTxHash *string `json:"ethereumTxHash"` + + // Init code + // Required: true + InitCode *string `json:"initCode"` + + // Max fee per gas + // Required: true + // Minimum: 0 + MaxFeePerGas *int64 `json:"maxFeePerGas"` + + // Max priority fee per gas + // Required: true + // Minimum: 0 + MaxPriorityFeePerGas *int64 `json:"maxPriorityFeePerGas"` + + // Nonce + // Required: true + // Minimum: 0 + Nonce *int64 `json:"nonce"` + + // Paymaster + // Required: true + Paymaster *string `json:"paymaster"` + + // Paymaster data + // Required: true + PaymasterData *string `json:"paymasterData"` + + // Pre verification gas + // Required: true + // Minimum: 0 + PreVerificationGas *int64 `json:"preVerificationGas"` + + // safe operation + SafeOperation *SafeOperationResponse `json:"safeOperation,omitempty"` + + // Sender + // Required: true + Sender *string `json:"sender"` + + // Signature + // Required: true + Signature *string `json:"signature"` + + // User operation hash + // Required: true + UserOperationHash *string `json:"userOperationHash"` + + // Verification gas limit + // Required: true + // Minimum: 0 + VerificationGasLimit *int64 `json:"verificationGasLimit"` +} + +// Validate validates this user operation with safe operation response +func (m *UserOperationWithSafeOperationResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCallData(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCallGasLimit(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEntryPoint(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEthereumTxHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInitCode(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMaxFeePerGas(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMaxPriorityFeePerGas(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNonce(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePaymaster(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePaymasterData(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePreVerificationGas(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafeOperation(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSender(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSignature(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUserOperationHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVerificationGasLimit(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UserOperationWithSafeOperationResponse) validateCallData(formats strfmt.Registry) error { + + if err := validate.Required("callData", "body", m.CallData); err != nil { + return err + } + + return nil +} + +func (m *UserOperationWithSafeOperationResponse) validateCallGasLimit(formats strfmt.Registry) error { + + if err := validate.Required("callGasLimit", "body", m.CallGasLimit); err != nil { + return err + } + + if err := validate.MinimumInt("callGasLimit", "body", *m.CallGasLimit, 0, false); err != nil { + return err + } + + return nil +} + +func (m *UserOperationWithSafeOperationResponse) validateEntryPoint(formats strfmt.Registry) error { + + if err := validate.Required("entryPoint", "body", m.EntryPoint); err != nil { + return err + } + + return nil +} + +func (m *UserOperationWithSafeOperationResponse) validateEthereumTxHash(formats strfmt.Registry) error { + + if err := validate.Required("ethereumTxHash", "body", m.EthereumTxHash); err != nil { + return err + } + + return nil +} + +func (m *UserOperationWithSafeOperationResponse) validateInitCode(formats strfmt.Registry) error { + + if err := validate.Required("initCode", "body", m.InitCode); err != nil { + return err + } + + return nil +} + +func (m *UserOperationWithSafeOperationResponse) validateMaxFeePerGas(formats strfmt.Registry) error { + + if err := validate.Required("maxFeePerGas", "body", m.MaxFeePerGas); err != nil { + return err + } + + if err := validate.MinimumInt("maxFeePerGas", "body", *m.MaxFeePerGas, 0, false); err != nil { + return err + } + + return nil +} + +func (m *UserOperationWithSafeOperationResponse) validateMaxPriorityFeePerGas(formats strfmt.Registry) error { + + if err := validate.Required("maxPriorityFeePerGas", "body", m.MaxPriorityFeePerGas); err != nil { + return err + } + + if err := validate.MinimumInt("maxPriorityFeePerGas", "body", *m.MaxPriorityFeePerGas, 0, false); err != nil { + return err + } + + return nil +} + +func (m *UserOperationWithSafeOperationResponse) validateNonce(formats strfmt.Registry) error { + + if err := validate.Required("nonce", "body", m.Nonce); err != nil { + return err + } + + if err := validate.MinimumInt("nonce", "body", *m.Nonce, 0, false); err != nil { + return err + } + + return nil +} + +func (m *UserOperationWithSafeOperationResponse) validatePaymaster(formats strfmt.Registry) error { + + if err := validate.Required("paymaster", "body", m.Paymaster); err != nil { + return err + } + + return nil +} + +func (m *UserOperationWithSafeOperationResponse) validatePaymasterData(formats strfmt.Registry) error { + + if err := validate.Required("paymasterData", "body", m.PaymasterData); err != nil { + return err + } + + return nil +} + +func (m *UserOperationWithSafeOperationResponse) validatePreVerificationGas(formats strfmt.Registry) error { + + if err := validate.Required("preVerificationGas", "body", m.PreVerificationGas); err != nil { + return err + } + + if err := validate.MinimumInt("preVerificationGas", "body", *m.PreVerificationGas, 0, false); err != nil { + return err + } + + return nil +} + +func (m *UserOperationWithSafeOperationResponse) validateSafeOperation(formats strfmt.Registry) error { + if swag.IsZero(m.SafeOperation) { // not required + return nil + } + + if m.SafeOperation != nil { + if err := m.SafeOperation.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("safeOperation") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("safeOperation") + } + return err + } + } + + return nil +} + +func (m *UserOperationWithSafeOperationResponse) validateSender(formats strfmt.Registry) error { + + if err := validate.Required("sender", "body", m.Sender); err != nil { + return err + } + + return nil +} + +func (m *UserOperationWithSafeOperationResponse) validateSignature(formats strfmt.Registry) error { + + if err := validate.Required("signature", "body", m.Signature); err != nil { + return err + } + + return nil +} + +func (m *UserOperationWithSafeOperationResponse) validateUserOperationHash(formats strfmt.Registry) error { + + if err := validate.Required("userOperationHash", "body", m.UserOperationHash); err != nil { + return err + } + + return nil +} + +func (m *UserOperationWithSafeOperationResponse) validateVerificationGasLimit(formats strfmt.Registry) error { + + if err := validate.Required("verificationGasLimit", "body", m.VerificationGasLimit); err != nil { + return err + } + + if err := validate.MinimumInt("verificationGasLimit", "body", *m.VerificationGasLimit, 0, false); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this user operation with safe operation response based on the context it is used +func (m *UserOperationWithSafeOperationResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSafeOperation(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UserOperationWithSafeOperationResponse) contextValidateSafeOperation(ctx context.Context, formats strfmt.Registry) error { + + if m.SafeOperation != nil { + + if swag.IsZero(m.SafeOperation) { // not required + return nil + } + + if err := m.SafeOperation.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("safeOperation") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("safeOperation") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *UserOperationWithSafeOperationResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UserOperationWithSafeOperationResponse) UnmarshalBinary(b []byte) error { + var res UserOperationWithSafeOperationResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/utils/token_price/binance.go b/utils/token_price/binance.go new file mode 100644 index 0000000..62096b8 --- /dev/null +++ b/utils/token_price/binance.go @@ -0,0 +1,56 @@ +package token_price + +import ( + "context" + "fmt" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "omni-balance/utils" + "omni-balance/utils/configs" + "strings" +) + +type Binance struct { +} + +type BinancePriceResp struct { + Symbol string `json:"symbol"` + Price decimal.Decimal `json:"price"` +} + +func (b Binance) GetTokenPriceInUSDT(ctx context.Context, tokens ...configs.SourceToken) ([]TokenPriceData, error) { + if len(tokens) == 0 { + return nil, errors.Errorf("tokens is empty") + } + var ( + symbol2Name = make(map[string]string) + tokenNames = SourceTokens2Map(tokens) + ) + + for _, v := range tokenNames { + piarsName := strings.ToUpper(fmt.Sprintf("%sUSDT", v.Name)) + symbol2Name[piarsName] = v.Name + } + var resp []BinancePriceResp + if err := utils.Request(ctx, "GET", "https://api.binance.com/api/v3/ticker/price", nil, &resp); err != nil { + return nil, errors.Wrap(err, "decode response") + } + var result []TokenPriceData + for _, v := range resp { + if _, ok := symbol2Name[v.Symbol]; !ok { + continue + } + if v.Price.LessThan(decimal.Zero) { + continue + } + result = append(result, TokenPriceData{ + TokeName: symbol2Name[v.Symbol], + Price: v.Price, + }) + } + return AppendUsdtPrice(result), nil +} + +func (b Binance) Name() string { + return "binance" +} diff --git a/utils/token_price/bitget.go b/utils/token_price/bitget.go new file mode 100644 index 0000000..3aecdc1 --- /dev/null +++ b/utils/token_price/bitget.go @@ -0,0 +1,66 @@ +package token_price + +import ( + "context" + "github.com/shopspring/decimal" + "omni-balance/utils" + "omni-balance/utils/configs" + "strings" +) + +type Bitget struct { +} + +type bitgetMarket struct { + Code string `json:"code"` + Msg string `json:"msg"` + RequestTime int64 `json:"requestTime"` + Data []struct { + Open string `json:"open"` + Symbol string `json:"symbol"` + High24H string `json:"high24h"` + Low24H string `json:"low24h"` + LastPr decimal.Decimal `json:"lastPr"` + QuoteVolume string `json:"quoteVolume"` + BaseVolume string `json:"baseVolume"` + UsdtVolume string `json:"usdtVolume"` + Ts string `json:"ts"` + BidPr string `json:"bidPr"` + AskPr string `json:"askPr"` + BidSz string `json:"bidSz"` + AskSz string `json:"askSz"` + OpenUtc string `json:"openUtc"` + ChangeUtc24H string `json:"changeUtc24h"` + Change24H string `json:"change24h"` + } `json:"data"` +} + +func (b Bitget) GetTokenPriceInUSDT(ctx context.Context, tokens ...configs.SourceToken) ([]TokenPriceData, error) { + var ( + tokenNames = SourceTokens2Map(tokens) + ) + var bitgetMarket bitgetMarket + err := utils.Request(ctx, "GET", "https://api.bitget.com/api/v2/spot/market/tickers", nil, &bitgetMarket) + if err != nil { + return nil, err + } + var result []TokenPriceData + for _, token := range bitgetMarket.Data { + name := strings.TrimRight(token.Symbol, "USDT") + if _, ok := tokenNames[name]; !ok { + continue + } + if token.LastPr.LessThan(decimal.Zero) { + continue + } + result = append(result, TokenPriceData{ + TokeName: name, + Price: token.LastPr, + }) + } + return AppendUsdtPrice(result), nil +} + +func (b Bitget) Name() string { + return "bitget" +} diff --git a/utils/token_price/bybit.go b/utils/token_price/bybit.go new file mode 100644 index 0000000..71c5b97 --- /dev/null +++ b/utils/token_price/bybit.go @@ -0,0 +1,66 @@ +package token_price + +import ( + "context" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "omni-balance/utils" + "omni-balance/utils/configs" + "strings" +) + +type Bybit struct { +} + +type bybitMarketResp struct { + RetCode int `json:"retCode"` + RetMsg string `json:"retMsg"` + Result struct { + Category string `json:"category"` + List []struct { + Symbol string `json:"symbol"` + Bid1Price string `json:"bid1Price"` + Bid1Size string `json:"bid1Size"` + Ask1Price string `json:"ask1Price"` + Ask1Size string `json:"ask1Size"` + LastPrice decimal.Decimal `json:"lastPrice"` + PrevPrice24H string `json:"prevPrice24h"` + Price24HPcnt string `json:"price24hPcnt"` + HighPrice24H string `json:"highPrice24h"` + LowPrice24H string `json:"lowPrice24h"` + Turnover24H string `json:"turnover24h"` + Volume24H string `json:"volume24h"` + } `json:"list"` + } `json:"result"` +} + +func (b Bybit) GetTokenPriceInUSDT(ctx context.Context, tokens ...configs.SourceToken) ([]TokenPriceData, error) { + var ( + tokenNames = SourceTokens2Map(tokens) + ) + url := "https://api.bybit.com/v5/market/tickers?category=spot&baseCoin=USDT" + var data bybitMarketResp + if err := utils.Request(ctx, "GET", url, nil, &data); err != nil { + return nil, errors.Wrap(err, "decode response") + } + var result []TokenPriceData + for _, token := range data.Result.List { + name := strings.TrimRight(token.Symbol, "USDT") + if _, ok := tokenNames[name]; !ok { + continue + } + if token.LastPrice.LessThan(decimal.Zero) { + continue + } + result = append(result, TokenPriceData{ + TokeName: name, + Price: token.LastPrice, + TokenAddress: "", + }) + } + return AppendUsdtPrice(result), nil +} + +func (b Bybit) Name() string { + return "bybit" +} diff --git a/utils/token_price/gate.go b/utils/token_price/gate.go new file mode 100644 index 0000000..0dd2270 --- /dev/null +++ b/utils/token_price/gate.go @@ -0,0 +1,50 @@ +package token_price + +import ( + "context" + "github.com/shopspring/decimal" + "omni-balance/utils/configs" + "omni-balance/utils/provider/cex/gate" + "strings" +) + +type Gate struct { +} + +func NewGatePrice() TokenPrice { + return &Gate{} +} + +func (gp *Gate) GetTokenPriceInUSDT(ctx context.Context, tokens ...configs.SourceToken) ([]TokenPriceData, error) { + g, err := gate.New(configs.Config{}, true) + if err != nil { + return nil, err + } + var ( + pairs []string + tokenNames = SourceTokens2Map(tokens) + ) + for _, v := range tokenNames { + pairs = append(pairs, strings.ToUpper(v.Name+"_USDT")) + } + + tickerList, err := g.(*gate.Gate).Tickers(pairs...) + if err != nil { + return nil, err + } + var result []TokenPriceData + for _, v := range tickerList { + if v.Price.LessThan(decimal.Zero) { + continue + } + result = append(result, TokenPriceData{ + TokeName: v.TokenName, + Price: v.Price, + }) + } + return AppendUsdtPrice(result), nil +} + +func (g *Gate) Name() string { + return "gate.io" +} diff --git a/utils/token_price/init.go b/utils/token_price/init.go new file mode 100644 index 0000000..d1a04a1 --- /dev/null +++ b/utils/token_price/init.go @@ -0,0 +1,81 @@ +package token_price + +import ( + "context" + "github.com/shopspring/decimal" + "omni-balance/utils/configs" + "strings" +) + +var ( + tokenPriceProviders = map[string]TokenPrice{} +) + +func init() { + RegisterTokenPriceProvider(new(Binance).Name(), new(Binance)) + RegisterTokenPriceProvider(new(OKX).Name(), new(OKX)) + RegisterTokenPriceProvider(new(Gate).Name(), new(Gate)) + RegisterTokenPriceProvider(new(Bybit).Name(), new(Bybit)) + RegisterTokenPriceProvider(new(Mexc).Name(), new(Mexc)) + RegisterTokenPriceProvider(new(Bitget).Name(), new(Bitget)) +} + +type TokenPrice interface { + GetTokenPriceInUSDT(ctx context.Context, tokens ...configs.SourceToken) ([]TokenPriceData, error) + Name() string +} + +type TokenPriceData struct { + TokeName string `json:"toke_name"` + Price decimal.Decimal `json:"price"` + TokenAddress string `json:"token_address"` +} + +func RegisterTokenPriceProvider(name string, provider TokenPrice) { + tokenPriceProviders[name] = provider +} + +func ListTokenPriceProviders() []TokenPrice { + var providers []TokenPrice + for name := range tokenPriceProviders { + providers = append(providers, tokenPriceProviders[name]) + } + return providers +} + +func SourceTokens2Map(tokens []configs.SourceToken) (result map[string]configs.SourceToken) { + result = make(map[string]configs.SourceToken) + for index, token := range tokens { + if strings.EqualFold(token.Name, "USDT") { + continue + } + result[token.Name] = tokens[index] + } + return result +} + +func AppendUsdtPrice(data []TokenPriceData) []TokenPriceData { + var ( + result []TokenPriceData + hasUsdt bool + ) + for _, token := range data { + if strings.EqualFold(token.TokeName, "USDT") { + hasUsdt = true + result = append(result, TokenPriceData{ + TokeName: "USDT", + Price: decimal.NewFromInt(1), + TokenAddress: token.TokenAddress, + }) + continue + } + result = append(result, token) + } + if !hasUsdt { + result = append(result, TokenPriceData{ + TokeName: "USDT", + Price: decimal.NewFromInt(1), + }) + } + return result +} diff --git a/utils/token_price/mexc.go b/utils/token_price/mexc.go new file mode 100644 index 0000000..4b7fd31 --- /dev/null +++ b/utils/token_price/mexc.go @@ -0,0 +1,46 @@ +package token_price + +import ( + "context" + "github.com/shopspring/decimal" + "omni-balance/utils" + "omni-balance/utils/configs" + "strings" +) + +type Mexc struct { +} + +type mexcticker struct { + Symbol string `json:"symbol"` + Price decimal.Decimal `json:"price"` +} + +func (m Mexc) GetTokenPriceInUSDT(ctx context.Context, tokens ...configs.SourceToken) ([]TokenPriceData, error) { + var tokenNames = SourceTokens2Map(tokens) + + var tickers []mexcticker + err := utils.Request(ctx, "GET", "https://api.mexc.com/api/v3/ticker/price", nil, &tickers) + if err != nil { + return nil, err + } + var result []TokenPriceData + for _, ticker := range tickers { + name := strings.TrimRight(ticker.Symbol, "USDT") + if _, ok := tokenNames[name]; !ok { + continue + } + if ticker.Price.LessThan(decimal.Zero) { + continue + } + result = append(result, TokenPriceData{ + TokeName: name, + Price: ticker.Price, + }) + } + return AppendUsdtPrice(result), nil +} + +func (m Mexc) Name() string { + return "mexc" +} diff --git a/utils/token_price/okx.go b/utils/token_price/okx.go new file mode 100644 index 0000000..f25fb3d --- /dev/null +++ b/utils/token_price/okx.go @@ -0,0 +1,56 @@ +package token_price + +import ( + "context" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "omni-balance/utils" + "omni-balance/utils/configs" + "strings" +) + +type OKX struct { +} + +type marketResp struct { + Code string `json:"code"` + Msg string `json:"msg"` + Data []struct { + InstId string `json:"instId"` + IdxPx decimal.Decimal `json:"idxPx"` + High24H decimal.Decimal `json:"high24h"` + SodUtc0 decimal.Decimal `json:"sodUtc0"` + Open24H decimal.Decimal `json:"open24h"` + Low24H decimal.Decimal `json:"low24h"` + SodUtc8 decimal.Decimal `json:"sodUtc8"` + Ts string `json:"ts"` + } `json:"data"` +} + +func (O OKX) GetTokenPriceInUSDT(ctx context.Context, tokens ...configs.SourceToken) ([]TokenPriceData, error) { + var tokenNames = SourceTokens2Map(tokens) + var data marketResp + if err := utils.Request(ctx, "GET", "https://www.okx.com/api/v5/market/index-tickers?quoteCcy=USDT", nil, &data); err != nil { + return nil, errors.Wrap(err, "decode response") + } + + var result []TokenPriceData + for _, token := range data.Data { + tokenName := strings.Split(token.InstId, "-")[0] + if _, ok := tokenNames[tokenName]; !ok { + continue + } + if token.IdxPx.LessThan(decimal.Zero) { + continue + } + result = append(result, TokenPriceData{ + Price: token.IdxPx, + TokeName: tokenName, + }) + } + return AppendUsdtPrice(result), nil +} + +func (O OKX) Name() string { + return "okx" +} diff --git a/utils/util.go b/utils/util.go new file mode 100644 index 0000000..2fc0ab2 --- /dev/null +++ b/utils/util.go @@ -0,0 +1,192 @@ +package utils + +import ( + "context" + "crypto/md5" + "encoding/json" + "fmt" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + "github.com/stretchr/testify/assert" + "golang.org/x/exp/constraints" + "golang.org/x/exp/rand" + "io" + "math/big" + "net/http" + "omni-balance/utils/constant" + "reflect" + "strings" + "sync/atomic" + "testing" + "time" +) + +var ( + index atomic.Int64 +) + +func GetNextIndex(v int) int { + if v <= 0 { + return 0 + } + return int(index.Add(1) % int64(v)) +} + +func GetNextIndexStrings(v []string) string { + if len(v) <= 0 { + return "" + } + return v[GetNextIndex(len(v))] +} + +func ExtractTagFromStruct(s interface{}, tags ...string) map[string]map[string]string { + t := reflect.TypeOf(s) + t = t.Elem() + var result = make(map[string]map[string]string) + n := t.NumField() + for i := 0; i < n; i++ { + field := t.Field(i) + for _, tag := range tags { + if _, ok := result[field.Name]; !ok { + result[field.Name] = make(map[string]string) + } + result[field.Name][tag] = field.Tag.Get(tag) + } + } + return result +} + +func GetCurrencyPair(sourceToken, sep, targetToken string) string { + return strings.ToUpper(fmt.Sprintf("%s%s%s", sourceToken, sep, targetToken)) +} + +type Element interface { + string | int8 | int16 | int32 | int64 | int | float32 | float64 | uint | uint8 | uint16 | uint32 | uint64 +} + +func InArray[t Element](value t, arr []t) bool { + for _, v := range arr { + if value != v { + continue + } + return true + } + return false +} + +func InArrayFold(value string, arr []string) bool { + for _, v := range arr { + if !strings.EqualFold(v, value) { + continue + } + return true + } + return false +} + +func AssertEqualFold(t *testing.T, a, b string) { + assert.Equal(t, strings.ToUpper(a), strings.ToUpper(b)) +} + +func ZFillByte(b []byte, n int) []byte { + if len(b) >= n { + return b + } + return append(make([]byte, n-len(b)), b...) +} + +// SetBit sets the nth bit of the byte to v. +func SetBit(b byte, n byte, v bool) byte { + if v { + return b | (1 << n) + } + return b &^ (1 << n) +} + +type PermitSingle struct { + Owner string + Spender string + Value *big.Int + Deadline *big.Int + Nonce *big.Int +} + +func RandomNumberIn[t constraints.Integer](min, max t) t { + rand.New(rand.NewSource(uint64(time.Now().UnixMilli()))) + return t(rand.Intn(int(max-min+1)) + int(min)) +} + +func Choose[T any](arr []T) T { + if len(arr) == 0 { + panic("arr is empty") + } + if len(arr) == 1 { + return arr[0] + } + return arr[RandomNumberIn(0, len(arr)-1)] +} + +func Request(ctx context.Context, method string, url string, body io.Reader, dest interface{}, headers ...string) error { + req, err := http.NewRequest(method, url, body) + if err != nil { + return errors.Wrap(err, "new request") + } + for i := 0; i < len(headers); i += 2 { + req.Header.Set(headers[i], headers[i+1]) + } + req = req.WithContext(ctx) + var count int + for count < 3 { + count++ + resp, err := new(http.Client).Do(req) + if err != nil { + logrus.Debugf("request failed: %s", err) + time.Sleep(time.Second) + continue + } + if dest == nil { + _ = resp.Body.Close() + return nil + } + data, err := io.ReadAll(resp.Body) + if err != nil { + logrus.Debugf("read response failed: %s", err) + _ = resp.Body.Close() + time.Sleep(time.Second) + continue + } + _ = resp.Body.Close() + return json.Unmarshal(data, dest) + } + return errors.New("request failed") +} + +func String(s string) *string { + return &s +} + +func Number[t constraints.Integer | constraints.Float](n t) *t { + return &n +} + +func Md5(s string) string { + return fmt.Sprintf("%x", md5.Sum([]byte(s))) +} + +func ToMap(v interface{}) map[string]interface{} { + data, _ := json.Marshal(v) + var result map[string]interface{} + _ = json.Unmarshal(data, &result) + return result +} + +func SetLogToCtx(ctx context.Context, log *logrus.Entry) context.Context { + return context.WithValue(ctx, constant.LogKeyInCtx, log) +} + +func GetLogFromCtx(ctx context.Context) *logrus.Entry { + if v, ok := ctx.Value(constant.LogKeyInCtx).(*logrus.Entry); ok { + return v + } + return logrus.NewEntry(logrus.StandardLogger()) +} diff --git a/utils/util_test.go b/utils/util_test.go new file mode 100644 index 0000000..6cff3a5 --- /dev/null +++ b/utils/util_test.go @@ -0,0 +1,132 @@ +package utils + +import ( + "reflect" + "testing" +) + +type TestStruct struct { + Name string `json:"name" db:"Name"` + Address string `json:"address" db:"Addr"` + Age uint `json:"age" db:"Age"` +} + +func TestExtractTagFromStruct(t *testing.T) { + tests := []struct { + name string + s interface{} + tags []string + want map[string]map[string]string + }{ + { + "test with json and db tag", + &TestStruct{Name: "John", Address: "Street X", Age: 20}, + []string{"json", "db"}, + map[string]map[string]string{ + "Name": {"json": "name", "db": "Name"}, + "Address": {"json": "address", "db": "Addr"}, + "Age": {"json": "age", "db": "Age"}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := ExtractTagFromStruct(tt.s, tt.tags...); !reflect.DeepEqual(got, tt.want) { + t.Errorf("ExtractTagFromStruct() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestGetNextIndexStrings(t *testing.T) { + cases := []struct { + name string + input []string + expected string + isErr bool + reset bool + }{ + {"empty", []string{}, "", false, false}, + {"single element", []string{"one"}, "one", false, false}, + {"multiple elements", []string{"one", "two", "three"}, "three", false, false}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if tc.reset { + index.Store(0) + } + actual := GetNextIndexStrings(tc.input) + if actual != tc.expected { + t.Errorf("expected %v, got %v", tc.expected, actual) + } + }) + } +} + +func TestGetNextIndex(t *testing.T) { + + tests := []struct { + name string + arg int + want int + }{ + {"Negative Input", -5, 0}, + {"Zero Input", 0, 0}, + {"Positive Input", 7, 1}, // Assuming index start at 0 + {"Large Positive Input", 100000, 1}, // Assuming index start at 0 + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + index.Store(0) + if got := GetNextIndex(tt.arg); got != tt.want { + t.Errorf("GetNextIndex() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestByteZfill(t *testing.T) { + type args struct { + b []byte + n int + } + tests := []struct { + name string + args args + want []byte + }{ + { + name: "test1", + args: args{ + b: []byte{1, 2, 3}, + n: 5, + }, + want: []byte{0, 0, 1, 2, 3}, + }, + { + name: "test2", + args: args{ + b: []byte{1, 2, 3}, + n: 2, + }, + want: []byte{1, 2, 3}, + }, + { + name: "test3", + args: args{ + b: []byte{1, 2, 3}, + n: 5, + }, + want: []byte{0, 0, 1, 2, 3}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := ZFillByte(tt.args.b, tt.args.n); !reflect.DeepEqual(got, tt.want) { + t.Errorf("ZFillByte() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/utils/wallet_monitor/monitor.go b/utils/wallet_monitor/monitor.go new file mode 100644 index 0000000..4464998 --- /dev/null +++ b/utils/wallet_monitor/monitor.go @@ -0,0 +1,146 @@ +package wallet_monitor + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "omni-balance/utils/chains" + "omni-balance/utils/configs" + "omni-balance/utils/wallets" + "sync" +) + +type Monitor struct { + config configs.Config +} + +type ReBalanceTokenChain struct { + BuyTokenInfo + ChainName string `json:"chain_name"` +} + +type BuyTokenInfo struct { + TokenBalance decimal.Decimal `json:"balance"` + Amount decimal.Decimal `json:"amount"` +} + +type Result struct { + // need rebalance wallet + Wallet string `json:"wallet"` + // need rebalance tokens + Tokens []ReBalanceToken `json:"tokens"` +} + +type ReBalanceToken struct { + Name string `json:"name"` + Chains []ReBalanceTokenChain `json:"chains"` +} + +type IgnoreToken struct { + Name string `json:"name"` + Chain string `json:"chain"` + Address string `json:"wallet"` +} + +func NewMonitor(conf configs.Config) *Monitor { + return &Monitor{config: conf} +} + +func (m *Monitor) GetBalance(ctx context.Context, wallet wallets.Wallets, tokenName, chainName string) (balance decimal.Decimal, err error) { + var ( + chain = m.config.GetChainConfig(chainName) + token = chain.GetToken(tokenName) + ) + + if len(chain.RpcEndpoints) == 0 { + return decimal.Zero, errors.New("rpc endpoints is empty") + } + client, err := chains.NewTryClient(ctx, chain.RpcEndpoints) + if err != nil { + return decimal.Zero, errors.Wrap(err, "dial rpc") + } + defer client.Close() + return wallet.GetExternalBalance(ctx, common.HexToAddress(token.ContractAddress), token.Decimals, client) +} + +func (m *Monitor) Check(ctx context.Context, ignoreToken ...IgnoreToken) (result []Result, err error) { + var ( + // balances {"wallet": {"token_name": "chain_name": BuyTokenInfo}} + balances = map[string]map[string][]ReBalanceTokenChain{} + w sync.WaitGroup + mutex sync.Mutex + ignoreTokens = make(map[string]map[string]map[string]struct{}) + ) + for _, token := range ignoreToken { + if _, ok := ignoreTokens[token.Address]; !ok { + ignoreTokens[token.Address] = make(map[string]map[string]struct{}) + } + if _, ok := ignoreTokens[token.Address][token.Name]; !ok { + ignoreTokens[token.Address][token.Name] = make(map[string]struct{}) + } + ignoreTokens[token.Address][token.Name][token.Chain] = struct{}{} + } + + appendBalances := func(wallet, tokenName string, rbtc ReBalanceTokenChain) { + mutex.Lock() + defer mutex.Unlock() + if _, ok := balances[wallet]; !ok { + balances[wallet] = make(map[string][]ReBalanceTokenChain) + } + balances[wallet][tokenName] = append(balances[wallet][tokenName], rbtc) + } + for _, wallet := range m.config.Wallets { + w.Add(1) + go func(wallet configs.Wallet) { + defer w.Done() + for _, token := range wallet.Tokens { + for _, chainName := range token.Chains { + if _, ok := ignoreTokens[wallet.Address][token.Name][chainName]; ok { + continue + } + balance, err := m.GetBalance(ctx, m.config.GetWallet(wallet.Address), token.Name, chainName) + if err != nil { + logrus.Errorf("get %s balance error: %s", token.Name, err.Error()) + continue + } + + threshold := m.config.GetTokenThreshold(wallet.Address, token.Name, chainName) + logrus.Debugf("wallet %s token %s on %s balance is %s, the threshold is %s", + wallet.Address, token.Name, chainName, balance.String(), threshold.String()) + if balance.GreaterThan(threshold) { + continue + } + + amount := m.config.GetTokenPurchaseAmount(wallet.Address, token.Name, chainName) + if amount.LessThanOrEqual(decimal.Zero) { + logrus.Errorf("token %s config amount is invalid", token.Name) + continue + } + logrus.Debugf("wallet %s token %s on %s need rebalance %s", + wallet.Address, token.Name, chainName, amount.String()) + appendBalances(wallet.Address, token.Name, ReBalanceTokenChain{ + BuyTokenInfo: BuyTokenInfo{ + TokenBalance: balance, + Amount: amount, + }, + ChainName: chainName, + }) + } + } + }(wallet) + } + w.Wait() + for walletAddress, item := range balances { + r := &Result{Wallet: walletAddress} + for tokenName, chains := range item { + r.Tokens = append(r.Tokens, ReBalanceToken{ + Name: tokenName, + Chains: chains, + }) + } + result = append(result, *r) + } + return +} diff --git a/utils/wallets/init.go b/utils/wallets/init.go new file mode 100644 index 0000000..111b74c --- /dev/null +++ b/utils/wallets/init.go @@ -0,0 +1,13 @@ +package wallets + +var ( + wallets = make(map[string]func(conf WalletConfig) Wallets) +) + +func Register(name string, wallet func(conf WalletConfig) Wallets) { + wallets[name] = wallet +} + +func Get(name string) func(conf WalletConfig) Wallets { + return wallets[name] +} diff --git a/utils/wallets/private_key.go b/utils/wallets/private_key.go new file mode 100644 index 0000000..5121d33 --- /dev/null +++ b/utils/wallets/private_key.go @@ -0,0 +1,190 @@ +package wallets + +import ( + "context" + "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethclient/simulated" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "log" + "omni-balance/utils/chains" + "omni-balance/utils/constant" + "omni-balance/utils/erc20" + "omni-balance/utils/error_types" + "omni-balance/utils/locks" + "strings" +) + +func init() { + Register("", func(conf WalletConfig) Wallets { + return NewPrivateKeyWallet(conf) + }) +} + +type PrivateKeyWallet struct { + conf WalletConfig +} + +func NewPrivateKeyWallet(conf WalletConfig) *PrivateKeyWallet { + p := &PrivateKeyWallet{ + conf: conf, + } + + if p.conf.PrivateKey == "" && + conf.Operator.Address.Cmp(constant.ZeroAddress) == 0 && + conf.Operator.PrivateKey == "" { + log.Fatalln("privateKey and operator.privateKey can not be empty") + } + if p.conf.Operator.Address.Cmp(constant.ZeroAddress) != 0 && p.conf.PrivateKey == "" { + log.Fatalln("privateKey can not be empty when operator.address is not empty") + } + + if p.conf.Operator.Operator.Cmp(constant.ZeroAddress) != 0 && p.conf.Operator.PrivateKey == "" { + log.Fatalln("operator.privateKey can not be empty when operator.address is not empty") + } + checkKey := func(privateKey string, address common.Address) error { + key, err := crypto.HexToECDSA(privateKey) + if err != nil { + return errors.Wrap(err, "crypto.HexToECDSA") + } + if !strings.EqualFold(address.Hex(), crypto.PubkeyToAddress(key.PublicKey).Hex()) { + return error_types.ErrPrivateKeyNotMatch + } + return nil + } + + if conf.Operator.Address.Cmp(constant.ZeroAddress) == 0 && conf.PrivateKey != "" && checkKey(conf.PrivateKey, conf.Address) != nil { + log.Fatalln("privateKey not match address") + } + + if conf.Operator.Address.Cmp(constant.ZeroAddress) != 0 && + conf.Operator.Operator.Cmp(constant.ZeroAddress) == 0 && + conf.PrivateKey != "" && checkKey(conf.PrivateKey, conf.Operator.Address) != nil { + log.Fatalln("privateKey not match operator address") + } + + if conf.Operator.Address.Cmp(constant.ZeroAddress) != 0 && + conf.Operator.Operator.Cmp(constant.ZeroAddress) != 0 && + conf.PrivateKey != "" && checkKey(conf.PrivateKey, conf.Operator.Operator) != nil { + log.Fatalln("privateKey not match operator address") + } + return p +} + +func (p *PrivateKeyWallet) GetAddress(isReal ...bool) common.Address { + if len(isReal) == 0 || + !isReal[0] || + p.conf.Operator.Address.Cmp(constant.ZeroAddress) == 0 { + return p.conf.Address + } + return p.conf.Operator.Address +} + +func (p *PrivateKeyWallet) IsSupportEip712() bool { + return true +} + +func (p *PrivateKeyWallet) Init(conf WalletConfig) error { + p.conf = conf + + return nil +} + +func (p *PrivateKeyWallet) IsDifferentAddress() bool { + return p.GetAddress().Cmp(p.GetAddress(true)) != 0 +} + +func (p *PrivateKeyWallet) CheckFullAccess(ctx context.Context) error { + return nil +} + +func (p *PrivateKeyWallet) GetExternalBalance(ctx context.Context, tokenAddress common.Address, decimals int32, + client simulated.Client) (decimal.Decimal, error) { + return p.balanceOf(ctx, p.GetAddress(), tokenAddress, decimals, client) +} + +func (p *PrivateKeyWallet) GetBalance(ctx context.Context, tokenAddress common.Address, decimals int32, + client simulated.Client) (decimal.Decimal, error) { + return p.balanceOf(ctx, p.GetAddress(true), tokenAddress, decimals, client) +} + +func (p *PrivateKeyWallet) balanceOf(ctx context.Context, wallet, tokenAddress common.Address, decimals int32, + client simulated.Client) (decimal.Decimal, error) { + if tokenAddress.Cmp(constant.ZeroAddress) == 0 { + balance, err := client.BalanceAt(ctx, wallet, nil) + if err != nil { + return decimal.Zero, errors.Wrap(err, "client.BalanceAt") + } + return chains.WeiToEth(balance, decimals), nil + } + token, err := erc20.NewTokenCaller(tokenAddress, client) + if err != nil { + return decimal.Zero, errors.Wrap(err, "erc20.NewToken") + } + balance, err := token.BalanceOf(&bind.CallOpts{Context: ctx}, wallet) + if err != nil { + return decimal.Zero, errors.Wrap(err, "token.BalanceOf") + } + return chains.WeiToEth(balance, decimals), nil +} + +func (p *PrivateKeyWallet) GetNonce(ctx context.Context, client simulated.Client) (uint64, error) { + return client.NonceAt(ctx, p.GetAddress(true), nil) +} + +func (p *PrivateKeyWallet) SendTransaction(ctx context.Context, tx *types.LegacyTx, + client simulated.Client) (common.Hash, error) { + if tx.GasPrice == nil { + gasPrice, err := client.SuggestGasPrice(ctx) + if err != nil { + return common.Hash{}, errors.Wrap(err, "get suggest gas") + } + tx.GasPrice = gasPrice + } + if tx.Gas == 0 { + gas, err := client.EstimateGas(ctx, ethereum.CallMsg{ + From: p.GetAddress(true), + To: tx.To, + Value: tx.Value, + Data: tx.Data, + }) + if err != nil { + return common.Hash{}, errors.Wrap(err, "get estimate gas") + } + tx.Gas = gas + } + if tx.Nonce == 0 { + nonce, err := p.GetNonce(ctx, client) + if err != nil { + return common.Hash{}, errors.Wrap(err, "get nonce") + } + tx.Nonce = nonce + } + + chainId, err := client.ChainID(ctx) + if err != nil { + return common.Hash{}, errors.Wrap(err, "get chain id") + } + + txData := types.NewTx(tx) + txData, err = chains.SignTx(txData, p.conf.PrivateKey, chainId.Int64()) + if err != nil { + return common.Hash{}, errors.Wrap(err, "sign tx") + } + key := locks.LockKey(p.GetAddress(true).Hex(), chainId.String()) + locks.LockWithKey(ctx, key) + defer locks.UnlockWithKey(ctx, key) + return txData.Hash(), client.SendTransaction(ctx, txData) +} + +func (p *PrivateKeyWallet) WaitTransaction(ctx context.Context, txHash common.Hash, client simulated.Client) error { + return chains.WaitForTx(ctx, client, txHash) +} + +func (p *PrivateKeyWallet) SignRawMessage(msg []byte) (sig []byte, err error) { + return chains.SignMsg(msg, p.conf.PrivateKey) +} diff --git a/utils/wallets/safe/init.go b/utils/wallets/safe/init.go new file mode 100644 index 0000000..d86c74f --- /dev/null +++ b/utils/wallets/safe/init.go @@ -0,0 +1,11 @@ +package safe + +import ( + "omni-balance/utils/wallets" +) + +func init() { + wallets.Register("safe", func(conf wallets.WalletConfig) wallets.Wallets { + return NewSafe(conf) + }) +} diff --git a/utils/wallets/safe/safe.go b/utils/wallets/safe/safe.go new file mode 100644 index 0000000..dabb324 --- /dev/null +++ b/utils/wallets/safe/safe.go @@ -0,0 +1,161 @@ +package safe + +import ( + "context" + "fmt" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient/simulated" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "omni-balance/utils" + "omni-balance/utils/chains" + "omni-balance/utils/constant" + "omni-balance/utils/error_types" + "omni-balance/utils/notice" + "omni-balance/utils/wallets" + "time" +) + +type Safe struct { + conf wallets.WalletConfig + operatorSafe *Safe +} + +func NewSafe(conf wallets.WalletConfig) *Safe { + if conf.Operator.Address.Cmp(constant.ZeroAddress) == 0 { + panic("operator address is empty") + } + if conf.Operator.Address.Cmp(conf.Address) == 0 { + panic("operator address is same as safe address") + } + s := &Safe{ + conf: conf, + } + if conf.Operator.MultiSignType != "" { + operator := conf.Operator + s.operatorSafe = &Safe{ + conf: wallets.WalletConfig{ + PrivateKey: operator.PrivateKey, + Address: operator.Address, + Operator: wallets.Operator{ + Address: operator.Operator, + PrivateKey: operator.PrivateKey, + }, + MultiSignType: operator.MultiSignType, + }, + } + } + return s +} + +func (*Safe) IsSupportEip712() bool { + return false +} + +func (s *Safe) CheckFullAccess(ctx context.Context) error { + info, err := s.safeWalletInfo(ctx) + if err != nil { + return err + } + if !utils.InArrayFold(s.conf.Operator.Address.Hex(), info.Owners) { + return errors.New("operator is not in owners") + } + return nil +} + +// GetAddress retrieves the address from the security configuration. +// If isReal is provided as true and the multisig type is set, +// it returns the operator's address; otherwise, it returns the default address. +// Parameters: +// +// isReal - An optional boolean indicating whether to return the real address. +// +// Returns: +// +// common.Address - The address from the configuration. +func (s *Safe) GetAddress(isReal ...bool) common.Address { + if len(isReal) > 0 && isReal[0] { + return s.conf.Operator.Address + } + return s.conf.Address +} + +func (s *Safe) IsDifferentAddress() bool { + return true +} + +func (s *Safe) SignRawMessage(msg []byte) (sig []byte, err error) { + return nil, error_types.ErrUnsupportedWalletType +} + +func (s *Safe) GetExternalBalance(ctx context.Context, tokenAddress common.Address, decimals int32, + client simulated.Client) (decimal.Decimal, error) { + return s.GetBalance(ctx, tokenAddress, decimals, client) +} + +func (s *Safe) GetBalance(ctx context.Context, tokenAddress common.Address, decimals int32, + client simulated.Client) (decimal.Decimal, error) { + return chains.GetTokenBalance(ctx, client, tokenAddress.Hex(), s.GetAddress().Hex(), decimals) +} + +func (s *Safe) GetNonce(ctx context.Context, client simulated.Client) (uint64, error) { + log := utils.GetLogFromCtx(ctx) + if s.operatorSafe != nil { + nonce, err := s.operatorSafe.nonce(ctx) + log.Debugf("operator %s safe nonce: %d", s.conf.Operator.Address.Hex(), nonce) + return uint64(nonce), err + } + return client.NonceAt(ctx, s.GetAddress(), nil) +} + +func (s *Safe) SendTransaction(ctx context.Context, tx *types.LegacyTx, client simulated.Client) (common.Hash, error) { + return s.MultisigTransaction(ctx, tx, client) +} + +func (s *Safe) WaitTransaction(ctx context.Context, txHash common.Hash, client simulated.Client) error { + var ( + log = utils.GetLogFromCtx(ctx) + t = time.NewTicker(time.Second * 2) + count = 0 + ) + defer t.Stop() + for count < 60 { // 180s + select { + case <-ctx.Done(): + return context.Canceled + case <-t.C: + tx, err := s.GetMultiSigTransaction(ctx, txHash) + if err != nil { + log.Debugf("wait transaction %s error: %s", txHash, err) + continue + } + if len(tx.Confirmations) < tx.ConfirmationsRequired { + log.Debugf("transaction %s confirmations: %d, required: %d, try to sending notice", + txHash, len(tx.Confirmations), tx.ConfirmationsRequired) + if err := notice.Send(ctx, + fmt.Sprintf("wait transaction %s confirmations", txHash), + fmt.Sprintf("Please go to %s to confirm %d nonce transaction", tx.Safe, tx.Nonce), + logrus.WarnLevel, + ); err != nil { + log.Debugf("send notice error: %s", err) + } + continue + } + if !tx.IsExecuted { + log.Debugf("transaction %s is not executed", txHash) + count++ + continue + } + if !tx.IsSuccessful { + log.Debugf("transaction %s is not successful", txHash) + count++ + continue + } + log.Debugf("transaction %s is successful", txHash) + return nil + } + } + return errors.Errorf("wait transaction %s timeout", txHash) +} diff --git a/utils/wallets/safe/safe_abi/safe.go b/utils/wallets/safe/safe_abi/safe.go new file mode 100644 index 0000000..ec0353b --- /dev/null +++ b/utils/wallets/safe/safe_abi/safe.go @@ -0,0 +1,3412 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package safe_abi + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription + _ = abi.ConvertType +) + +// SafeAbiMetaData contains all meta data concerning the SafeAbi contract. +var SafeAbiMetaData = &bind.MetaData{ + ABI: "[{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"AddedOwner\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"approvedHash\",\"type\":\"bytes32\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"ApproveHash\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"handler\",\"type\":\"address\"}],\"name\":\"ChangedFallbackHandler\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"guard\",\"type\":\"address\"}],\"name\":\"ChangedGuard\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"threshold\",\"type\":\"uint256\"}],\"name\":\"ChangedThreshold\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"module\",\"type\":\"address\"}],\"name\":\"DisabledModule\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"module\",\"type\":\"address\"}],\"name\":\"EnabledModule\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"txHash\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"payment\",\"type\":\"uint256\"}],\"name\":\"ExecutionFailure\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"module\",\"type\":\"address\"}],\"name\":\"ExecutionFromModuleFailure\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"module\",\"type\":\"address\"}],\"name\":\"ExecutionFromModuleSuccess\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"txHash\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"payment\",\"type\":\"uint256\"}],\"name\":\"ExecutionSuccess\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"RemovedOwner\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"module\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"indexed\":false,\"internalType\":\"enumEnum.Operation\",\"name\":\"operation\",\"type\":\"uint8\"}],\"name\":\"SafeModuleTransaction\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"indexed\":false,\"internalType\":\"enumEnum.Operation\",\"name\":\"operation\",\"type\":\"uint8\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"safeTxGas\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"baseGas\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"gasPrice\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"gasToken\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"addresspayable\",\"name\":\"refundReceiver\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"signatures\",\"type\":\"bytes\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"additionalInfo\",\"type\":\"bytes\"}],\"name\":\"SafeMultiSigTransaction\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"SafeReceived\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"initiator\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address[]\",\"name\":\"owners\",\"type\":\"address[]\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"threshold\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"initializer\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"fallbackHandler\",\"type\":\"address\"}],\"name\":\"SafeSetup\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"bytes32\",\"name\":\"msgHash\",\"type\":\"bytes32\"}],\"name\":\"SignMsg\",\"type\":\"event\"},{\"stateMutability\":\"nonpayable\",\"type\":\"fallback\"},{\"inputs\":[],\"name\":\"VERSION\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"_threshold\",\"type\":\"uint256\"}],\"name\":\"addOwnerWithThreshold\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"hashToApprove\",\"type\":\"bytes32\"}],\"name\":\"approveHash\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"approvedHashes\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_threshold\",\"type\":\"uint256\"}],\"name\":\"changeThreshold\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"dataHash\",\"type\":\"bytes32\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"bytes\",\"name\":\"signatures\",\"type\":\"bytes\"},{\"internalType\":\"uint256\",\"name\":\"requiredSignatures\",\"type\":\"uint256\"}],\"name\":\"checkNSignatures\",\"outputs\":[],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"dataHash\",\"type\":\"bytes32\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"bytes\",\"name\":\"signatures\",\"type\":\"bytes\"}],\"name\":\"checkSignatures\",\"outputs\":[],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"prevModule\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"module\",\"type\":\"address\"}],\"name\":\"disableModule\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"domainSeparator\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"module\",\"type\":\"address\"}],\"name\":\"enableModule\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"enumEnum.Operation\",\"name\":\"operation\",\"type\":\"uint8\"},{\"internalType\":\"uint256\",\"name\":\"safeTxGas\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"baseGas\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"gasPrice\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"gasToken\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"refundReceiver\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"_nonce\",\"type\":\"uint256\"}],\"name\":\"encodeTransactionData\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"enumEnum.Operation\",\"name\":\"operation\",\"type\":\"uint8\"},{\"internalType\":\"uint256\",\"name\":\"safeTxGas\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"baseGas\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"gasPrice\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"gasToken\",\"type\":\"address\"},{\"internalType\":\"addresspayable\",\"name\":\"refundReceiver\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"signatures\",\"type\":\"bytes\"}],\"name\":\"execTransaction\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"enumEnum.Operation\",\"name\":\"operation\",\"type\":\"uint8\"}],\"name\":\"execTransactionFromModule\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"success\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"enumEnum.Operation\",\"name\":\"operation\",\"type\":\"uint8\"}],\"name\":\"execTransactionFromModuleReturnData\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"success\",\"type\":\"bool\"},{\"internalType\":\"bytes\",\"name\":\"returnData\",\"type\":\"bytes\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getChainId\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"start\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"pageSize\",\"type\":\"uint256\"}],\"name\":\"getModulesPaginated\",\"outputs\":[{\"internalType\":\"address[]\",\"name\":\"array\",\"type\":\"address[]\"},{\"internalType\":\"address\",\"name\":\"next\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getOwners\",\"outputs\":[{\"internalType\":\"address[]\",\"name\":\"\",\"type\":\"address[]\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"offset\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"length\",\"type\":\"uint256\"}],\"name\":\"getStorageAt\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getThreshold\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"enumEnum.Operation\",\"name\":\"operation\",\"type\":\"uint8\"},{\"internalType\":\"uint256\",\"name\":\"safeTxGas\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"baseGas\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"gasPrice\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"gasToken\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"refundReceiver\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"_nonce\",\"type\":\"uint256\"}],\"name\":\"getTransactionHash\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"module\",\"type\":\"address\"}],\"name\":\"isModuleEnabled\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"isOwner\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"nonce\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"prevOwner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"_threshold\",\"type\":\"uint256\"}],\"name\":\"removeOwner\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"enumEnum.Operation\",\"name\":\"operation\",\"type\":\"uint8\"}],\"name\":\"requiredTxGas\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"handler\",\"type\":\"address\"}],\"name\":\"setFallbackHandler\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"guard\",\"type\":\"address\"}],\"name\":\"setGuard\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address[]\",\"name\":\"_owners\",\"type\":\"address[]\"},{\"internalType\":\"uint256\",\"name\":\"_threshold\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"address\",\"name\":\"fallbackHandler\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"paymentToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"payment\",\"type\":\"uint256\"},{\"internalType\":\"addresspayable\",\"name\":\"paymentReceiver\",\"type\":\"address\"}],\"name\":\"setup\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"signedMessages\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"targetContract\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"calldataPayload\",\"type\":\"bytes\"}],\"name\":\"simulateAndRevert\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"prevOwner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"oldOwner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"swapOwner\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}]", +} + +// SafeAbiABI is the input ABI used to generate the binding from. +// Deprecated: Use SafeAbiMetaData.ABI instead. +var SafeAbiABI = SafeAbiMetaData.ABI + +// SafeAbi is an auto generated Go binding around an Ethereum contract. +type SafeAbi struct { + SafeAbiCaller // Read-only binding to the contract + SafeAbiTransactor // Write-only binding to the contract + SafeAbiFilterer // Log filterer for contract events +} + +// SafeAbiCaller is an auto generated read-only Go binding around an Ethereum contract. +type SafeAbiCaller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// SafeAbiTransactor is an auto generated write-only Go binding around an Ethereum contract. +type SafeAbiTransactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// SafeAbiFilterer is an auto generated log filtering Go binding around an Ethereum contract events. +type SafeAbiFilterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// SafeAbiSession is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type SafeAbiSession struct { + Contract *SafeAbi // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// SafeAbiCallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type SafeAbiCallerSession struct { + Contract *SafeAbiCaller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// SafeAbiTransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type SafeAbiTransactorSession struct { + Contract *SafeAbiTransactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// SafeAbiRaw is an auto generated low-level Go binding around an Ethereum contract. +type SafeAbiRaw struct { + Contract *SafeAbi // Generic contract binding to access the raw methods on +} + +// SafeAbiCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type SafeAbiCallerRaw struct { + Contract *SafeAbiCaller // Generic read-only contract binding to access the raw methods on +} + +// SafeAbiTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type SafeAbiTransactorRaw struct { + Contract *SafeAbiTransactor // Generic write-only contract binding to access the raw methods on +} + +// NewSafeAbi creates a new instance of SafeAbi, bound to a specific deployed contract. +func NewSafeAbi(address common.Address, backend bind.ContractBackend) (*SafeAbi, error) { + contract, err := bindSafeAbi(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &SafeAbi{SafeAbiCaller: SafeAbiCaller{contract: contract}, SafeAbiTransactor: SafeAbiTransactor{contract: contract}, SafeAbiFilterer: SafeAbiFilterer{contract: contract}}, nil +} + +// NewSafeAbiCaller creates a new read-only instance of SafeAbi, bound to a specific deployed contract. +func NewSafeAbiCaller(address common.Address, caller bind.ContractCaller) (*SafeAbiCaller, error) { + contract, err := bindSafeAbi(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &SafeAbiCaller{contract: contract}, nil +} + +// NewSafeAbiTransactor creates a new write-only instance of SafeAbi, bound to a specific deployed contract. +func NewSafeAbiTransactor(address common.Address, transactor bind.ContractTransactor) (*SafeAbiTransactor, error) { + contract, err := bindSafeAbi(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &SafeAbiTransactor{contract: contract}, nil +} + +// NewSafeAbiFilterer creates a new log filterer instance of SafeAbi, bound to a specific deployed contract. +func NewSafeAbiFilterer(address common.Address, filterer bind.ContractFilterer) (*SafeAbiFilterer, error) { + contract, err := bindSafeAbi(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &SafeAbiFilterer{contract: contract}, nil +} + +// bindSafeAbi binds a generic wrapper to an already deployed contract. +func bindSafeAbi(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := SafeAbiMetaData.GetAbi() + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, *parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_SafeAbi *SafeAbiRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _SafeAbi.Contract.SafeAbiCaller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_SafeAbi *SafeAbiRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _SafeAbi.Contract.SafeAbiTransactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_SafeAbi *SafeAbiRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _SafeAbi.Contract.SafeAbiTransactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_SafeAbi *SafeAbiCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _SafeAbi.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_SafeAbi *SafeAbiTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _SafeAbi.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_SafeAbi *SafeAbiTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _SafeAbi.Contract.contract.Transact(opts, method, params...) +} + +// VERSION is a free data retrieval call binding the contract method 0xffa1ad74. +// +// Solidity: function VERSION() view returns(string) +func (_SafeAbi *SafeAbiCaller) VERSION(opts *bind.CallOpts) (string, error) { + var out []interface{} + err := _SafeAbi.contract.Call(opts, &out, "VERSION") + + if err != nil { + return *new(string), err + } + + out0 := *abi.ConvertType(out[0], new(string)).(*string) + + return out0, err + +} + +// VERSION is a free data retrieval call binding the contract method 0xffa1ad74. +// +// Solidity: function VERSION() view returns(string) +func (_SafeAbi *SafeAbiSession) VERSION() (string, error) { + return _SafeAbi.Contract.VERSION(&_SafeAbi.CallOpts) +} + +// VERSION is a free data retrieval call binding the contract method 0xffa1ad74. +// +// Solidity: function VERSION() view returns(string) +func (_SafeAbi *SafeAbiCallerSession) VERSION() (string, error) { + return _SafeAbi.Contract.VERSION(&_SafeAbi.CallOpts) +} + +// ApprovedHashes is a free data retrieval call binding the contract method 0x7d832974. +// +// Solidity: function approvedHashes(address , bytes32 ) view returns(uint256) +func (_SafeAbi *SafeAbiCaller) ApprovedHashes(opts *bind.CallOpts, arg0 common.Address, arg1 [32]byte) (*big.Int, error) { + var out []interface{} + err := _SafeAbi.contract.Call(opts, &out, "approvedHashes", arg0, arg1) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// ApprovedHashes is a free data retrieval call binding the contract method 0x7d832974. +// +// Solidity: function approvedHashes(address , bytes32 ) view returns(uint256) +func (_SafeAbi *SafeAbiSession) ApprovedHashes(arg0 common.Address, arg1 [32]byte) (*big.Int, error) { + return _SafeAbi.Contract.ApprovedHashes(&_SafeAbi.CallOpts, arg0, arg1) +} + +// ApprovedHashes is a free data retrieval call binding the contract method 0x7d832974. +// +// Solidity: function approvedHashes(address , bytes32 ) view returns(uint256) +func (_SafeAbi *SafeAbiCallerSession) ApprovedHashes(arg0 common.Address, arg1 [32]byte) (*big.Int, error) { + return _SafeAbi.Contract.ApprovedHashes(&_SafeAbi.CallOpts, arg0, arg1) +} + +// CheckNSignatures is a free data retrieval call binding the contract method 0x12fb68e0. +// +// Solidity: function checkNSignatures(bytes32 dataHash, bytes data, bytes signatures, uint256 requiredSignatures) view returns() +func (_SafeAbi *SafeAbiCaller) CheckNSignatures(opts *bind.CallOpts, dataHash [32]byte, data []byte, signatures []byte, requiredSignatures *big.Int) error { + var out []interface{} + err := _SafeAbi.contract.Call(opts, &out, "checkNSignatures", dataHash, data, signatures, requiredSignatures) + + if err != nil { + return err + } + + return err + +} + +// CheckNSignatures is a free data retrieval call binding the contract method 0x12fb68e0. +// +// Solidity: function checkNSignatures(bytes32 dataHash, bytes data, bytes signatures, uint256 requiredSignatures) view returns() +func (_SafeAbi *SafeAbiSession) CheckNSignatures(dataHash [32]byte, data []byte, signatures []byte, requiredSignatures *big.Int) error { + return _SafeAbi.Contract.CheckNSignatures(&_SafeAbi.CallOpts, dataHash, data, signatures, requiredSignatures) +} + +// CheckNSignatures is a free data retrieval call binding the contract method 0x12fb68e0. +// +// Solidity: function checkNSignatures(bytes32 dataHash, bytes data, bytes signatures, uint256 requiredSignatures) view returns() +func (_SafeAbi *SafeAbiCallerSession) CheckNSignatures(dataHash [32]byte, data []byte, signatures []byte, requiredSignatures *big.Int) error { + return _SafeAbi.Contract.CheckNSignatures(&_SafeAbi.CallOpts, dataHash, data, signatures, requiredSignatures) +} + +// CheckSignatures is a free data retrieval call binding the contract method 0x934f3a11. +// +// Solidity: function checkSignatures(bytes32 dataHash, bytes data, bytes signatures) view returns() +func (_SafeAbi *SafeAbiCaller) CheckSignatures(opts *bind.CallOpts, dataHash [32]byte, data []byte, signatures []byte) error { + var out []interface{} + err := _SafeAbi.contract.Call(opts, &out, "checkSignatures", dataHash, data, signatures) + + if err != nil { + return err + } + + return err + +} + +// CheckSignatures is a free data retrieval call binding the contract method 0x934f3a11. +// +// Solidity: function checkSignatures(bytes32 dataHash, bytes data, bytes signatures) view returns() +func (_SafeAbi *SafeAbiSession) CheckSignatures(dataHash [32]byte, data []byte, signatures []byte) error { + return _SafeAbi.Contract.CheckSignatures(&_SafeAbi.CallOpts, dataHash, data, signatures) +} + +// CheckSignatures is a free data retrieval call binding the contract method 0x934f3a11. +// +// Solidity: function checkSignatures(bytes32 dataHash, bytes data, bytes signatures) view returns() +func (_SafeAbi *SafeAbiCallerSession) CheckSignatures(dataHash [32]byte, data []byte, signatures []byte) error { + return _SafeAbi.Contract.CheckSignatures(&_SafeAbi.CallOpts, dataHash, data, signatures) +} + +// DomainSeparator is a free data retrieval call binding the contract method 0xf698da25. +// +// Solidity: function domainSeparator() view returns(bytes32) +func (_SafeAbi *SafeAbiCaller) DomainSeparator(opts *bind.CallOpts) ([32]byte, error) { + var out []interface{} + err := _SafeAbi.contract.Call(opts, &out, "domainSeparator") + + if err != nil { + return *new([32]byte), err + } + + out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) + + return out0, err + +} + +// DomainSeparator is a free data retrieval call binding the contract method 0xf698da25. +// +// Solidity: function domainSeparator() view returns(bytes32) +func (_SafeAbi *SafeAbiSession) DomainSeparator() ([32]byte, error) { + return _SafeAbi.Contract.DomainSeparator(&_SafeAbi.CallOpts) +} + +// DomainSeparator is a free data retrieval call binding the contract method 0xf698da25. +// +// Solidity: function domainSeparator() view returns(bytes32) +func (_SafeAbi *SafeAbiCallerSession) DomainSeparator() ([32]byte, error) { + return _SafeAbi.Contract.DomainSeparator(&_SafeAbi.CallOpts) +} + +// EncodeTransactionData is a free data retrieval call binding the contract method 0xe86637db. +// +// Solidity: function encodeTransactionData(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce) view returns(bytes) +func (_SafeAbi *SafeAbiCaller) EncodeTransactionData(opts *bind.CallOpts, to common.Address, value *big.Int, data []byte, operation uint8, safeTxGas *big.Int, baseGas *big.Int, gasPrice *big.Int, gasToken common.Address, refundReceiver common.Address, _nonce *big.Int) ([]byte, error) { + var out []interface{} + err := _SafeAbi.contract.Call(opts, &out, "encodeTransactionData", to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce) + + if err != nil { + return *new([]byte), err + } + + out0 := *abi.ConvertType(out[0], new([]byte)).(*[]byte) + + return out0, err + +} + +// EncodeTransactionData is a free data retrieval call binding the contract method 0xe86637db. +// +// Solidity: function encodeTransactionData(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce) view returns(bytes) +func (_SafeAbi *SafeAbiSession) EncodeTransactionData(to common.Address, value *big.Int, data []byte, operation uint8, safeTxGas *big.Int, baseGas *big.Int, gasPrice *big.Int, gasToken common.Address, refundReceiver common.Address, _nonce *big.Int) ([]byte, error) { + return _SafeAbi.Contract.EncodeTransactionData(&_SafeAbi.CallOpts, to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce) +} + +// EncodeTransactionData is a free data retrieval call binding the contract method 0xe86637db. +// +// Solidity: function encodeTransactionData(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce) view returns(bytes) +func (_SafeAbi *SafeAbiCallerSession) EncodeTransactionData(to common.Address, value *big.Int, data []byte, operation uint8, safeTxGas *big.Int, baseGas *big.Int, gasPrice *big.Int, gasToken common.Address, refundReceiver common.Address, _nonce *big.Int) ([]byte, error) { + return _SafeAbi.Contract.EncodeTransactionData(&_SafeAbi.CallOpts, to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce) +} + +// GetChainId is a free data retrieval call binding the contract method 0x3408e470. +// +// Solidity: function getChainId() view returns(uint256) +func (_SafeAbi *SafeAbiCaller) GetChainId(opts *bind.CallOpts) (*big.Int, error) { + var out []interface{} + err := _SafeAbi.contract.Call(opts, &out, "getChainId") + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// GetChainId is a free data retrieval call binding the contract method 0x3408e470. +// +// Solidity: function getChainId() view returns(uint256) +func (_SafeAbi *SafeAbiSession) GetChainId() (*big.Int, error) { + return _SafeAbi.Contract.GetChainId(&_SafeAbi.CallOpts) +} + +// GetChainId is a free data retrieval call binding the contract method 0x3408e470. +// +// Solidity: function getChainId() view returns(uint256) +func (_SafeAbi *SafeAbiCallerSession) GetChainId() (*big.Int, error) { + return _SafeAbi.Contract.GetChainId(&_SafeAbi.CallOpts) +} + +// GetModulesPaginated is a free data retrieval call binding the contract method 0xcc2f8452. +// +// Solidity: function getModulesPaginated(address start, uint256 pageSize) view returns(address[] array, address next) +func (_SafeAbi *SafeAbiCaller) GetModulesPaginated(opts *bind.CallOpts, start common.Address, pageSize *big.Int) (struct { + Array []common.Address + Next common.Address +}, error) { + var out []interface{} + err := _SafeAbi.contract.Call(opts, &out, "getModulesPaginated", start, pageSize) + + outstruct := new(struct { + Array []common.Address + Next common.Address + }) + if err != nil { + return *outstruct, err + } + + outstruct.Array = *abi.ConvertType(out[0], new([]common.Address)).(*[]common.Address) + outstruct.Next = *abi.ConvertType(out[1], new(common.Address)).(*common.Address) + + return *outstruct, err + +} + +// GetModulesPaginated is a free data retrieval call binding the contract method 0xcc2f8452. +// +// Solidity: function getModulesPaginated(address start, uint256 pageSize) view returns(address[] array, address next) +func (_SafeAbi *SafeAbiSession) GetModulesPaginated(start common.Address, pageSize *big.Int) (struct { + Array []common.Address + Next common.Address +}, error) { + return _SafeAbi.Contract.GetModulesPaginated(&_SafeAbi.CallOpts, start, pageSize) +} + +// GetModulesPaginated is a free data retrieval call binding the contract method 0xcc2f8452. +// +// Solidity: function getModulesPaginated(address start, uint256 pageSize) view returns(address[] array, address next) +func (_SafeAbi *SafeAbiCallerSession) GetModulesPaginated(start common.Address, pageSize *big.Int) (struct { + Array []common.Address + Next common.Address +}, error) { + return _SafeAbi.Contract.GetModulesPaginated(&_SafeAbi.CallOpts, start, pageSize) +} + +// GetOwners is a free data retrieval call binding the contract method 0xa0e67e2b. +// +// Solidity: function getOwners() view returns(address[]) +func (_SafeAbi *SafeAbiCaller) GetOwners(opts *bind.CallOpts) ([]common.Address, error) { + var out []interface{} + err := _SafeAbi.contract.Call(opts, &out, "getOwners") + + if err != nil { + return *new([]common.Address), err + } + + out0 := *abi.ConvertType(out[0], new([]common.Address)).(*[]common.Address) + + return out0, err + +} + +// GetOwners is a free data retrieval call binding the contract method 0xa0e67e2b. +// +// Solidity: function getOwners() view returns(address[]) +func (_SafeAbi *SafeAbiSession) GetOwners() ([]common.Address, error) { + return _SafeAbi.Contract.GetOwners(&_SafeAbi.CallOpts) +} + +// GetOwners is a free data retrieval call binding the contract method 0xa0e67e2b. +// +// Solidity: function getOwners() view returns(address[]) +func (_SafeAbi *SafeAbiCallerSession) GetOwners() ([]common.Address, error) { + return _SafeAbi.Contract.GetOwners(&_SafeAbi.CallOpts) +} + +// GetStorageAt is a free data retrieval call binding the contract method 0x5624b25b. +// +// Solidity: function getStorageAt(uint256 offset, uint256 length) view returns(bytes) +func (_SafeAbi *SafeAbiCaller) GetStorageAt(opts *bind.CallOpts, offset *big.Int, length *big.Int) ([]byte, error) { + var out []interface{} + err := _SafeAbi.contract.Call(opts, &out, "getStorageAt", offset, length) + + if err != nil { + return *new([]byte), err + } + + out0 := *abi.ConvertType(out[0], new([]byte)).(*[]byte) + + return out0, err + +} + +// GetStorageAt is a free data retrieval call binding the contract method 0x5624b25b. +// +// Solidity: function getStorageAt(uint256 offset, uint256 length) view returns(bytes) +func (_SafeAbi *SafeAbiSession) GetStorageAt(offset *big.Int, length *big.Int) ([]byte, error) { + return _SafeAbi.Contract.GetStorageAt(&_SafeAbi.CallOpts, offset, length) +} + +// GetStorageAt is a free data retrieval call binding the contract method 0x5624b25b. +// +// Solidity: function getStorageAt(uint256 offset, uint256 length) view returns(bytes) +func (_SafeAbi *SafeAbiCallerSession) GetStorageAt(offset *big.Int, length *big.Int) ([]byte, error) { + return _SafeAbi.Contract.GetStorageAt(&_SafeAbi.CallOpts, offset, length) +} + +// GetThreshold is a free data retrieval call binding the contract method 0xe75235b8. +// +// Solidity: function getThreshold() view returns(uint256) +func (_SafeAbi *SafeAbiCaller) GetThreshold(opts *bind.CallOpts) (*big.Int, error) { + var out []interface{} + err := _SafeAbi.contract.Call(opts, &out, "getThreshold") + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// GetThreshold is a free data retrieval call binding the contract method 0xe75235b8. +// +// Solidity: function getThreshold() view returns(uint256) +func (_SafeAbi *SafeAbiSession) GetThreshold() (*big.Int, error) { + return _SafeAbi.Contract.GetThreshold(&_SafeAbi.CallOpts) +} + +// GetThreshold is a free data retrieval call binding the contract method 0xe75235b8. +// +// Solidity: function getThreshold() view returns(uint256) +func (_SafeAbi *SafeAbiCallerSession) GetThreshold() (*big.Int, error) { + return _SafeAbi.Contract.GetThreshold(&_SafeAbi.CallOpts) +} + +// GetTransactionHash is a free data retrieval call binding the contract method 0xd8d11f78. +// +// Solidity: function getTransactionHash(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce) view returns(bytes32) +func (_SafeAbi *SafeAbiCaller) GetTransactionHash(opts *bind.CallOpts, to common.Address, value *big.Int, data []byte, operation uint8, safeTxGas *big.Int, baseGas *big.Int, gasPrice *big.Int, gasToken common.Address, refundReceiver common.Address, _nonce *big.Int) ([32]byte, error) { + var out []interface{} + err := _SafeAbi.contract.Call(opts, &out, "getTransactionHash", to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce) + + if err != nil { + return *new([32]byte), err + } + + out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) + + return out0, err + +} + +// GetTransactionHash is a free data retrieval call binding the contract method 0xd8d11f78. +// +// Solidity: function getTransactionHash(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce) view returns(bytes32) +func (_SafeAbi *SafeAbiSession) GetTransactionHash(to common.Address, value *big.Int, data []byte, operation uint8, safeTxGas *big.Int, baseGas *big.Int, gasPrice *big.Int, gasToken common.Address, refundReceiver common.Address, _nonce *big.Int) ([32]byte, error) { + return _SafeAbi.Contract.GetTransactionHash(&_SafeAbi.CallOpts, to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce) +} + +// GetTransactionHash is a free data retrieval call binding the contract method 0xd8d11f78. +// +// Solidity: function getTransactionHash(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce) view returns(bytes32) +func (_SafeAbi *SafeAbiCallerSession) GetTransactionHash(to common.Address, value *big.Int, data []byte, operation uint8, safeTxGas *big.Int, baseGas *big.Int, gasPrice *big.Int, gasToken common.Address, refundReceiver common.Address, _nonce *big.Int) ([32]byte, error) { + return _SafeAbi.Contract.GetTransactionHash(&_SafeAbi.CallOpts, to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce) +} + +// IsModuleEnabled is a free data retrieval call binding the contract method 0x2d9ad53d. +// +// Solidity: function isModuleEnabled(address module) view returns(bool) +func (_SafeAbi *SafeAbiCaller) IsModuleEnabled(opts *bind.CallOpts, module common.Address) (bool, error) { + var out []interface{} + err := _SafeAbi.contract.Call(opts, &out, "isModuleEnabled", module) + + if err != nil { + return *new(bool), err + } + + out0 := *abi.ConvertType(out[0], new(bool)).(*bool) + + return out0, err + +} + +// IsModuleEnabled is a free data retrieval call binding the contract method 0x2d9ad53d. +// +// Solidity: function isModuleEnabled(address module) view returns(bool) +func (_SafeAbi *SafeAbiSession) IsModuleEnabled(module common.Address) (bool, error) { + return _SafeAbi.Contract.IsModuleEnabled(&_SafeAbi.CallOpts, module) +} + +// IsModuleEnabled is a free data retrieval call binding the contract method 0x2d9ad53d. +// +// Solidity: function isModuleEnabled(address module) view returns(bool) +func (_SafeAbi *SafeAbiCallerSession) IsModuleEnabled(module common.Address) (bool, error) { + return _SafeAbi.Contract.IsModuleEnabled(&_SafeAbi.CallOpts, module) +} + +// IsOwner is a free data retrieval call binding the contract method 0x2f54bf6e. +// +// Solidity: function isOwner(address owner) view returns(bool) +func (_SafeAbi *SafeAbiCaller) IsOwner(opts *bind.CallOpts, owner common.Address) (bool, error) { + var out []interface{} + err := _SafeAbi.contract.Call(opts, &out, "isOwner", owner) + + if err != nil { + return *new(bool), err + } + + out0 := *abi.ConvertType(out[0], new(bool)).(*bool) + + return out0, err + +} + +// IsOwner is a free data retrieval call binding the contract method 0x2f54bf6e. +// +// Solidity: function isOwner(address owner) view returns(bool) +func (_SafeAbi *SafeAbiSession) IsOwner(owner common.Address) (bool, error) { + return _SafeAbi.Contract.IsOwner(&_SafeAbi.CallOpts, owner) +} + +// IsOwner is a free data retrieval call binding the contract method 0x2f54bf6e. +// +// Solidity: function isOwner(address owner) view returns(bool) +func (_SafeAbi *SafeAbiCallerSession) IsOwner(owner common.Address) (bool, error) { + return _SafeAbi.Contract.IsOwner(&_SafeAbi.CallOpts, owner) +} + +// Nonce is a free data retrieval call binding the contract method 0xaffed0e0. +// +// Solidity: function nonce() view returns(uint256) +func (_SafeAbi *SafeAbiCaller) Nonce(opts *bind.CallOpts) (*big.Int, error) { + var out []interface{} + err := _SafeAbi.contract.Call(opts, &out, "nonce") + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// Nonce is a free data retrieval call binding the contract method 0xaffed0e0. +// +// Solidity: function nonce() view returns(uint256) +func (_SafeAbi *SafeAbiSession) Nonce() (*big.Int, error) { + return _SafeAbi.Contract.Nonce(&_SafeAbi.CallOpts) +} + +// Nonce is a free data retrieval call binding the contract method 0xaffed0e0. +// +// Solidity: function nonce() view returns(uint256) +func (_SafeAbi *SafeAbiCallerSession) Nonce() (*big.Int, error) { + return _SafeAbi.Contract.Nonce(&_SafeAbi.CallOpts) +} + +// SignedMessages is a free data retrieval call binding the contract method 0x5ae6bd37. +// +// Solidity: function signedMessages(bytes32 ) view returns(uint256) +func (_SafeAbi *SafeAbiCaller) SignedMessages(opts *bind.CallOpts, arg0 [32]byte) (*big.Int, error) { + var out []interface{} + err := _SafeAbi.contract.Call(opts, &out, "signedMessages", arg0) + + if err != nil { + return *new(*big.Int), err + } + + out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) + + return out0, err + +} + +// SignedMessages is a free data retrieval call binding the contract method 0x5ae6bd37. +// +// Solidity: function signedMessages(bytes32 ) view returns(uint256) +func (_SafeAbi *SafeAbiSession) SignedMessages(arg0 [32]byte) (*big.Int, error) { + return _SafeAbi.Contract.SignedMessages(&_SafeAbi.CallOpts, arg0) +} + +// SignedMessages is a free data retrieval call binding the contract method 0x5ae6bd37. +// +// Solidity: function signedMessages(bytes32 ) view returns(uint256) +func (_SafeAbi *SafeAbiCallerSession) SignedMessages(arg0 [32]byte) (*big.Int, error) { + return _SafeAbi.Contract.SignedMessages(&_SafeAbi.CallOpts, arg0) +} + +// AddOwnerWithThreshold is a paid mutator transaction binding the contract method 0x0d582f13. +// +// Solidity: function addOwnerWithThreshold(address owner, uint256 _threshold) returns() +func (_SafeAbi *SafeAbiTransactor) AddOwnerWithThreshold(opts *bind.TransactOpts, owner common.Address, _threshold *big.Int) (*types.Transaction, error) { + return _SafeAbi.contract.Transact(opts, "addOwnerWithThreshold", owner, _threshold) +} + +// AddOwnerWithThreshold is a paid mutator transaction binding the contract method 0x0d582f13. +// +// Solidity: function addOwnerWithThreshold(address owner, uint256 _threshold) returns() +func (_SafeAbi *SafeAbiSession) AddOwnerWithThreshold(owner common.Address, _threshold *big.Int) (*types.Transaction, error) { + return _SafeAbi.Contract.AddOwnerWithThreshold(&_SafeAbi.TransactOpts, owner, _threshold) +} + +// AddOwnerWithThreshold is a paid mutator transaction binding the contract method 0x0d582f13. +// +// Solidity: function addOwnerWithThreshold(address owner, uint256 _threshold) returns() +func (_SafeAbi *SafeAbiTransactorSession) AddOwnerWithThreshold(owner common.Address, _threshold *big.Int) (*types.Transaction, error) { + return _SafeAbi.Contract.AddOwnerWithThreshold(&_SafeAbi.TransactOpts, owner, _threshold) +} + +// ApproveHash is a paid mutator transaction binding the contract method 0xd4d9bdcd. +// +// Solidity: function approveHash(bytes32 hashToApprove) returns() +func (_SafeAbi *SafeAbiTransactor) ApproveHash(opts *bind.TransactOpts, hashToApprove [32]byte) (*types.Transaction, error) { + return _SafeAbi.contract.Transact(opts, "approveHash", hashToApprove) +} + +// ApproveHash is a paid mutator transaction binding the contract method 0xd4d9bdcd. +// +// Solidity: function approveHash(bytes32 hashToApprove) returns() +func (_SafeAbi *SafeAbiSession) ApproveHash(hashToApprove [32]byte) (*types.Transaction, error) { + return _SafeAbi.Contract.ApproveHash(&_SafeAbi.TransactOpts, hashToApprove) +} + +// ApproveHash is a paid mutator transaction binding the contract method 0xd4d9bdcd. +// +// Solidity: function approveHash(bytes32 hashToApprove) returns() +func (_SafeAbi *SafeAbiTransactorSession) ApproveHash(hashToApprove [32]byte) (*types.Transaction, error) { + return _SafeAbi.Contract.ApproveHash(&_SafeAbi.TransactOpts, hashToApprove) +} + +// ChangeThreshold is a paid mutator transaction binding the contract method 0x694e80c3. +// +// Solidity: function changeThreshold(uint256 _threshold) returns() +func (_SafeAbi *SafeAbiTransactor) ChangeThreshold(opts *bind.TransactOpts, _threshold *big.Int) (*types.Transaction, error) { + return _SafeAbi.contract.Transact(opts, "changeThreshold", _threshold) +} + +// ChangeThreshold is a paid mutator transaction binding the contract method 0x694e80c3. +// +// Solidity: function changeThreshold(uint256 _threshold) returns() +func (_SafeAbi *SafeAbiSession) ChangeThreshold(_threshold *big.Int) (*types.Transaction, error) { + return _SafeAbi.Contract.ChangeThreshold(&_SafeAbi.TransactOpts, _threshold) +} + +// ChangeThreshold is a paid mutator transaction binding the contract method 0x694e80c3. +// +// Solidity: function changeThreshold(uint256 _threshold) returns() +func (_SafeAbi *SafeAbiTransactorSession) ChangeThreshold(_threshold *big.Int) (*types.Transaction, error) { + return _SafeAbi.Contract.ChangeThreshold(&_SafeAbi.TransactOpts, _threshold) +} + +// DisableModule is a paid mutator transaction binding the contract method 0xe009cfde. +// +// Solidity: function disableModule(address prevModule, address module) returns() +func (_SafeAbi *SafeAbiTransactor) DisableModule(opts *bind.TransactOpts, prevModule common.Address, module common.Address) (*types.Transaction, error) { + return _SafeAbi.contract.Transact(opts, "disableModule", prevModule, module) +} + +// DisableModule is a paid mutator transaction binding the contract method 0xe009cfde. +// +// Solidity: function disableModule(address prevModule, address module) returns() +func (_SafeAbi *SafeAbiSession) DisableModule(prevModule common.Address, module common.Address) (*types.Transaction, error) { + return _SafeAbi.Contract.DisableModule(&_SafeAbi.TransactOpts, prevModule, module) +} + +// DisableModule is a paid mutator transaction binding the contract method 0xe009cfde. +// +// Solidity: function disableModule(address prevModule, address module) returns() +func (_SafeAbi *SafeAbiTransactorSession) DisableModule(prevModule common.Address, module common.Address) (*types.Transaction, error) { + return _SafeAbi.Contract.DisableModule(&_SafeAbi.TransactOpts, prevModule, module) +} + +// EnableModule is a paid mutator transaction binding the contract method 0x610b5925. +// +// Solidity: function enableModule(address module) returns() +func (_SafeAbi *SafeAbiTransactor) EnableModule(opts *bind.TransactOpts, module common.Address) (*types.Transaction, error) { + return _SafeAbi.contract.Transact(opts, "enableModule", module) +} + +// EnableModule is a paid mutator transaction binding the contract method 0x610b5925. +// +// Solidity: function enableModule(address module) returns() +func (_SafeAbi *SafeAbiSession) EnableModule(module common.Address) (*types.Transaction, error) { + return _SafeAbi.Contract.EnableModule(&_SafeAbi.TransactOpts, module) +} + +// EnableModule is a paid mutator transaction binding the contract method 0x610b5925. +// +// Solidity: function enableModule(address module) returns() +func (_SafeAbi *SafeAbiTransactorSession) EnableModule(module common.Address) (*types.Transaction, error) { + return _SafeAbi.Contract.EnableModule(&_SafeAbi.TransactOpts, module) +} + +// ExecTransaction is a paid mutator transaction binding the contract method 0x6a761202. +// +// Solidity: function execTransaction(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, bytes signatures) payable returns(bool) +func (_SafeAbi *SafeAbiTransactor) ExecTransaction(opts *bind.TransactOpts, to common.Address, value *big.Int, data []byte, operation uint8, safeTxGas *big.Int, baseGas *big.Int, gasPrice *big.Int, gasToken common.Address, refundReceiver common.Address, signatures []byte) (*types.Transaction, error) { + return _SafeAbi.contract.Transact(opts, "execTransaction", to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, signatures) +} + +// ExecTransaction is a paid mutator transaction binding the contract method 0x6a761202. +// +// Solidity: function execTransaction(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, bytes signatures) payable returns(bool) +func (_SafeAbi *SafeAbiSession) ExecTransaction(to common.Address, value *big.Int, data []byte, operation uint8, safeTxGas *big.Int, baseGas *big.Int, gasPrice *big.Int, gasToken common.Address, refundReceiver common.Address, signatures []byte) (*types.Transaction, error) { + return _SafeAbi.Contract.ExecTransaction(&_SafeAbi.TransactOpts, to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, signatures) +} + +// ExecTransaction is a paid mutator transaction binding the contract method 0x6a761202. +// +// Solidity: function execTransaction(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, bytes signatures) payable returns(bool) +func (_SafeAbi *SafeAbiTransactorSession) ExecTransaction(to common.Address, value *big.Int, data []byte, operation uint8, safeTxGas *big.Int, baseGas *big.Int, gasPrice *big.Int, gasToken common.Address, refundReceiver common.Address, signatures []byte) (*types.Transaction, error) { + return _SafeAbi.Contract.ExecTransaction(&_SafeAbi.TransactOpts, to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, signatures) +} + +// ExecTransactionFromModule is a paid mutator transaction binding the contract method 0x468721a7. +// +// Solidity: function execTransactionFromModule(address to, uint256 value, bytes data, uint8 operation) returns(bool success) +func (_SafeAbi *SafeAbiTransactor) ExecTransactionFromModule(opts *bind.TransactOpts, to common.Address, value *big.Int, data []byte, operation uint8) (*types.Transaction, error) { + return _SafeAbi.contract.Transact(opts, "execTransactionFromModule", to, value, data, operation) +} + +// ExecTransactionFromModule is a paid mutator transaction binding the contract method 0x468721a7. +// +// Solidity: function execTransactionFromModule(address to, uint256 value, bytes data, uint8 operation) returns(bool success) +func (_SafeAbi *SafeAbiSession) ExecTransactionFromModule(to common.Address, value *big.Int, data []byte, operation uint8) (*types.Transaction, error) { + return _SafeAbi.Contract.ExecTransactionFromModule(&_SafeAbi.TransactOpts, to, value, data, operation) +} + +// ExecTransactionFromModule is a paid mutator transaction binding the contract method 0x468721a7. +// +// Solidity: function execTransactionFromModule(address to, uint256 value, bytes data, uint8 operation) returns(bool success) +func (_SafeAbi *SafeAbiTransactorSession) ExecTransactionFromModule(to common.Address, value *big.Int, data []byte, operation uint8) (*types.Transaction, error) { + return _SafeAbi.Contract.ExecTransactionFromModule(&_SafeAbi.TransactOpts, to, value, data, operation) +} + +// ExecTransactionFromModuleReturnData is a paid mutator transaction binding the contract method 0x5229073f. +// +// Solidity: function execTransactionFromModuleReturnData(address to, uint256 value, bytes data, uint8 operation) returns(bool success, bytes returnData) +func (_SafeAbi *SafeAbiTransactor) ExecTransactionFromModuleReturnData(opts *bind.TransactOpts, to common.Address, value *big.Int, data []byte, operation uint8) (*types.Transaction, error) { + return _SafeAbi.contract.Transact(opts, "execTransactionFromModuleReturnData", to, value, data, operation) +} + +// ExecTransactionFromModuleReturnData is a paid mutator transaction binding the contract method 0x5229073f. +// +// Solidity: function execTransactionFromModuleReturnData(address to, uint256 value, bytes data, uint8 operation) returns(bool success, bytes returnData) +func (_SafeAbi *SafeAbiSession) ExecTransactionFromModuleReturnData(to common.Address, value *big.Int, data []byte, operation uint8) (*types.Transaction, error) { + return _SafeAbi.Contract.ExecTransactionFromModuleReturnData(&_SafeAbi.TransactOpts, to, value, data, operation) +} + +// ExecTransactionFromModuleReturnData is a paid mutator transaction binding the contract method 0x5229073f. +// +// Solidity: function execTransactionFromModuleReturnData(address to, uint256 value, bytes data, uint8 operation) returns(bool success, bytes returnData) +func (_SafeAbi *SafeAbiTransactorSession) ExecTransactionFromModuleReturnData(to common.Address, value *big.Int, data []byte, operation uint8) (*types.Transaction, error) { + return _SafeAbi.Contract.ExecTransactionFromModuleReturnData(&_SafeAbi.TransactOpts, to, value, data, operation) +} + +// RemoveOwner is a paid mutator transaction binding the contract method 0xf8dc5dd9. +// +// Solidity: function removeOwner(address prevOwner, address owner, uint256 _threshold) returns() +func (_SafeAbi *SafeAbiTransactor) RemoveOwner(opts *bind.TransactOpts, prevOwner common.Address, owner common.Address, _threshold *big.Int) (*types.Transaction, error) { + return _SafeAbi.contract.Transact(opts, "removeOwner", prevOwner, owner, _threshold) +} + +// RemoveOwner is a paid mutator transaction binding the contract method 0xf8dc5dd9. +// +// Solidity: function removeOwner(address prevOwner, address owner, uint256 _threshold) returns() +func (_SafeAbi *SafeAbiSession) RemoveOwner(prevOwner common.Address, owner common.Address, _threshold *big.Int) (*types.Transaction, error) { + return _SafeAbi.Contract.RemoveOwner(&_SafeAbi.TransactOpts, prevOwner, owner, _threshold) +} + +// RemoveOwner is a paid mutator transaction binding the contract method 0xf8dc5dd9. +// +// Solidity: function removeOwner(address prevOwner, address owner, uint256 _threshold) returns() +func (_SafeAbi *SafeAbiTransactorSession) RemoveOwner(prevOwner common.Address, owner common.Address, _threshold *big.Int) (*types.Transaction, error) { + return _SafeAbi.Contract.RemoveOwner(&_SafeAbi.TransactOpts, prevOwner, owner, _threshold) +} + +// RequiredTxGas is a paid mutator transaction binding the contract method 0xc4ca3a9c. +// +// Solidity: function requiredTxGas(address to, uint256 value, bytes data, uint8 operation) returns(uint256) +func (_SafeAbi *SafeAbiTransactor) RequiredTxGas(opts *bind.TransactOpts, to common.Address, value *big.Int, data []byte, operation uint8) (*types.Transaction, error) { + return _SafeAbi.contract.Transact(opts, "requiredTxGas", to, value, data, operation) +} + +// RequiredTxGas is a paid mutator transaction binding the contract method 0xc4ca3a9c. +// +// Solidity: function requiredTxGas(address to, uint256 value, bytes data, uint8 operation) returns(uint256) +func (_SafeAbi *SafeAbiSession) RequiredTxGas(to common.Address, value *big.Int, data []byte, operation uint8) (*types.Transaction, error) { + return _SafeAbi.Contract.RequiredTxGas(&_SafeAbi.TransactOpts, to, value, data, operation) +} + +// RequiredTxGas is a paid mutator transaction binding the contract method 0xc4ca3a9c. +// +// Solidity: function requiredTxGas(address to, uint256 value, bytes data, uint8 operation) returns(uint256) +func (_SafeAbi *SafeAbiTransactorSession) RequiredTxGas(to common.Address, value *big.Int, data []byte, operation uint8) (*types.Transaction, error) { + return _SafeAbi.Contract.RequiredTxGas(&_SafeAbi.TransactOpts, to, value, data, operation) +} + +// SetFallbackHandler is a paid mutator transaction binding the contract method 0xf08a0323. +// +// Solidity: function setFallbackHandler(address handler) returns() +func (_SafeAbi *SafeAbiTransactor) SetFallbackHandler(opts *bind.TransactOpts, handler common.Address) (*types.Transaction, error) { + return _SafeAbi.contract.Transact(opts, "setFallbackHandler", handler) +} + +// SetFallbackHandler is a paid mutator transaction binding the contract method 0xf08a0323. +// +// Solidity: function setFallbackHandler(address handler) returns() +func (_SafeAbi *SafeAbiSession) SetFallbackHandler(handler common.Address) (*types.Transaction, error) { + return _SafeAbi.Contract.SetFallbackHandler(&_SafeAbi.TransactOpts, handler) +} + +// SetFallbackHandler is a paid mutator transaction binding the contract method 0xf08a0323. +// +// Solidity: function setFallbackHandler(address handler) returns() +func (_SafeAbi *SafeAbiTransactorSession) SetFallbackHandler(handler common.Address) (*types.Transaction, error) { + return _SafeAbi.Contract.SetFallbackHandler(&_SafeAbi.TransactOpts, handler) +} + +// SetGuard is a paid mutator transaction binding the contract method 0xe19a9dd9. +// +// Solidity: function setGuard(address guard) returns() +func (_SafeAbi *SafeAbiTransactor) SetGuard(opts *bind.TransactOpts, guard common.Address) (*types.Transaction, error) { + return _SafeAbi.contract.Transact(opts, "setGuard", guard) +} + +// SetGuard is a paid mutator transaction binding the contract method 0xe19a9dd9. +// +// Solidity: function setGuard(address guard) returns() +func (_SafeAbi *SafeAbiSession) SetGuard(guard common.Address) (*types.Transaction, error) { + return _SafeAbi.Contract.SetGuard(&_SafeAbi.TransactOpts, guard) +} + +// SetGuard is a paid mutator transaction binding the contract method 0xe19a9dd9. +// +// Solidity: function setGuard(address guard) returns() +func (_SafeAbi *SafeAbiTransactorSession) SetGuard(guard common.Address) (*types.Transaction, error) { + return _SafeAbi.Contract.SetGuard(&_SafeAbi.TransactOpts, guard) +} + +// Setup is a paid mutator transaction binding the contract method 0xb63e800d. +// +// Solidity: function setup(address[] _owners, uint256 _threshold, address to, bytes data, address fallbackHandler, address paymentToken, uint256 payment, address paymentReceiver) returns() +func (_SafeAbi *SafeAbiTransactor) Setup(opts *bind.TransactOpts, _owners []common.Address, _threshold *big.Int, to common.Address, data []byte, fallbackHandler common.Address, paymentToken common.Address, payment *big.Int, paymentReceiver common.Address) (*types.Transaction, error) { + return _SafeAbi.contract.Transact(opts, "setup", _owners, _threshold, to, data, fallbackHandler, paymentToken, payment, paymentReceiver) +} + +// Setup is a paid mutator transaction binding the contract method 0xb63e800d. +// +// Solidity: function setup(address[] _owners, uint256 _threshold, address to, bytes data, address fallbackHandler, address paymentToken, uint256 payment, address paymentReceiver) returns() +func (_SafeAbi *SafeAbiSession) Setup(_owners []common.Address, _threshold *big.Int, to common.Address, data []byte, fallbackHandler common.Address, paymentToken common.Address, payment *big.Int, paymentReceiver common.Address) (*types.Transaction, error) { + return _SafeAbi.Contract.Setup(&_SafeAbi.TransactOpts, _owners, _threshold, to, data, fallbackHandler, paymentToken, payment, paymentReceiver) +} + +// Setup is a paid mutator transaction binding the contract method 0xb63e800d. +// +// Solidity: function setup(address[] _owners, uint256 _threshold, address to, bytes data, address fallbackHandler, address paymentToken, uint256 payment, address paymentReceiver) returns() +func (_SafeAbi *SafeAbiTransactorSession) Setup(_owners []common.Address, _threshold *big.Int, to common.Address, data []byte, fallbackHandler common.Address, paymentToken common.Address, payment *big.Int, paymentReceiver common.Address) (*types.Transaction, error) { + return _SafeAbi.Contract.Setup(&_SafeAbi.TransactOpts, _owners, _threshold, to, data, fallbackHandler, paymentToken, payment, paymentReceiver) +} + +// SimulateAndRevert is a paid mutator transaction binding the contract method 0xb4faba09. +// +// Solidity: function simulateAndRevert(address targetContract, bytes calldataPayload) returns() +func (_SafeAbi *SafeAbiTransactor) SimulateAndRevert(opts *bind.TransactOpts, targetContract common.Address, calldataPayload []byte) (*types.Transaction, error) { + return _SafeAbi.contract.Transact(opts, "simulateAndRevert", targetContract, calldataPayload) +} + +// SimulateAndRevert is a paid mutator transaction binding the contract method 0xb4faba09. +// +// Solidity: function simulateAndRevert(address targetContract, bytes calldataPayload) returns() +func (_SafeAbi *SafeAbiSession) SimulateAndRevert(targetContract common.Address, calldataPayload []byte) (*types.Transaction, error) { + return _SafeAbi.Contract.SimulateAndRevert(&_SafeAbi.TransactOpts, targetContract, calldataPayload) +} + +// SimulateAndRevert is a paid mutator transaction binding the contract method 0xb4faba09. +// +// Solidity: function simulateAndRevert(address targetContract, bytes calldataPayload) returns() +func (_SafeAbi *SafeAbiTransactorSession) SimulateAndRevert(targetContract common.Address, calldataPayload []byte) (*types.Transaction, error) { + return _SafeAbi.Contract.SimulateAndRevert(&_SafeAbi.TransactOpts, targetContract, calldataPayload) +} + +// SwapOwner is a paid mutator transaction binding the contract method 0xe318b52b. +// +// Solidity: function swapOwner(address prevOwner, address oldOwner, address newOwner) returns() +func (_SafeAbi *SafeAbiTransactor) SwapOwner(opts *bind.TransactOpts, prevOwner common.Address, oldOwner common.Address, newOwner common.Address) (*types.Transaction, error) { + return _SafeAbi.contract.Transact(opts, "swapOwner", prevOwner, oldOwner, newOwner) +} + +// SwapOwner is a paid mutator transaction binding the contract method 0xe318b52b. +// +// Solidity: function swapOwner(address prevOwner, address oldOwner, address newOwner) returns() +func (_SafeAbi *SafeAbiSession) SwapOwner(prevOwner common.Address, oldOwner common.Address, newOwner common.Address) (*types.Transaction, error) { + return _SafeAbi.Contract.SwapOwner(&_SafeAbi.TransactOpts, prevOwner, oldOwner, newOwner) +} + +// SwapOwner is a paid mutator transaction binding the contract method 0xe318b52b. +// +// Solidity: function swapOwner(address prevOwner, address oldOwner, address newOwner) returns() +func (_SafeAbi *SafeAbiTransactorSession) SwapOwner(prevOwner common.Address, oldOwner common.Address, newOwner common.Address) (*types.Transaction, error) { + return _SafeAbi.Contract.SwapOwner(&_SafeAbi.TransactOpts, prevOwner, oldOwner, newOwner) +} + +// Fallback is a paid mutator transaction binding the contract fallback function. +// +// Solidity: fallback() returns() +func (_SafeAbi *SafeAbiTransactor) Fallback(opts *bind.TransactOpts, calldata []byte) (*types.Transaction, error) { + return _SafeAbi.contract.RawTransact(opts, calldata) +} + +// Fallback is a paid mutator transaction binding the contract fallback function. +// +// Solidity: fallback() returns() +func (_SafeAbi *SafeAbiSession) Fallback(calldata []byte) (*types.Transaction, error) { + return _SafeAbi.Contract.Fallback(&_SafeAbi.TransactOpts, calldata) +} + +// Fallback is a paid mutator transaction binding the contract fallback function. +// +// Solidity: fallback() returns() +func (_SafeAbi *SafeAbiTransactorSession) Fallback(calldata []byte) (*types.Transaction, error) { + return _SafeAbi.Contract.Fallback(&_SafeAbi.TransactOpts, calldata) +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_SafeAbi *SafeAbiTransactor) Receive(opts *bind.TransactOpts) (*types.Transaction, error) { + return _SafeAbi.contract.RawTransact(opts, nil) // calldata is disallowed for receive function +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_SafeAbi *SafeAbiSession) Receive() (*types.Transaction, error) { + return _SafeAbi.Contract.Receive(&_SafeAbi.TransactOpts) +} + +// Receive is a paid mutator transaction binding the contract receive function. +// +// Solidity: receive() payable returns() +func (_SafeAbi *SafeAbiTransactorSession) Receive() (*types.Transaction, error) { + return _SafeAbi.Contract.Receive(&_SafeAbi.TransactOpts) +} + +// SafeAbiAddedOwnerIterator is returned from FilterAddedOwner and is used to iterate over the raw logs and unpacked data for AddedOwner events raised by the SafeAbi contract. +type SafeAbiAddedOwnerIterator struct { + Event *SafeAbiAddedOwner // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *SafeAbiAddedOwnerIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(SafeAbiAddedOwner) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(SafeAbiAddedOwner) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *SafeAbiAddedOwnerIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *SafeAbiAddedOwnerIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// SafeAbiAddedOwner represents a AddedOwner event raised by the SafeAbi contract. +type SafeAbiAddedOwner struct { + Owner common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterAddedOwner is a free log retrieval operation binding the contract event 0x9465fa0c962cc76958e6373a993326400c1c94f8be2fe3a952adfa7f60b2ea26. +// +// Solidity: event AddedOwner(address owner) +func (_SafeAbi *SafeAbiFilterer) FilterAddedOwner(opts *bind.FilterOpts) (*SafeAbiAddedOwnerIterator, error) { + + logs, sub, err := _SafeAbi.contract.FilterLogs(opts, "AddedOwner") + if err != nil { + return nil, err + } + return &SafeAbiAddedOwnerIterator{contract: _SafeAbi.contract, event: "AddedOwner", logs: logs, sub: sub}, nil +} + +// WatchAddedOwner is a free log subscription operation binding the contract event 0x9465fa0c962cc76958e6373a993326400c1c94f8be2fe3a952adfa7f60b2ea26. +// +// Solidity: event AddedOwner(address owner) +func (_SafeAbi *SafeAbiFilterer) WatchAddedOwner(opts *bind.WatchOpts, sink chan<- *SafeAbiAddedOwner) (event.Subscription, error) { + + logs, sub, err := _SafeAbi.contract.WatchLogs(opts, "AddedOwner") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(SafeAbiAddedOwner) + if err := _SafeAbi.contract.UnpackLog(event, "AddedOwner", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseAddedOwner is a log parse operation binding the contract event 0x9465fa0c962cc76958e6373a993326400c1c94f8be2fe3a952adfa7f60b2ea26. +// +// Solidity: event AddedOwner(address owner) +func (_SafeAbi *SafeAbiFilterer) ParseAddedOwner(log types.Log) (*SafeAbiAddedOwner, error) { + event := new(SafeAbiAddedOwner) + if err := _SafeAbi.contract.UnpackLog(event, "AddedOwner", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// SafeAbiApproveHashIterator is returned from FilterApproveHash and is used to iterate over the raw logs and unpacked data for ApproveHash events raised by the SafeAbi contract. +type SafeAbiApproveHashIterator struct { + Event *SafeAbiApproveHash // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *SafeAbiApproveHashIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(SafeAbiApproveHash) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(SafeAbiApproveHash) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *SafeAbiApproveHashIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *SafeAbiApproveHashIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// SafeAbiApproveHash represents a ApproveHash event raised by the SafeAbi contract. +type SafeAbiApproveHash struct { + ApprovedHash [32]byte + Owner common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterApproveHash is a free log retrieval operation binding the contract event 0xf2a0eb156472d1440255b0d7c1e19cc07115d1051fe605b0dce69acfec884d9c. +// +// Solidity: event ApproveHash(bytes32 indexed approvedHash, address indexed owner) +func (_SafeAbi *SafeAbiFilterer) FilterApproveHash(opts *bind.FilterOpts, approvedHash [][32]byte, owner []common.Address) (*SafeAbiApproveHashIterator, error) { + + var approvedHashRule []interface{} + for _, approvedHashItem := range approvedHash { + approvedHashRule = append(approvedHashRule, approvedHashItem) + } + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + + logs, sub, err := _SafeAbi.contract.FilterLogs(opts, "ApproveHash", approvedHashRule, ownerRule) + if err != nil { + return nil, err + } + return &SafeAbiApproveHashIterator{contract: _SafeAbi.contract, event: "ApproveHash", logs: logs, sub: sub}, nil +} + +// WatchApproveHash is a free log subscription operation binding the contract event 0xf2a0eb156472d1440255b0d7c1e19cc07115d1051fe605b0dce69acfec884d9c. +// +// Solidity: event ApproveHash(bytes32 indexed approvedHash, address indexed owner) +func (_SafeAbi *SafeAbiFilterer) WatchApproveHash(opts *bind.WatchOpts, sink chan<- *SafeAbiApproveHash, approvedHash [][32]byte, owner []common.Address) (event.Subscription, error) { + + var approvedHashRule []interface{} + for _, approvedHashItem := range approvedHash { + approvedHashRule = append(approvedHashRule, approvedHashItem) + } + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + + logs, sub, err := _SafeAbi.contract.WatchLogs(opts, "ApproveHash", approvedHashRule, ownerRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(SafeAbiApproveHash) + if err := _SafeAbi.contract.UnpackLog(event, "ApproveHash", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseApproveHash is a log parse operation binding the contract event 0xf2a0eb156472d1440255b0d7c1e19cc07115d1051fe605b0dce69acfec884d9c. +// +// Solidity: event ApproveHash(bytes32 indexed approvedHash, address indexed owner) +func (_SafeAbi *SafeAbiFilterer) ParseApproveHash(log types.Log) (*SafeAbiApproveHash, error) { + event := new(SafeAbiApproveHash) + if err := _SafeAbi.contract.UnpackLog(event, "ApproveHash", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// SafeAbiChangedFallbackHandlerIterator is returned from FilterChangedFallbackHandler and is used to iterate over the raw logs and unpacked data for ChangedFallbackHandler events raised by the SafeAbi contract. +type SafeAbiChangedFallbackHandlerIterator struct { + Event *SafeAbiChangedFallbackHandler // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *SafeAbiChangedFallbackHandlerIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(SafeAbiChangedFallbackHandler) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(SafeAbiChangedFallbackHandler) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *SafeAbiChangedFallbackHandlerIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *SafeAbiChangedFallbackHandlerIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// SafeAbiChangedFallbackHandler represents a ChangedFallbackHandler event raised by the SafeAbi contract. +type SafeAbiChangedFallbackHandler struct { + Handler common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterChangedFallbackHandler is a free log retrieval operation binding the contract event 0x5ac6c46c93c8d0e53714ba3b53db3e7c046da994313d7ed0d192028bc7c228b0. +// +// Solidity: event ChangedFallbackHandler(address handler) +func (_SafeAbi *SafeAbiFilterer) FilterChangedFallbackHandler(opts *bind.FilterOpts) (*SafeAbiChangedFallbackHandlerIterator, error) { + + logs, sub, err := _SafeAbi.contract.FilterLogs(opts, "ChangedFallbackHandler") + if err != nil { + return nil, err + } + return &SafeAbiChangedFallbackHandlerIterator{contract: _SafeAbi.contract, event: "ChangedFallbackHandler", logs: logs, sub: sub}, nil +} + +// WatchChangedFallbackHandler is a free log subscription operation binding the contract event 0x5ac6c46c93c8d0e53714ba3b53db3e7c046da994313d7ed0d192028bc7c228b0. +// +// Solidity: event ChangedFallbackHandler(address handler) +func (_SafeAbi *SafeAbiFilterer) WatchChangedFallbackHandler(opts *bind.WatchOpts, sink chan<- *SafeAbiChangedFallbackHandler) (event.Subscription, error) { + + logs, sub, err := _SafeAbi.contract.WatchLogs(opts, "ChangedFallbackHandler") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(SafeAbiChangedFallbackHandler) + if err := _SafeAbi.contract.UnpackLog(event, "ChangedFallbackHandler", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseChangedFallbackHandler is a log parse operation binding the contract event 0x5ac6c46c93c8d0e53714ba3b53db3e7c046da994313d7ed0d192028bc7c228b0. +// +// Solidity: event ChangedFallbackHandler(address handler) +func (_SafeAbi *SafeAbiFilterer) ParseChangedFallbackHandler(log types.Log) (*SafeAbiChangedFallbackHandler, error) { + event := new(SafeAbiChangedFallbackHandler) + if err := _SafeAbi.contract.UnpackLog(event, "ChangedFallbackHandler", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// SafeAbiChangedGuardIterator is returned from FilterChangedGuard and is used to iterate over the raw logs and unpacked data for ChangedGuard events raised by the SafeAbi contract. +type SafeAbiChangedGuardIterator struct { + Event *SafeAbiChangedGuard // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *SafeAbiChangedGuardIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(SafeAbiChangedGuard) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(SafeAbiChangedGuard) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *SafeAbiChangedGuardIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *SafeAbiChangedGuardIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// SafeAbiChangedGuard represents a ChangedGuard event raised by the SafeAbi contract. +type SafeAbiChangedGuard struct { + Guard common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterChangedGuard is a free log retrieval operation binding the contract event 0x1151116914515bc0891ff9047a6cb32cf902546f83066499bcf8ba33d2353fa2. +// +// Solidity: event ChangedGuard(address guard) +func (_SafeAbi *SafeAbiFilterer) FilterChangedGuard(opts *bind.FilterOpts) (*SafeAbiChangedGuardIterator, error) { + + logs, sub, err := _SafeAbi.contract.FilterLogs(opts, "ChangedGuard") + if err != nil { + return nil, err + } + return &SafeAbiChangedGuardIterator{contract: _SafeAbi.contract, event: "ChangedGuard", logs: logs, sub: sub}, nil +} + +// WatchChangedGuard is a free log subscription operation binding the contract event 0x1151116914515bc0891ff9047a6cb32cf902546f83066499bcf8ba33d2353fa2. +// +// Solidity: event ChangedGuard(address guard) +func (_SafeAbi *SafeAbiFilterer) WatchChangedGuard(opts *bind.WatchOpts, sink chan<- *SafeAbiChangedGuard) (event.Subscription, error) { + + logs, sub, err := _SafeAbi.contract.WatchLogs(opts, "ChangedGuard") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(SafeAbiChangedGuard) + if err := _SafeAbi.contract.UnpackLog(event, "ChangedGuard", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseChangedGuard is a log parse operation binding the contract event 0x1151116914515bc0891ff9047a6cb32cf902546f83066499bcf8ba33d2353fa2. +// +// Solidity: event ChangedGuard(address guard) +func (_SafeAbi *SafeAbiFilterer) ParseChangedGuard(log types.Log) (*SafeAbiChangedGuard, error) { + event := new(SafeAbiChangedGuard) + if err := _SafeAbi.contract.UnpackLog(event, "ChangedGuard", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// SafeAbiChangedThresholdIterator is returned from FilterChangedThreshold and is used to iterate over the raw logs and unpacked data for ChangedThreshold events raised by the SafeAbi contract. +type SafeAbiChangedThresholdIterator struct { + Event *SafeAbiChangedThreshold // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *SafeAbiChangedThresholdIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(SafeAbiChangedThreshold) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(SafeAbiChangedThreshold) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *SafeAbiChangedThresholdIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *SafeAbiChangedThresholdIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// SafeAbiChangedThreshold represents a ChangedThreshold event raised by the SafeAbi contract. +type SafeAbiChangedThreshold struct { + Threshold *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterChangedThreshold is a free log retrieval operation binding the contract event 0x610f7ff2b304ae8903c3de74c60c6ab1f7d6226b3f52c5161905bb5ad4039c93. +// +// Solidity: event ChangedThreshold(uint256 threshold) +func (_SafeAbi *SafeAbiFilterer) FilterChangedThreshold(opts *bind.FilterOpts) (*SafeAbiChangedThresholdIterator, error) { + + logs, sub, err := _SafeAbi.contract.FilterLogs(opts, "ChangedThreshold") + if err != nil { + return nil, err + } + return &SafeAbiChangedThresholdIterator{contract: _SafeAbi.contract, event: "ChangedThreshold", logs: logs, sub: sub}, nil +} + +// WatchChangedThreshold is a free log subscription operation binding the contract event 0x610f7ff2b304ae8903c3de74c60c6ab1f7d6226b3f52c5161905bb5ad4039c93. +// +// Solidity: event ChangedThreshold(uint256 threshold) +func (_SafeAbi *SafeAbiFilterer) WatchChangedThreshold(opts *bind.WatchOpts, sink chan<- *SafeAbiChangedThreshold) (event.Subscription, error) { + + logs, sub, err := _SafeAbi.contract.WatchLogs(opts, "ChangedThreshold") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(SafeAbiChangedThreshold) + if err := _SafeAbi.contract.UnpackLog(event, "ChangedThreshold", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseChangedThreshold is a log parse operation binding the contract event 0x610f7ff2b304ae8903c3de74c60c6ab1f7d6226b3f52c5161905bb5ad4039c93. +// +// Solidity: event ChangedThreshold(uint256 threshold) +func (_SafeAbi *SafeAbiFilterer) ParseChangedThreshold(log types.Log) (*SafeAbiChangedThreshold, error) { + event := new(SafeAbiChangedThreshold) + if err := _SafeAbi.contract.UnpackLog(event, "ChangedThreshold", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// SafeAbiDisabledModuleIterator is returned from FilterDisabledModule and is used to iterate over the raw logs and unpacked data for DisabledModule events raised by the SafeAbi contract. +type SafeAbiDisabledModuleIterator struct { + Event *SafeAbiDisabledModule // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *SafeAbiDisabledModuleIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(SafeAbiDisabledModule) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(SafeAbiDisabledModule) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *SafeAbiDisabledModuleIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *SafeAbiDisabledModuleIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// SafeAbiDisabledModule represents a DisabledModule event raised by the SafeAbi contract. +type SafeAbiDisabledModule struct { + Module common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterDisabledModule is a free log retrieval operation binding the contract event 0xaab4fa2b463f581b2b32cb3b7e3b704b9ce37cc209b5fb4d77e593ace4054276. +// +// Solidity: event DisabledModule(address module) +func (_SafeAbi *SafeAbiFilterer) FilterDisabledModule(opts *bind.FilterOpts) (*SafeAbiDisabledModuleIterator, error) { + + logs, sub, err := _SafeAbi.contract.FilterLogs(opts, "DisabledModule") + if err != nil { + return nil, err + } + return &SafeAbiDisabledModuleIterator{contract: _SafeAbi.contract, event: "DisabledModule", logs: logs, sub: sub}, nil +} + +// WatchDisabledModule is a free log subscription operation binding the contract event 0xaab4fa2b463f581b2b32cb3b7e3b704b9ce37cc209b5fb4d77e593ace4054276. +// +// Solidity: event DisabledModule(address module) +func (_SafeAbi *SafeAbiFilterer) WatchDisabledModule(opts *bind.WatchOpts, sink chan<- *SafeAbiDisabledModule) (event.Subscription, error) { + + logs, sub, err := _SafeAbi.contract.WatchLogs(opts, "DisabledModule") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(SafeAbiDisabledModule) + if err := _SafeAbi.contract.UnpackLog(event, "DisabledModule", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseDisabledModule is a log parse operation binding the contract event 0xaab4fa2b463f581b2b32cb3b7e3b704b9ce37cc209b5fb4d77e593ace4054276. +// +// Solidity: event DisabledModule(address module) +func (_SafeAbi *SafeAbiFilterer) ParseDisabledModule(log types.Log) (*SafeAbiDisabledModule, error) { + event := new(SafeAbiDisabledModule) + if err := _SafeAbi.contract.UnpackLog(event, "DisabledModule", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// SafeAbiEnabledModuleIterator is returned from FilterEnabledModule and is used to iterate over the raw logs and unpacked data for EnabledModule events raised by the SafeAbi contract. +type SafeAbiEnabledModuleIterator struct { + Event *SafeAbiEnabledModule // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *SafeAbiEnabledModuleIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(SafeAbiEnabledModule) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(SafeAbiEnabledModule) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *SafeAbiEnabledModuleIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *SafeAbiEnabledModuleIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// SafeAbiEnabledModule represents a EnabledModule event raised by the SafeAbi contract. +type SafeAbiEnabledModule struct { + Module common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterEnabledModule is a free log retrieval operation binding the contract event 0xecdf3a3effea5783a3c4c2140e677577666428d44ed9d474a0b3a4c9943f8440. +// +// Solidity: event EnabledModule(address module) +func (_SafeAbi *SafeAbiFilterer) FilterEnabledModule(opts *bind.FilterOpts) (*SafeAbiEnabledModuleIterator, error) { + + logs, sub, err := _SafeAbi.contract.FilterLogs(opts, "EnabledModule") + if err != nil { + return nil, err + } + return &SafeAbiEnabledModuleIterator{contract: _SafeAbi.contract, event: "EnabledModule", logs: logs, sub: sub}, nil +} + +// WatchEnabledModule is a free log subscription operation binding the contract event 0xecdf3a3effea5783a3c4c2140e677577666428d44ed9d474a0b3a4c9943f8440. +// +// Solidity: event EnabledModule(address module) +func (_SafeAbi *SafeAbiFilterer) WatchEnabledModule(opts *bind.WatchOpts, sink chan<- *SafeAbiEnabledModule) (event.Subscription, error) { + + logs, sub, err := _SafeAbi.contract.WatchLogs(opts, "EnabledModule") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(SafeAbiEnabledModule) + if err := _SafeAbi.contract.UnpackLog(event, "EnabledModule", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseEnabledModule is a log parse operation binding the contract event 0xecdf3a3effea5783a3c4c2140e677577666428d44ed9d474a0b3a4c9943f8440. +// +// Solidity: event EnabledModule(address module) +func (_SafeAbi *SafeAbiFilterer) ParseEnabledModule(log types.Log) (*SafeAbiEnabledModule, error) { + event := new(SafeAbiEnabledModule) + if err := _SafeAbi.contract.UnpackLog(event, "EnabledModule", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// SafeAbiExecutionFailureIterator is returned from FilterExecutionFailure and is used to iterate over the raw logs and unpacked data for ExecutionFailure events raised by the SafeAbi contract. +type SafeAbiExecutionFailureIterator struct { + Event *SafeAbiExecutionFailure // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *SafeAbiExecutionFailureIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(SafeAbiExecutionFailure) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(SafeAbiExecutionFailure) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *SafeAbiExecutionFailureIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *SafeAbiExecutionFailureIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// SafeAbiExecutionFailure represents a ExecutionFailure event raised by the SafeAbi contract. +type SafeAbiExecutionFailure struct { + TxHash [32]byte + Payment *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterExecutionFailure is a free log retrieval operation binding the contract event 0x23428b18acfb3ea64b08dc0c1d296ea9c09702c09083ca5272e64d115b687d23. +// +// Solidity: event ExecutionFailure(bytes32 txHash, uint256 payment) +func (_SafeAbi *SafeAbiFilterer) FilterExecutionFailure(opts *bind.FilterOpts) (*SafeAbiExecutionFailureIterator, error) { + + logs, sub, err := _SafeAbi.contract.FilterLogs(opts, "ExecutionFailure") + if err != nil { + return nil, err + } + return &SafeAbiExecutionFailureIterator{contract: _SafeAbi.contract, event: "ExecutionFailure", logs: logs, sub: sub}, nil +} + +// WatchExecutionFailure is a free log subscription operation binding the contract event 0x23428b18acfb3ea64b08dc0c1d296ea9c09702c09083ca5272e64d115b687d23. +// +// Solidity: event ExecutionFailure(bytes32 txHash, uint256 payment) +func (_SafeAbi *SafeAbiFilterer) WatchExecutionFailure(opts *bind.WatchOpts, sink chan<- *SafeAbiExecutionFailure) (event.Subscription, error) { + + logs, sub, err := _SafeAbi.contract.WatchLogs(opts, "ExecutionFailure") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(SafeAbiExecutionFailure) + if err := _SafeAbi.contract.UnpackLog(event, "ExecutionFailure", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseExecutionFailure is a log parse operation binding the contract event 0x23428b18acfb3ea64b08dc0c1d296ea9c09702c09083ca5272e64d115b687d23. +// +// Solidity: event ExecutionFailure(bytes32 txHash, uint256 payment) +func (_SafeAbi *SafeAbiFilterer) ParseExecutionFailure(log types.Log) (*SafeAbiExecutionFailure, error) { + event := new(SafeAbiExecutionFailure) + if err := _SafeAbi.contract.UnpackLog(event, "ExecutionFailure", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// SafeAbiExecutionFromModuleFailureIterator is returned from FilterExecutionFromModuleFailure and is used to iterate over the raw logs and unpacked data for ExecutionFromModuleFailure events raised by the SafeAbi contract. +type SafeAbiExecutionFromModuleFailureIterator struct { + Event *SafeAbiExecutionFromModuleFailure // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *SafeAbiExecutionFromModuleFailureIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(SafeAbiExecutionFromModuleFailure) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(SafeAbiExecutionFromModuleFailure) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *SafeAbiExecutionFromModuleFailureIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *SafeAbiExecutionFromModuleFailureIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// SafeAbiExecutionFromModuleFailure represents a ExecutionFromModuleFailure event raised by the SafeAbi contract. +type SafeAbiExecutionFromModuleFailure struct { + Module common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterExecutionFromModuleFailure is a free log retrieval operation binding the contract event 0xacd2c8702804128fdb0db2bb49f6d127dd0181c13fd45dbfe16de0930e2bd375. +// +// Solidity: event ExecutionFromModuleFailure(address indexed module) +func (_SafeAbi *SafeAbiFilterer) FilterExecutionFromModuleFailure(opts *bind.FilterOpts, module []common.Address) (*SafeAbiExecutionFromModuleFailureIterator, error) { + + var moduleRule []interface{} + for _, moduleItem := range module { + moduleRule = append(moduleRule, moduleItem) + } + + logs, sub, err := _SafeAbi.contract.FilterLogs(opts, "ExecutionFromModuleFailure", moduleRule) + if err != nil { + return nil, err + } + return &SafeAbiExecutionFromModuleFailureIterator{contract: _SafeAbi.contract, event: "ExecutionFromModuleFailure", logs: logs, sub: sub}, nil +} + +// WatchExecutionFromModuleFailure is a free log subscription operation binding the contract event 0xacd2c8702804128fdb0db2bb49f6d127dd0181c13fd45dbfe16de0930e2bd375. +// +// Solidity: event ExecutionFromModuleFailure(address indexed module) +func (_SafeAbi *SafeAbiFilterer) WatchExecutionFromModuleFailure(opts *bind.WatchOpts, sink chan<- *SafeAbiExecutionFromModuleFailure, module []common.Address) (event.Subscription, error) { + + var moduleRule []interface{} + for _, moduleItem := range module { + moduleRule = append(moduleRule, moduleItem) + } + + logs, sub, err := _SafeAbi.contract.WatchLogs(opts, "ExecutionFromModuleFailure", moduleRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(SafeAbiExecutionFromModuleFailure) + if err := _SafeAbi.contract.UnpackLog(event, "ExecutionFromModuleFailure", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseExecutionFromModuleFailure is a log parse operation binding the contract event 0xacd2c8702804128fdb0db2bb49f6d127dd0181c13fd45dbfe16de0930e2bd375. +// +// Solidity: event ExecutionFromModuleFailure(address indexed module) +func (_SafeAbi *SafeAbiFilterer) ParseExecutionFromModuleFailure(log types.Log) (*SafeAbiExecutionFromModuleFailure, error) { + event := new(SafeAbiExecutionFromModuleFailure) + if err := _SafeAbi.contract.UnpackLog(event, "ExecutionFromModuleFailure", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// SafeAbiExecutionFromModuleSuccessIterator is returned from FilterExecutionFromModuleSuccess and is used to iterate over the raw logs and unpacked data for ExecutionFromModuleSuccess events raised by the SafeAbi contract. +type SafeAbiExecutionFromModuleSuccessIterator struct { + Event *SafeAbiExecutionFromModuleSuccess // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *SafeAbiExecutionFromModuleSuccessIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(SafeAbiExecutionFromModuleSuccess) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(SafeAbiExecutionFromModuleSuccess) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *SafeAbiExecutionFromModuleSuccessIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *SafeAbiExecutionFromModuleSuccessIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// SafeAbiExecutionFromModuleSuccess represents a ExecutionFromModuleSuccess event raised by the SafeAbi contract. +type SafeAbiExecutionFromModuleSuccess struct { + Module common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterExecutionFromModuleSuccess is a free log retrieval operation binding the contract event 0x6895c13664aa4f67288b25d7a21d7aaa34916e355fb9b6fae0a139a9085becb8. +// +// Solidity: event ExecutionFromModuleSuccess(address indexed module) +func (_SafeAbi *SafeAbiFilterer) FilterExecutionFromModuleSuccess(opts *bind.FilterOpts, module []common.Address) (*SafeAbiExecutionFromModuleSuccessIterator, error) { + + var moduleRule []interface{} + for _, moduleItem := range module { + moduleRule = append(moduleRule, moduleItem) + } + + logs, sub, err := _SafeAbi.contract.FilterLogs(opts, "ExecutionFromModuleSuccess", moduleRule) + if err != nil { + return nil, err + } + return &SafeAbiExecutionFromModuleSuccessIterator{contract: _SafeAbi.contract, event: "ExecutionFromModuleSuccess", logs: logs, sub: sub}, nil +} + +// WatchExecutionFromModuleSuccess is a free log subscription operation binding the contract event 0x6895c13664aa4f67288b25d7a21d7aaa34916e355fb9b6fae0a139a9085becb8. +// +// Solidity: event ExecutionFromModuleSuccess(address indexed module) +func (_SafeAbi *SafeAbiFilterer) WatchExecutionFromModuleSuccess(opts *bind.WatchOpts, sink chan<- *SafeAbiExecutionFromModuleSuccess, module []common.Address) (event.Subscription, error) { + + var moduleRule []interface{} + for _, moduleItem := range module { + moduleRule = append(moduleRule, moduleItem) + } + + logs, sub, err := _SafeAbi.contract.WatchLogs(opts, "ExecutionFromModuleSuccess", moduleRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(SafeAbiExecutionFromModuleSuccess) + if err := _SafeAbi.contract.UnpackLog(event, "ExecutionFromModuleSuccess", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseExecutionFromModuleSuccess is a log parse operation binding the contract event 0x6895c13664aa4f67288b25d7a21d7aaa34916e355fb9b6fae0a139a9085becb8. +// +// Solidity: event ExecutionFromModuleSuccess(address indexed module) +func (_SafeAbi *SafeAbiFilterer) ParseExecutionFromModuleSuccess(log types.Log) (*SafeAbiExecutionFromModuleSuccess, error) { + event := new(SafeAbiExecutionFromModuleSuccess) + if err := _SafeAbi.contract.UnpackLog(event, "ExecutionFromModuleSuccess", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// SafeAbiExecutionSuccessIterator is returned from FilterExecutionSuccess and is used to iterate over the raw logs and unpacked data for ExecutionSuccess events raised by the SafeAbi contract. +type SafeAbiExecutionSuccessIterator struct { + Event *SafeAbiExecutionSuccess // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *SafeAbiExecutionSuccessIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(SafeAbiExecutionSuccess) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(SafeAbiExecutionSuccess) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *SafeAbiExecutionSuccessIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *SafeAbiExecutionSuccessIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// SafeAbiExecutionSuccess represents a ExecutionSuccess event raised by the SafeAbi contract. +type SafeAbiExecutionSuccess struct { + TxHash [32]byte + Payment *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterExecutionSuccess is a free log retrieval operation binding the contract event 0x442e715f626346e8c54381002da614f62bee8d27386535b2521ec8540898556e. +// +// Solidity: event ExecutionSuccess(bytes32 txHash, uint256 payment) +func (_SafeAbi *SafeAbiFilterer) FilterExecutionSuccess(opts *bind.FilterOpts) (*SafeAbiExecutionSuccessIterator, error) { + + logs, sub, err := _SafeAbi.contract.FilterLogs(opts, "ExecutionSuccess") + if err != nil { + return nil, err + } + return &SafeAbiExecutionSuccessIterator{contract: _SafeAbi.contract, event: "ExecutionSuccess", logs: logs, sub: sub}, nil +} + +// WatchExecutionSuccess is a free log subscription operation binding the contract event 0x442e715f626346e8c54381002da614f62bee8d27386535b2521ec8540898556e. +// +// Solidity: event ExecutionSuccess(bytes32 txHash, uint256 payment) +func (_SafeAbi *SafeAbiFilterer) WatchExecutionSuccess(opts *bind.WatchOpts, sink chan<- *SafeAbiExecutionSuccess) (event.Subscription, error) { + + logs, sub, err := _SafeAbi.contract.WatchLogs(opts, "ExecutionSuccess") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(SafeAbiExecutionSuccess) + if err := _SafeAbi.contract.UnpackLog(event, "ExecutionSuccess", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseExecutionSuccess is a log parse operation binding the contract event 0x442e715f626346e8c54381002da614f62bee8d27386535b2521ec8540898556e. +// +// Solidity: event ExecutionSuccess(bytes32 txHash, uint256 payment) +func (_SafeAbi *SafeAbiFilterer) ParseExecutionSuccess(log types.Log) (*SafeAbiExecutionSuccess, error) { + event := new(SafeAbiExecutionSuccess) + if err := _SafeAbi.contract.UnpackLog(event, "ExecutionSuccess", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// SafeAbiRemovedOwnerIterator is returned from FilterRemovedOwner and is used to iterate over the raw logs and unpacked data for RemovedOwner events raised by the SafeAbi contract. +type SafeAbiRemovedOwnerIterator struct { + Event *SafeAbiRemovedOwner // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *SafeAbiRemovedOwnerIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(SafeAbiRemovedOwner) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(SafeAbiRemovedOwner) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *SafeAbiRemovedOwnerIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *SafeAbiRemovedOwnerIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// SafeAbiRemovedOwner represents a RemovedOwner event raised by the SafeAbi contract. +type SafeAbiRemovedOwner struct { + Owner common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterRemovedOwner is a free log retrieval operation binding the contract event 0xf8d49fc529812e9a7c5c50e69c20f0dccc0db8fa95c98bc58cc9a4f1c1299eaf. +// +// Solidity: event RemovedOwner(address owner) +func (_SafeAbi *SafeAbiFilterer) FilterRemovedOwner(opts *bind.FilterOpts) (*SafeAbiRemovedOwnerIterator, error) { + + logs, sub, err := _SafeAbi.contract.FilterLogs(opts, "RemovedOwner") + if err != nil { + return nil, err + } + return &SafeAbiRemovedOwnerIterator{contract: _SafeAbi.contract, event: "RemovedOwner", logs: logs, sub: sub}, nil +} + +// WatchRemovedOwner is a free log subscription operation binding the contract event 0xf8d49fc529812e9a7c5c50e69c20f0dccc0db8fa95c98bc58cc9a4f1c1299eaf. +// +// Solidity: event RemovedOwner(address owner) +func (_SafeAbi *SafeAbiFilterer) WatchRemovedOwner(opts *bind.WatchOpts, sink chan<- *SafeAbiRemovedOwner) (event.Subscription, error) { + + logs, sub, err := _SafeAbi.contract.WatchLogs(opts, "RemovedOwner") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(SafeAbiRemovedOwner) + if err := _SafeAbi.contract.UnpackLog(event, "RemovedOwner", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseRemovedOwner is a log parse operation binding the contract event 0xf8d49fc529812e9a7c5c50e69c20f0dccc0db8fa95c98bc58cc9a4f1c1299eaf. +// +// Solidity: event RemovedOwner(address owner) +func (_SafeAbi *SafeAbiFilterer) ParseRemovedOwner(log types.Log) (*SafeAbiRemovedOwner, error) { + event := new(SafeAbiRemovedOwner) + if err := _SafeAbi.contract.UnpackLog(event, "RemovedOwner", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// SafeAbiSafeModuleTransactionIterator is returned from FilterSafeModuleTransaction and is used to iterate over the raw logs and unpacked data for SafeModuleTransaction events raised by the SafeAbi contract. +type SafeAbiSafeModuleTransactionIterator struct { + Event *SafeAbiSafeModuleTransaction // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *SafeAbiSafeModuleTransactionIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(SafeAbiSafeModuleTransaction) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(SafeAbiSafeModuleTransaction) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *SafeAbiSafeModuleTransactionIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *SafeAbiSafeModuleTransactionIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// SafeAbiSafeModuleTransaction represents a SafeModuleTransaction event raised by the SafeAbi contract. +type SafeAbiSafeModuleTransaction struct { + Module common.Address + To common.Address + Value *big.Int + Data []byte + Operation uint8 + Raw types.Log // Blockchain specific contextual infos +} + +// FilterSafeModuleTransaction is a free log retrieval operation binding the contract event 0xb648d3644f584ed1c2232d53c46d87e693586486ad0d1175f8656013110b714e. +// +// Solidity: event SafeModuleTransaction(address module, address to, uint256 value, bytes data, uint8 operation) +func (_SafeAbi *SafeAbiFilterer) FilterSafeModuleTransaction(opts *bind.FilterOpts) (*SafeAbiSafeModuleTransactionIterator, error) { + + logs, sub, err := _SafeAbi.contract.FilterLogs(opts, "SafeModuleTransaction") + if err != nil { + return nil, err + } + return &SafeAbiSafeModuleTransactionIterator{contract: _SafeAbi.contract, event: "SafeModuleTransaction", logs: logs, sub: sub}, nil +} + +// WatchSafeModuleTransaction is a free log subscription operation binding the contract event 0xb648d3644f584ed1c2232d53c46d87e693586486ad0d1175f8656013110b714e. +// +// Solidity: event SafeModuleTransaction(address module, address to, uint256 value, bytes data, uint8 operation) +func (_SafeAbi *SafeAbiFilterer) WatchSafeModuleTransaction(opts *bind.WatchOpts, sink chan<- *SafeAbiSafeModuleTransaction) (event.Subscription, error) { + + logs, sub, err := _SafeAbi.contract.WatchLogs(opts, "SafeModuleTransaction") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(SafeAbiSafeModuleTransaction) + if err := _SafeAbi.contract.UnpackLog(event, "SafeModuleTransaction", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseSafeModuleTransaction is a log parse operation binding the contract event 0xb648d3644f584ed1c2232d53c46d87e693586486ad0d1175f8656013110b714e. +// +// Solidity: event SafeModuleTransaction(address module, address to, uint256 value, bytes data, uint8 operation) +func (_SafeAbi *SafeAbiFilterer) ParseSafeModuleTransaction(log types.Log) (*SafeAbiSafeModuleTransaction, error) { + event := new(SafeAbiSafeModuleTransaction) + if err := _SafeAbi.contract.UnpackLog(event, "SafeModuleTransaction", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// SafeAbiSafeMultiSigTransactionIterator is returned from FilterSafeMultiSigTransaction and is used to iterate over the raw logs and unpacked data for SafeMultiSigTransaction events raised by the SafeAbi contract. +type SafeAbiSafeMultiSigTransactionIterator struct { + Event *SafeAbiSafeMultiSigTransaction // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *SafeAbiSafeMultiSigTransactionIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(SafeAbiSafeMultiSigTransaction) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(SafeAbiSafeMultiSigTransaction) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *SafeAbiSafeMultiSigTransactionIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *SafeAbiSafeMultiSigTransactionIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// SafeAbiSafeMultiSigTransaction represents a SafeMultiSigTransaction event raised by the SafeAbi contract. +type SafeAbiSafeMultiSigTransaction struct { + To common.Address + Value *big.Int + Data []byte + Operation uint8 + SafeTxGas *big.Int + BaseGas *big.Int + GasPrice *big.Int + GasToken common.Address + RefundReceiver common.Address + Signatures []byte + AdditionalInfo []byte + Raw types.Log // Blockchain specific contextual infos +} + +// FilterSafeMultiSigTransaction is a free log retrieval operation binding the contract event 0x66753cd2356569ee081232e3be8909b950e0a76c1f8460c3a5e3c2be32b11bed. +// +// Solidity: event SafeMultiSigTransaction(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, bytes signatures, bytes additionalInfo) +func (_SafeAbi *SafeAbiFilterer) FilterSafeMultiSigTransaction(opts *bind.FilterOpts) (*SafeAbiSafeMultiSigTransactionIterator, error) { + + logs, sub, err := _SafeAbi.contract.FilterLogs(opts, "SafeMultiSigTransaction") + if err != nil { + return nil, err + } + return &SafeAbiSafeMultiSigTransactionIterator{contract: _SafeAbi.contract, event: "SafeMultiSigTransaction", logs: logs, sub: sub}, nil +} + +// WatchSafeMultiSigTransaction is a free log subscription operation binding the contract event 0x66753cd2356569ee081232e3be8909b950e0a76c1f8460c3a5e3c2be32b11bed. +// +// Solidity: event SafeMultiSigTransaction(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, bytes signatures, bytes additionalInfo) +func (_SafeAbi *SafeAbiFilterer) WatchSafeMultiSigTransaction(opts *bind.WatchOpts, sink chan<- *SafeAbiSafeMultiSigTransaction) (event.Subscription, error) { + + logs, sub, err := _SafeAbi.contract.WatchLogs(opts, "SafeMultiSigTransaction") + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(SafeAbiSafeMultiSigTransaction) + if err := _SafeAbi.contract.UnpackLog(event, "SafeMultiSigTransaction", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseSafeMultiSigTransaction is a log parse operation binding the contract event 0x66753cd2356569ee081232e3be8909b950e0a76c1f8460c3a5e3c2be32b11bed. +// +// Solidity: event SafeMultiSigTransaction(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, bytes signatures, bytes additionalInfo) +func (_SafeAbi *SafeAbiFilterer) ParseSafeMultiSigTransaction(log types.Log) (*SafeAbiSafeMultiSigTransaction, error) { + event := new(SafeAbiSafeMultiSigTransaction) + if err := _SafeAbi.contract.UnpackLog(event, "SafeMultiSigTransaction", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// SafeAbiSafeReceivedIterator is returned from FilterSafeReceived and is used to iterate over the raw logs and unpacked data for SafeReceived events raised by the SafeAbi contract. +type SafeAbiSafeReceivedIterator struct { + Event *SafeAbiSafeReceived // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *SafeAbiSafeReceivedIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(SafeAbiSafeReceived) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(SafeAbiSafeReceived) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *SafeAbiSafeReceivedIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *SafeAbiSafeReceivedIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// SafeAbiSafeReceived represents a SafeReceived event raised by the SafeAbi contract. +type SafeAbiSafeReceived struct { + Sender common.Address + Value *big.Int + Raw types.Log // Blockchain specific contextual infos +} + +// FilterSafeReceived is a free log retrieval operation binding the contract event 0x3d0ce9bfc3ed7d6862dbb28b2dea94561fe714a1b4d019aa8af39730d1ad7c3d. +// +// Solidity: event SafeReceived(address indexed sender, uint256 value) +func (_SafeAbi *SafeAbiFilterer) FilterSafeReceived(opts *bind.FilterOpts, sender []common.Address) (*SafeAbiSafeReceivedIterator, error) { + + var senderRule []interface{} + for _, senderItem := range sender { + senderRule = append(senderRule, senderItem) + } + + logs, sub, err := _SafeAbi.contract.FilterLogs(opts, "SafeReceived", senderRule) + if err != nil { + return nil, err + } + return &SafeAbiSafeReceivedIterator{contract: _SafeAbi.contract, event: "SafeReceived", logs: logs, sub: sub}, nil +} + +// WatchSafeReceived is a free log subscription operation binding the contract event 0x3d0ce9bfc3ed7d6862dbb28b2dea94561fe714a1b4d019aa8af39730d1ad7c3d. +// +// Solidity: event SafeReceived(address indexed sender, uint256 value) +func (_SafeAbi *SafeAbiFilterer) WatchSafeReceived(opts *bind.WatchOpts, sink chan<- *SafeAbiSafeReceived, sender []common.Address) (event.Subscription, error) { + + var senderRule []interface{} + for _, senderItem := range sender { + senderRule = append(senderRule, senderItem) + } + + logs, sub, err := _SafeAbi.contract.WatchLogs(opts, "SafeReceived", senderRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(SafeAbiSafeReceived) + if err := _SafeAbi.contract.UnpackLog(event, "SafeReceived", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseSafeReceived is a log parse operation binding the contract event 0x3d0ce9bfc3ed7d6862dbb28b2dea94561fe714a1b4d019aa8af39730d1ad7c3d. +// +// Solidity: event SafeReceived(address indexed sender, uint256 value) +func (_SafeAbi *SafeAbiFilterer) ParseSafeReceived(log types.Log) (*SafeAbiSafeReceived, error) { + event := new(SafeAbiSafeReceived) + if err := _SafeAbi.contract.UnpackLog(event, "SafeReceived", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// SafeAbiSafeSetupIterator is returned from FilterSafeSetup and is used to iterate over the raw logs and unpacked data for SafeSetup events raised by the SafeAbi contract. +type SafeAbiSafeSetupIterator struct { + Event *SafeAbiSafeSetup // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *SafeAbiSafeSetupIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(SafeAbiSafeSetup) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(SafeAbiSafeSetup) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *SafeAbiSafeSetupIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *SafeAbiSafeSetupIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// SafeAbiSafeSetup represents a SafeSetup event raised by the SafeAbi contract. +type SafeAbiSafeSetup struct { + Initiator common.Address + Owners []common.Address + Threshold *big.Int + Initializer common.Address + FallbackHandler common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterSafeSetup is a free log retrieval operation binding the contract event 0x141df868a6331af528e38c83b7aa03edc19be66e37ae67f9285bf4f8e3c6a1a8. +// +// Solidity: event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler) +func (_SafeAbi *SafeAbiFilterer) FilterSafeSetup(opts *bind.FilterOpts, initiator []common.Address) (*SafeAbiSafeSetupIterator, error) { + + var initiatorRule []interface{} + for _, initiatorItem := range initiator { + initiatorRule = append(initiatorRule, initiatorItem) + } + + logs, sub, err := _SafeAbi.contract.FilterLogs(opts, "SafeSetup", initiatorRule) + if err != nil { + return nil, err + } + return &SafeAbiSafeSetupIterator{contract: _SafeAbi.contract, event: "SafeSetup", logs: logs, sub: sub}, nil +} + +// WatchSafeSetup is a free log subscription operation binding the contract event 0x141df868a6331af528e38c83b7aa03edc19be66e37ae67f9285bf4f8e3c6a1a8. +// +// Solidity: event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler) +func (_SafeAbi *SafeAbiFilterer) WatchSafeSetup(opts *bind.WatchOpts, sink chan<- *SafeAbiSafeSetup, initiator []common.Address) (event.Subscription, error) { + + var initiatorRule []interface{} + for _, initiatorItem := range initiator { + initiatorRule = append(initiatorRule, initiatorItem) + } + + logs, sub, err := _SafeAbi.contract.WatchLogs(opts, "SafeSetup", initiatorRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(SafeAbiSafeSetup) + if err := _SafeAbi.contract.UnpackLog(event, "SafeSetup", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseSafeSetup is a log parse operation binding the contract event 0x141df868a6331af528e38c83b7aa03edc19be66e37ae67f9285bf4f8e3c6a1a8. +// +// Solidity: event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler) +func (_SafeAbi *SafeAbiFilterer) ParseSafeSetup(log types.Log) (*SafeAbiSafeSetup, error) { + event := new(SafeAbiSafeSetup) + if err := _SafeAbi.contract.UnpackLog(event, "SafeSetup", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} + +// SafeAbiSignMsgIterator is returned from FilterSignMsg and is used to iterate over the raw logs and unpacked data for SignMsg events raised by the SafeAbi contract. +type SafeAbiSignMsgIterator struct { + Event *SafeAbiSignMsg // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *SafeAbiSignMsgIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(SafeAbiSignMsg) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(SafeAbiSignMsg) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *SafeAbiSignMsgIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *SafeAbiSignMsgIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// SafeAbiSignMsg represents a SignMsg event raised by the SafeAbi contract. +type SafeAbiSignMsg struct { + MsgHash [32]byte + Raw types.Log // Blockchain specific contextual infos +} + +// FilterSignMsg is a free log retrieval operation binding the contract event 0xe7f4675038f4f6034dfcbbb24c4dc08e4ebf10eb9d257d3d02c0f38d122ac6e4. +// +// Solidity: event SignMsg(bytes32 indexed msgHash) +func (_SafeAbi *SafeAbiFilterer) FilterSignMsg(opts *bind.FilterOpts, msgHash [][32]byte) (*SafeAbiSignMsgIterator, error) { + + var msgHashRule []interface{} + for _, msgHashItem := range msgHash { + msgHashRule = append(msgHashRule, msgHashItem) + } + + logs, sub, err := _SafeAbi.contract.FilterLogs(opts, "SignMsg", msgHashRule) + if err != nil { + return nil, err + } + return &SafeAbiSignMsgIterator{contract: _SafeAbi.contract, event: "SignMsg", logs: logs, sub: sub}, nil +} + +// WatchSignMsg is a free log subscription operation binding the contract event 0xe7f4675038f4f6034dfcbbb24c4dc08e4ebf10eb9d257d3d02c0f38d122ac6e4. +// +// Solidity: event SignMsg(bytes32 indexed msgHash) +func (_SafeAbi *SafeAbiFilterer) WatchSignMsg(opts *bind.WatchOpts, sink chan<- *SafeAbiSignMsg, msgHash [][32]byte) (event.Subscription, error) { + + var msgHashRule []interface{} + for _, msgHashItem := range msgHash { + msgHashRule = append(msgHashRule, msgHashItem) + } + + logs, sub, err := _SafeAbi.contract.WatchLogs(opts, "SignMsg", msgHashRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(SafeAbiSignMsg) + if err := _SafeAbi.contract.UnpackLog(event, "SignMsg", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseSignMsg is a log parse operation binding the contract event 0xe7f4675038f4f6034dfcbbb24c4dc08e4ebf10eb9d257d3d02c0f38d122ac6e4. +// +// Solidity: event SignMsg(bytes32 indexed msgHash) +func (_SafeAbi *SafeAbiFilterer) ParseSignMsg(log types.Log) (*SafeAbiSignMsg, error) { + event := new(SafeAbiSignMsg) + if err := _SafeAbi.contract.UnpackLog(event, "SignMsg", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} diff --git a/utils/wallets/safe/utils.go b/utils/wallets/safe/utils.go new file mode 100644 index 0000000..426c084 --- /dev/null +++ b/utils/wallets/safe/utils.go @@ -0,0 +1,434 @@ +package safe + +import ( + "context" + "fmt" + "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/math" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient/simulated" + "github.com/ethereum/go-ethereum/signer/core/apitypes" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/pkg/errors" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "github.com/spf13/cast" + "math/big" + "net/url" + "omni-balance/utils" + "omni-balance/utils/chains" + "omni-balance/utils/constant" + "omni-balance/utils/safe_api" + apiclient "omni-balance/utils/safe_api/client" + "omni-balance/utils/safe_api/client/safes" + "omni-balance/utils/safe_api/client/transactions" + "omni-balance/utils/wallets/safe/safe_abi" + "strings" + "time" +) + +var ( + safeDomain = map[string]string{ + constant.Arbitrum: "safe-transaction-arbitrum.safe.global", + constant.Avalanche: "safe-transaction-avalanche.safe.global", + constant.Base: "safe-transaction-base.safe.global", + constant.Bnb: "safe-transaction-bsc.safe.global", + constant.Celo: "safe-transaction-celo.safe.global", + constant.Ethereum: "safe-transaction-mainnet.safe.global", + constant.Gnosis: "safe-transaction-gnosis-chain.safe.global", + constant.Optimism: "safe-transaction-optimism.safe.global", + constant.Polygon: "safe-transaction-polygon.safe.global", + constant.PolygonZkEvm: "safe-transaction-zkevm.safe.global", + constant.Zksync: "safe-transaction-zkevm.safe.global", + constant.Sepolia: "safe-transaction-sepolia.safe.global", + } +) + +type SafeResp struct { + Code int `json:"code"` + Message string `json:"message"` +} + +type Info struct { + SafeResp + Address string `json:"address"` + Nonce int `json:"nonce"` + Threshold int `json:"threshold"` + Owners []string `json:"owners"` + MasterCopy string `json:"masterCopy"` + Modules []interface{} `json:"modules"` + FallbackHandler string `json:"fallbackHandler"` + Guard string `json:"guard"` + Version string `json:"version"` +} + +type Transaction struct { + Detail string `json:"detail"` + Safe common.Address `json:"safe"` + To common.Address `json:"to"` + Value decimal.Decimal `json:"value"` + Data string `json:"data"` + Operation int `json:"operation"` + GasToken common.Address `json:"gasToken"` + SafeTxGas decimal.Decimal `json:"safeTxGas"` + BaseGas decimal.Decimal `json:"baseGas"` + GasPrice decimal.Decimal `json:"gasPrice"` + RefundReceiver common.Address `json:"refundReceiver"` + Nonce int `json:"nonce"` + TransactionHash interface{} `json:"transactionHash"` + SafeTxHash common.Hash `json:"safeTxHash"` + Proposer string `json:"proposer"` + Executor interface{} `json:"executor"` + IsExecuted bool `json:"isExecuted"` + IsSuccessful bool `json:"isSuccessful"` + EthGasPrice interface{} `json:"ethGasPrice"` + MaxFeePerGas interface{} `json:"maxFeePerGas"` + MaxPriorityFeePerGas interface{} `json:"maxPriorityFeePerGas"` + GasUsed interface{} `json:"gasUsed"` + Fee interface{} `json:"fee"` + Origin string `json:"origin"` + DataDecoded interface{} `json:"dataDecoded"` + ConfirmationsRequired int `json:"confirmationsRequired"` + Confirmations []struct { + Owner string `json:"owner"` + SubmissionDate time.Time `json:"submissionDate"` + TransactionHash interface{} `json:"transactionHash"` + Signature string `json:"signature"` + SignatureType string `json:"signatureType"` + } `json:"confirmations"` + Trusted bool `json:"trusted"` + Signatures interface{} `json:"signatures"` +} + +func (s *Safe) GetDomainByCtx(ctx context.Context) string { + chainName := cast.ToString(ctx.Value(constant.ChainNameKeyInCtx)) + if _, ok := safeDomain[chainName]; ok { + return safeDomain[chainName] + } + panic("chain name not found in context") +} + +func (s *Safe) GetChainIdByCtx(ctx context.Context) int { + chainId := constant.GetChainId(cast.ToString(ctx.Value(constant.ChainNameKeyInCtx))) + if chainId == 0 { + logrus.Fatalf("chain id not found in context") + } + return chainId +} + +func (s *Safe) safeWalletInfo(ctx context.Context) (*safe_api.SafeInfoResponse, error) { + var address = s.getOperatorSafeAddress().Hex() + resp, err := s.Client(ctx).Safes.V1SafesRead(&safes.V1SafesReadParams{Address: address}, nil) + if err != nil { + return nil, errors.Wrapf(err, "get %s safe info error", address) + } + return resp.Payload, nil +} + +func (s *Safe) Client(ctx context.Context) *apiclient.SafeTransactionServiceAPI { + c := httptransport.New( + s.GetDomainByCtx(ctx), apiclient.DefaultBasePath, apiclient.DefaultSchemes) + c.Context = ctx + c.SetLogger(logrus.New()) + return apiclient.New(c, strfmt.Default) +} + +func (s *Safe) Transfer(ctx context.Context, tx *types.LegacyTx, client simulated.Client) (common.Hash, error) { + if s.operatorSafe != nil { + utils.GetLogFromCtx(ctx).Debugf("transfer use operator safe") + return s.operatorSafe.SendTransaction(ctx, tx, client) + } + return chains.SendTransaction(ctx, client, tx, s.GetAddress(true), s.conf.Operator.PrivateKey) +} + +func (s *Safe) MultisigTransaction(ctx context.Context, tx *types.LegacyTx, client simulated.Client) (common.Hash, error) { + log := utils.GetLogFromCtx(ctx) + if tx.Nonce == 0 { + nonce, err := s.nonce(ctx) + if err != nil { + return common.Hash{}, errors.Wrap(err, "get nonce error") + } + tx.Nonce = uint64(nonce) + log.Debugf("%s nonce: %d", s.getOperatorSafeAddress(), tx.Nonce) + } + + to, _, err := chains.GetTransferInfo(tx.Data) + if err == nil && s.GetAddress().Cmp(to) == 0 { + log.Debugf("transfer to self") + return s.Transfer(ctx, tx, client) + } + + info, err := s.safeWalletInfo(ctx) + if err != nil { + return common.Hash{}, err + } + safeTxHash, err := s.proposeTransaction(ctx, tx) + if err != nil { + return common.Hash{}, errors.Wrap(err, "propose transaction error") + } + log.Debugf("safe tx hash: %s", safeTxHash) + if *info.Threshold > 1 { // todo: notify + return safeTxHash, nil + } + + txInfo, err := s.GetMultiSigTransaction(ctx, safeTxHash) + if err != nil { + return safeTxHash, errors.Wrap(err, "get multisig transaction error") + } + if txInfo.IsExecuted { + return safeTxHash, errors.New("transaction already executed") + } + return safeTxHash, s.ExecTransaction(ctx, txInfo, client) +} + +func (s *Safe) getOperatorSafeAddress() common.Address { + if s.conf.Operator.MultiSignType != "" { + return s.conf.Operator.Address + } + return s.conf.Address +} + +func (s *Safe) getOperatorAddress() common.Address { + if s.conf.Operator.MultiSignType != "" { + return s.conf.Operator.Operator + } + return s.conf.Operator.Address +} + +func (s *Safe) nonce(ctx context.Context) (int64, error) { + u := fmt.Sprintf("https://safe-client.safe.global/v1/chains/%d/safes/%s/nonces", s.GetChainIdByCtx(ctx), s.getOperatorSafeAddress().Hex()) + var dest = struct { + RecommendedNonce int64 `json:"recommendedNonce"` + }{} + return dest.RecommendedNonce, utils.Request(ctx, "GET", u, nil, &dest) +} + +func (s *Safe) proposeTransaction(ctx context.Context, tx *types.LegacyTx) (common.Hash, error) { + nonce, err := s.nonce(ctx) + if err != nil { + return common.Hash{}, errors.Wrap(err, "get nonce error") + } + t := &Transaction{ + Safe: s.getOperatorSafeAddress(), + To: *tx.To, + Data: common.Bytes2Hex(tx.Data), + Nonce: int(nonce), + } + //t.Data = fmt.Sprintf("0x%s", t.Data) + if tx.Value != nil { + t.Value = decimal.NewFromBigInt(tx.Value, 0) + } + + typedData := s.eip712(ctx, *t) + var safeTxHash string + + sigData, err := chains.SignTypedData(typedData, func(msg []byte) (sig []byte, err error) { + safeTxHash = common.Bytes2Hex(msg) + privateKey := s.conf.PrivateKey + if s.conf.Operator.PrivateKey != "" { + privateKey = s.conf.Operator.PrivateKey + } + return chains.SignMsg(msg, privateKey) + }) + if err != nil { + return common.Hash{}, errors.Wrap(err, "sign typed data error") + } + params := &transactions.V1SafesMultisigTransactionsCreateParams{ + Address: s.getOperatorSafeAddress().Hex(), + Data: &safe_api.SafeMultisigTransaction{ + Safe: utils.String(s.getOperatorSafeAddress().Hex()), + BaseGas: utils.Number(int64(0)), + ContractTransactionHash: utils.String(fmt.Sprintf("0x%s", safeTxHash)), + Data: utils.String(t.Data), + GasPrice: utils.Number(int64(0)), + GasToken: utils.String(constant.ZeroAddress.Hex()), + Nonce: utils.Number(int64(t.Nonce)), + Operation: utils.Number(int64(0)), + RefundReceiver: utils.String(constant.ZeroAddress.Hex()), + SafeTxGas: utils.Number(int64(0)), + Sender: utils.String(s.getOperatorAddress().Hex()), + Signature: utils.String(fmt.Sprintf("0x%s", common.Bytes2Hex(sigData))), + To: utils.String(t.To.Hex()), + Value: utils.Number(t.Value.IntPart()), + }, + Context: ctx, + } + + _, err = s.Client(ctx).Transactions.V1SafesMultisigTransactionsCreate(params, nil) + if err != nil { + return common.Hash{}, errors.Wrap(err, "create multisig transaction error") + } + return common.HexToHash(fmt.Sprintf("0x%s", safeTxHash)), nil +} + +func (s *Safe) GetMultiSigTransaction(ctx context.Context, safeTxHash common.Hash) (Transaction, error) { + u := fmt.Sprintf("https://%s/api/v1/multisig-transactions/%s/", s.GetDomainByCtx(ctx), safeTxHash.Hex()) + var result Transaction + if err := utils.Request(ctx, "GET", u, nil, &result); err != nil { + return result, errors.Wrap(err, "get multisig transaction error") + } + if result.Detail != "" { + return result, errors.New(result.Detail) + } + return result, nil +} + +func (s *Safe) ListMultiSigTransactions(ctx context.Context, filters ...string) ([]Transaction, error) { + // executed=false&ordering=nonce + u, err := url.Parse(fmt.Sprintf("https://%s/api/v1/safes/%s/multisig-transactions/", s.GetDomainByCtx(ctx), "0x0350101f2cB6aA65caaB7954246a56f906A3F57D")) + if err != nil { + return nil, errors.Wrap(err, "parse url error") + } + query := u.Query() + var ( + key string + ) + for index, v := range filters { + if index%2 == 0 { + key = v + continue + } + query.Add(key, v) + } + u.RawQuery = query.Encode() + var result = struct { + Count int `json:"count"` + Result []Transaction `json:"results"` + }{} + + if err := utils.Request(ctx, "GET", u.String(), nil, &result); err != nil { + return nil, errors.Wrap(err, "get multisig transactions error") + } + return result.Result, nil +} + +func (s *Safe) ExecTransaction(ctx context.Context, tx Transaction, client simulated.Client) error { + abi, err := safe_abi.SafeAbiMetaData.GetAbi() + if err != nil { + return errors.Wrap(err, "get abi error") + } + nonce, err := client.NonceAt(context.TODO(), s.GetAddress(true), nil) + if err != nil { + return errors.Wrap(err, "get nonce error") + } + var ( + signatures []string + hasSelf = false + ) + + for _, v := range tx.Confirmations { + if strings.EqualFold(v.Owner, s.GetAddress(true).Hex()) { + hasSelf = true + } + signatures = append(signatures, strings.TrimPrefix(v.Signature, "0x")) + } + + var signatureData []byte + if !hasSelf && len(signatures) != 0 { + address := common.Bytes2Hex(common.LeftPadBytes(s.GetAddress(true).Bytes(), 32)) + confriom := common.Bytes2Hex(common.LeftPadBytes(big.NewInt(1).Bytes(), 33)) + signatureData = common.Hex2Bytes(fmt.Sprintf("%s%s", address, confriom)) + } else { + signatureData, err = chains.SignTypedData(s.eip712(ctx, tx), func(msg []byte) (sig []byte, err error) { + return chains.SignMsg(msg, s.conf.PrivateKey) + }) + if err != nil { + return errors.Wrap(err, "sign error") + } + } + + if len(signatures) < tx.ConfirmationsRequired && hasSelf { + return errors.New("not enough signatures") + } + + if len(signatures) < tx.ConfirmationsRequired { + signatures = append(signatures, common.Bytes2Hex(signatureData)) + } + + if len(signatures) < tx.ConfirmationsRequired { + return errors.New("not enough signatures") + } + input, err := abi.Pack("execTransaction", + tx.To, + tx.Value.BigInt(), + common.Hex2Bytes(strings.TrimPrefix(tx.Data, "0x")), + uint8(tx.Operation), + tx.SafeTxGas.BigInt(), + tx.BaseGas.BigInt(), + tx.GasPrice.BigInt(), + tx.GasToken, + tx.RefundReceiver, + common.Hex2Bytes(strings.Join(signatures, "")), + ) + if err != nil { + return errors.Wrap(err, "pack error") + } + gasPrice, err := client.SuggestGasPrice(ctx) + if err != nil { + return errors.Wrap(err, "suggest gas price error") + } + gas, err := client.EstimateGas(context.TODO(), ethereum.CallMsg{ + From: s.GetAddress(true), + To: &tx.Safe, + GasPrice: gasPrice, + Data: input, + }) + if err != nil { + return errors.Wrap(err, "estimate gas error") + } + chainTransaction := types.NewTx(&types.LegacyTx{ + Nonce: nonce, + GasPrice: gasPrice, + Gas: gas, + To: &tx.Safe, + Data: input, + }) + + signTx, err := chains.SignTx(chainTransaction, s.conf.PrivateKey, int64(s.GetChainIdByCtx(ctx))) + if err != nil { + return errors.Wrap(err, "sign tx error") + } + return client.SendTransaction(ctx, signTx) +} + +func (s *Safe) eip712(ctx context.Context, t Transaction) apitypes.TypedData { + return apitypes.TypedData{ + Types: apitypes.Types{ + "EIP712Domain": []apitypes.Type{ + {Name: "chainId", Type: "uint256"}, + {Name: "verifyingContract", Type: "address"}, + }, + "SafeTx": []apitypes.Type{ + {Type: "address", Name: "to"}, + {Type: "uint256", Name: "value"}, + {Type: "bytes", Name: "data"}, + {Type: "uint8", Name: "operation"}, + {Type: "uint256", Name: "safeTxGas"}, + {Type: "uint256", Name: "baseGas"}, + {Type: "uint256", Name: "gasPrice"}, + {Type: "address", Name: "gasToken"}, + {Type: "address", Name: "refundReceiver"}, + {Type: "uint256", Name: "nonce"}, + }, + }, + PrimaryType: "SafeTx", + Domain: apitypes.TypedDataDomain{ + ChainId: math.NewHexOrDecimal256(int64(s.GetChainIdByCtx(ctx))), + VerifyingContract: t.Safe.Hex(), + }, + Message: apitypes.TypedDataMessage{ + "to": t.To.Hex(), + "value": math.NewHexOrDecimal256(t.Value.IntPart()), + "data": common.Hex2Bytes(t.Data), + "operation": math.NewHexOrDecimal256(int64(t.Operation)), + "baseGas": math.NewHexOrDecimal256(t.BaseGas.IntPart()), + "gasPrice": math.NewHexOrDecimal256(t.GasPrice.IntPart()), + "gasToken": t.GasToken.Hex(), + "refundReceiver": t.RefundReceiver.Hex(), + "nonce": math.NewHexOrDecimal256(int64(t.Nonce)), + "safeTxGas": math.NewHexOrDecimal256(t.SafeTxGas.IntPart()), + }, + } +} diff --git a/utils/wallets/wallets.go b/utils/wallets/wallets.go new file mode 100644 index 0000000..8e87b60 --- /dev/null +++ b/utils/wallets/wallets.go @@ -0,0 +1,56 @@ +package wallets + +import ( + "context" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/ethclient/simulated" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" +) + +type MultiSignType string + +const ( + MultiSignTypeSafe MultiSignType = "safe" +) + +type Wallets interface { + CheckFullAccess(ctx context.Context) error + GetAddress(isReal ...bool) common.Address + IsDifferentAddress() bool + IsSupportEip712() bool + SignRawMessage(msg []byte) (sig []byte, err error) + + GetExternalBalance(ctx context.Context, tokenAddress common.Address, decimals int32, client simulated.Client) (decimal.Decimal, error) + GetBalance(ctx context.Context, tokenAddress common.Address, decimals int32, client simulated.Client) (decimal.Decimal, error) + GetNonce(ctx context.Context, client simulated.Client) (uint64, error) + SendTransaction(ctx context.Context, tx *types.LegacyTx, client simulated.Client) (common.Hash, error) + WaitTransaction(ctx context.Context, txHash common.Hash, client simulated.Client) error +} + +type WalletConfig struct { + PrivateKey string `json:"private_key" yaml:"private_key" comment:"If Operator is empty and not multi sign wallet, then it is Address's private key, otherwise it is Operator's private key"` + Address common.Address `json:"address" yaml:"address" comment:"Need to monitor address"` + Operator Operator `json:"operator" yaml:"operator" comment:"Used to isolate the monitoring address and the operation address, preventing the leakage of the monitoring address private key. If Operator is empty, it is not enabled. If it is a multi-sign wallet, it must be set"` + MultiSignType string `json:"multi_sign_type" yaml:"multi_sign_type" comment:"MultiSign type, ex: safe"` +} + +type Operator struct { + Address common.Address `json:"address"` + Operator common.Address `json:"operator"` + PrivateKey string `json:"private_key"` + MultiSignType string `json:"multi_sign_type" yaml:"multi_sign_type" comment:"MultiSign type, ex: safe"` +} + +func (o Operator) IsMultiSign() bool { + return o.MultiSignType == string(MultiSignTypeSafe) +} + +func NewWallets(conf WalletConfig) Wallets { + wallet := Get(conf.MultiSignType) + if wallet == nil { + logrus.Fatalf("wallet type '%s' not found", conf.MultiSignType) + } + return wallet(conf) +}