From 515d9565637494a156c25b8197424ded34750842 Mon Sep 17 00:00:00 2001 From: Kozer4 Date: Tue, 28 Jan 2025 15:18:11 +0200 Subject: [PATCH] feat(SUI): add SUI --- .cspell.json | 6 +- .editorconfig | 2 +- .prettierrc.json | 3 + eslint.config.mjs | 2 +- examples/package.json | 14 +- examples/pnpm-lock.yaml | 381 ++++ .../examples/bridge/sui/sui-build-send-tx.ts | 53 + .../examples/bridge/sui/sui-build-swap-tx.ts | 54 + .../general/sui/sui-get-token-balance.ts | 34 + .../sui/get-amount-to-be-withdrawn.ts | 25 + .../sui/get-liquidity-balance.ts | 29 + .../sui/get-lp-amount-on-deposit.ts | 25 + .../sui/sui-build-claim-rewards-tx.ts | 33 + .../sui/sui-build-deposit-tx.ts | 35 + .../sui/sui-build-withdraw-tx.ts | 35 + examples/src/utils/sui.ts | 26 + examples/tsconfig.json | 2 +- package.json | 1 + pnpm-lock.yaml | 156 ++ src/__tests__/client/core-api/index.test.ts | 4 +- src/__tests__/index.test.ts | 26 +- src/__tests__/mock/bridge/models/bridge.ts | 2 +- src/__tests__/mock/utils.ts | 2 +- .../services/bridge/trx/index.test.ts | 2 +- .../services/liquidity-pool/trx/index.test.ts | 8 +- src/__tests__/utils/calculation/index.test.ts | 4 +- src/chains/chain.enums.ts | 6 + src/chains/index.ts | 6 + src/client/core-api/api-client.ts | 2 +- src/client/core-api/core-api-mapper.ts | 1 + src/client/core-api/core-api.model.ts | 3 +- src/client/core-api/core-client-filtered.ts | 4 +- .../core-api/core-client-pool-info-caching.ts | 2 +- src/configs/mainnet.ts | 3 +- src/exceptions/exceptions.ts | 4 +- src/index.ts | 50 +- src/models/index.ts | 1 + src/services/bridge/evm/index.ts | 57 +- .../get-cctp-sol-token-recipient-address.ts | 69 + src/services/bridge/index.ts | 14 +- src/services/bridge/models/bridge.model.ts | 6 +- .../bridge/raw-bridge-transaction-builder.ts | 8 +- src/services/bridge/sol/index.ts | 42 +- src/services/bridge/sol/jupiter.ts | 4 +- src/services/bridge/srb/index.ts | 2 +- src/services/bridge/sui/index.ts | 315 +++ src/services/bridge/trx/index.ts | 6 +- src/services/bridge/utils.ts | 103 +- src/services/index.ts | 76 +- src/services/liquidity-pool/evm/index.ts | 14 +- src/services/liquidity-pool/index.ts | 20 +- .../raw-pool-transaction-builder.ts | 10 +- src/services/liquidity-pool/sol/index.ts | 10 +- src/services/liquidity-pool/srb/index.ts | 2 +- src/services/liquidity-pool/sui/index.ts | 281 +++ src/services/liquidity-pool/trx/index.ts | 10 +- src/services/models/index.ts | 1 + src/services/models/srb/bridge-contract.ts | 48 +- .../models/srb/gas-oracle-contract.ts | 20 +- src/services/models/srb/messenger-contract.ts | 36 +- src/services/models/srb/pool-contract.ts | 32 +- src/services/models/srb/token-contract.ts | 26 +- src/services/models/sui/.eslintrc.json | 7 + .../_dependencies/source/0x1/ascii/structs.ts | 342 +++ .../source/0x1/bit-vector/structs.ts | 191 ++ .../source/0x1/fixed-point32/structs.ts | 180 ++ .../sui/_dependencies/source/0x1/index.ts | 4 + .../sui/_dependencies/source/0x1/init.ts | 22 + .../source/0x1/option/structs.ts | 233 ++ .../source/0x1/string/structs.ts | 183 ++ .../source/0x1/type-name/structs.ts | 181 ++ .../source/0x1/uq32-32/structs.ts | 180 ++ .../source/0x1/uq64-64/structs.ts | 180 ++ .../burn-message/structs.ts | 221 ++ .../deposit-for-burn/structs.ts | 538 +++++ .../handle-receive-message/structs.ts | 203 ++ .../index.ts | 4 + .../init.ts | 16 + .../structs.ts | 183 ++ .../state/structs.ts | 268 +++ .../index.ts | 4 + .../init.ts | 12 + .../mint-allowance/structs.ts | 227 ++ .../treasury/structs.ts | 848 +++++++ .../index.ts | 4 + .../init.ts | 13 + .../message/structs.ts | 248 +++ .../receive-message/structs.ts | 628 ++++++ .../state/structs.ts | 270 +++ .../bytes20/structs.ts | 183 ++ .../bytes32/structs.ts | 183 ++ .../consumed-vaas/structs.ts | 184 ++ .../cursor/structs.ts | 223 ++ .../emitter/structs.ts | 352 +++ .../external-address/structs.ts | 181 ++ .../fee-collector/structs.ts | 192 ++ .../guardian-set/structs.ts | 200 ++ .../guardian/structs.ts | 181 ++ .../index.ts | 4 + .../init.ts | 34 + .../publish-message/structs.ts | 411 ++++ .../set/structs.ts | 391 ++++ .../state/structs.ts | 262 +++ .../vaa/structs.ts | 249 +++ .../models/sui/_framework/init-loader.ts | 33 + src/services/models/sui/_framework/loader.ts | 85 + src/services/models/sui/_framework/reified.ts | 434 ++++ src/services/models/sui/_framework/util.ts | 378 ++++ src/services/models/sui/_framework/vector.ts | 120 + .../sui/bridge/another-bridge/functions.ts | 92 + .../sui/bridge/another-bridge/structs.ts | 200 ++ .../sui/bridge/bridge-interface/functions.ts | 722 ++++++ .../models/sui/bridge/bridge/functions.ts | 423 ++++ .../models/sui/bridge/bridge/structs.ts | 769 +++++++ .../models/sui/bridge/events/functions.ts | 157 ++ .../models/sui/bridge/events/structs.ts | 1758 +++++++++++++++ src/services/models/sui/bridge/index.ts | 41 + src/services/models/sui/bridge/init.ts | 32 + .../sui/bridge/pool-rewards/functions.ts | 116 + .../models/sui/bridge/pool-rewards/structs.ts | 258 +++ .../models/sui/bridge/pool-state/functions.ts | 215 ++ .../models/sui/bridge/pool-state/structs.ts | 257 +++ .../models/sui/bridge/pool/functions.ts | 285 +++ .../models/sui/bridge/pool/structs.ts | 611 ++++++ .../sui/bridge/user-deposit/functions.ts | 77 + .../models/sui/bridge/user-deposit/structs.ts | 242 ++ .../cctp-bridge-interface/functions.ts | 259 +++ .../sui/cctp-bridge/cctp-bridge/functions.ts | 272 +++ .../sui/cctp-bridge/cctp-bridge/structs.ts | 583 +++++ .../sui/cctp-bridge/events/functions.ts | 81 + .../models/sui/cctp-bridge/events/structs.ts | 807 +++++++ src/services/models/sui/cctp-bridge/index.ts | 33 + src/services/models/sui/cctp-bridge/init.ts | 16 + .../functions.ts | 10 + .../structs.ts | 183 ++ .../gas-oracle-interface/functions.ts | 182 ++ .../sui/gas-oracle/gas-oracle/functions.ts | 179 ++ .../sui/gas-oracle/gas-oracle/structs.ts | 529 +++++ src/services/models/sui/gas-oracle/index.ts | 33 + src/services/models/sui/gas-oracle/init.ts | 9 + .../models/sui/messenger/events/functions.ts | 18 + .../models/sui/messenger/events/structs.ts | 344 +++ src/services/models/sui/messenger/index.ts | 33 + src/services/models/sui/messenger/init.ts | 11 + .../messenger-interface/functions.ts | 203 ++ .../sui/messenger/messenger/functions.ts | 198 ++ .../models/sui/messenger/messenger/structs.ts | 427 ++++ .../models/sui/sui/address/functions.ts | 74 + .../sui/sui/authenticator-state/functions.ts | 132 ++ .../sui/sui/authenticator-state/structs.ts | 901 ++++++++ src/services/models/sui/sui/bag/functions.ts | 108 + src/services/models/sui/sui/bag/structs.ts | 189 ++ .../models/sui/sui/balance/functions.ts | 128 ++ .../models/sui/sui/balance/structs.ts | 427 ++++ src/services/models/sui/sui/bcs/functions.ts | 208 ++ src/services/models/sui/sui/bcs/structs.ts | 183 ++ .../models/sui/sui/bls12381/functions.ts | 428 ++++ .../models/sui/sui/bls12381/structs.ts | 832 +++++++ .../models/sui/sui/borrow/functions.ts | 42 + src/services/models/sui/sui/borrow/structs.ts | 408 ++++ .../models/sui/sui/clock/functions.ts | 30 + src/services/models/sui/sui/clock/structs.ts | 189 ++ src/services/models/sui/sui/coin/functions.ts | 554 +++++ src/services/models/sui/sui/coin/structs.ts | 1538 +++++++++++++ .../models/sui/sui/config/functions.ts | 172 ++ src/services/models/sui/sui/config/structs.ts | 662 ++++++ .../models/sui/sui/deny-list/functions.ts | 307 +++ .../models/sui/sui/deny-list/structs.ts | 1227 +++++++++++ .../models/sui/sui/display/functions.ts | 164 ++ .../models/sui/sui/display/structs.ts | 668 ++++++ .../models/sui/sui/dynamic-field/functions.ts | 216 ++ .../models/sui/sui/dynamic-field/structs.ts | 258 +++ .../sui/sui/dynamic-object-field/functions.ts | 170 ++ .../sui/sui/dynamic-object-field/structs.ts | 229 ++ .../models/sui/sui/ecdsa-k1/functions.ts | 43 + .../models/sui/sui/ecdsa-r1/functions.ts | 36 + .../models/sui/sui/ecvrf/functions.ts | 23 + .../models/sui/sui/ed25519/functions.ts | 21 + .../models/sui/sui/event/functions.ts | 12 + .../models/sui/sui/groth16/functions.ts | 132 ++ .../models/sui/sui/groth16/structs.ts | 692 ++++++ .../models/sui/sui/group-ops/functions.ts | 312 +++ .../models/sui/sui/group-ops/structs.ts | 228 ++ src/services/models/sui/sui/hash/functions.ts | 18 + src/services/models/sui/sui/hex/functions.ts | 25 + src/services/models/sui/sui/hmac/functions.ts | 16 + src/services/models/sui/sui/index.ts | 4 + src/services/models/sui/sui/init.ts | 138 ++ .../sui/sui/kiosk-extension/functions.ts | 177 ++ .../models/sui/sui/kiosk-extension/structs.ts | 407 ++++ .../models/sui/sui/kiosk/functions.ts | 490 +++++ src/services/models/sui/sui/kiosk/structs.ts | 1939 +++++++++++++++++ .../models/sui/sui/linked-table/functions.ts | 182 ++ .../models/sui/sui/linked-table/structs.ts | 501 +++++ src/services/models/sui/sui/math/functions.ts | 78 + .../models/sui/sui/object-bag/functions.ts | 124 ++ .../models/sui/sui/object-bag/structs.ts | 189 ++ .../models/sui/sui/object-table/functions.ts | 115 + .../models/sui/sui/object-table/structs.ts | 252 +++ .../models/sui/sui/object/functions.ts | 175 ++ src/services/models/sui/sui/object/structs.ts | 344 +++ .../models/sui/sui/package/functions.ts | 192 ++ .../models/sui/sui/package/structs.ts | 746 +++++++ src/services/models/sui/sui/pay/functions.ts | 105 + .../models/sui/sui/poseidon/functions.ts | 21 + .../sui/sui/priority-queue/functions.ts | 100 + .../models/sui/sui/priority-queue/structs.ts | 432 ++++ .../models/sui/sui/random/functions.ts | 229 ++ src/services/models/sui/sui/random/structs.ts | 559 +++++ src/services/models/sui/sui/sui/functions.ts | 20 + src/services/models/sui/sui/sui/structs.ts | 180 ++ .../models/sui/sui/table-vec/functions.ts | 126 ++ .../models/sui/sui/table-vec/structs.ts | 229 ++ .../models/sui/sui/table/functions.ts | 110 + src/services/models/sui/sui/table/structs.ts | 248 +++ .../models/sui/sui/token/functions.ts | 496 +++++ src/services/models/sui/sui/token/structs.ts | 1348 ++++++++++++ .../sui/sui/transfer-policy/functions.ts | 214 ++ .../models/sui/sui/transfer-policy/structs.ts | 1322 +++++++++++ .../models/sui/sui/transfer/functions.ts | 144 ++ .../models/sui/sui/transfer/structs.ts | 234 ++ .../models/sui/sui/tx-context/functions.ts | 58 + .../models/sui/sui/tx-context/structs.ts | 218 ++ .../models/sui/sui/types/functions.ts | 12 + src/services/models/sui/sui/url/functions.ts | 38 + src/services/models/sui/sui/url/structs.ts | 181 ++ src/services/models/sui/sui/vdf/functions.ts | 59 + .../models/sui/sui/vec-map/functions.ts | 217 ++ .../models/sui/sui/vec-map/structs.ts | 466 ++++ .../models/sui/sui/vec-set/functions.ts | 125 ++ .../models/sui/sui/vec-set/structs.ts | 223 ++ .../models/sui/sui/versioned/functions.ts | 76 + .../models/sui/sui/versioned/structs.ts | 360 +++ .../sui/sui/zklogin-verified-id/functions.ts | 114 + .../sui/sui/zklogin-verified-id/structs.ts | 225 ++ .../sui/zklogin-verified-issuer/functions.ts | 72 + .../sui/zklogin-verified-issuer/structs.ts | 201 ++ .../models/sui/utils/bytes32/functions.ts | 108 + .../models/sui/utils/bytes32/structs.ts | 183 ++ .../sui/utils/fee-collector/functions.ts | 55 + .../models/sui/utils/fee-collector/structs.ts | 228 ++ src/services/models/sui/utils/index.ts | 33 + src/services/models/sui/utils/init.ts | 18 + .../models/sui/utils/message/functions.ts | 111 + .../models/sui/utils/message/structs.ts | 181 ++ .../sui/utils/messenger-protocol/functions.ts | 25 + .../sui/utils/messenger-protocol/structs.ts | 180 ++ .../models/sui/utils/set/functions.ts | 59 + src/services/models/sui/utils/set/structs.ts | 391 ++++ .../models/sui/utils/version/functions.ts | 45 + .../models/sui/utils/version/structs.ts | 232 ++ .../wormhole-messenger/events/functions.ts | 28 + .../sui/wormhole-messenger/events/structs.ts | 360 +++ .../models/sui/wormhole-messenger/index.ts | 33 + .../models/sui/wormhole-messenger/init.ts | 11 + .../wh-messenger-interface/functions.ts | 219 ++ .../wormhole-messenger/functions.ts | 237 ++ .../wormhole-messenger/structs.ts | 430 ++++ src/services/token/evm/index.ts | 4 +- src/services/token/index.ts | 20 +- src/services/token/sol/index.ts | 4 +- src/services/token/srb/index.ts | 8 +- src/services/token/sui/index.ts | 61 + src/services/token/trx/index.ts | 6 +- src/services/utils/calculation/index.ts | 2 +- src/services/utils/sol/accounts.ts | 34 +- src/services/utils/sol/anchor-provider.ts | 2 +- src/services/utils/sol/compute-budget.ts | 12 +- src/services/utils/sol/index.ts | 6 +- src/services/utils/sui/coins.ts | 43 + src/services/utils/sui/paginated.ts | 20 + src/services/utils/sui/view.ts | 33 + src/tokens-info/tokens-info.model.ts | 40 + src/utils/calculation/index.ts | 10 +- .../calculation/swap-and-bridge-details.ts | 6 +- .../calculation/swap-and-bridge-fee-calc.ts | 24 +- src/utils/index.ts | 2 +- src/utils/sol/index.ts | 2 +- src/utils/sol/utils.ts | 6 +- src/utils/srb/index.ts | 8 +- src/utils/utils.ts | 12 +- tsconfig.json | 1 - 282 files changed, 52534 insertions(+), 409 deletions(-) create mode 100644 .prettierrc.json create mode 100644 examples/src/examples/bridge/sui/sui-build-send-tx.ts create mode 100644 examples/src/examples/bridge/sui/sui-build-swap-tx.ts create mode 100644 examples/src/examples/general/sui/sui-get-token-balance.ts create mode 100644 examples/src/examples/liquidity-pool/sui/get-amount-to-be-withdrawn.ts create mode 100644 examples/src/examples/liquidity-pool/sui/get-liquidity-balance.ts create mode 100644 examples/src/examples/liquidity-pool/sui/get-lp-amount-on-deposit.ts create mode 100644 examples/src/examples/liquidity-pool/sui/sui-build-claim-rewards-tx.ts create mode 100644 examples/src/examples/liquidity-pool/sui/sui-build-deposit-tx.ts create mode 100644 examples/src/examples/liquidity-pool/sui/sui-build-withdraw-tx.ts create mode 100644 examples/src/utils/sui.ts create mode 100644 src/services/bridge/get-cctp-sol-token-recipient-address.ts create mode 100644 src/services/bridge/sui/index.ts create mode 100644 src/services/liquidity-pool/sui/index.ts create mode 100644 src/services/models/sui/.eslintrc.json create mode 100644 src/services/models/sui/_dependencies/source/0x1/ascii/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0x1/bit-vector/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0x1/fixed-point32/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0x1/index.ts create mode 100644 src/services/models/sui/_dependencies/source/0x1/init.ts create mode 100644 src/services/models/sui/_dependencies/source/0x1/option/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0x1/string/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0x1/type-name/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0x1/uq32-32/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0x1/uq64-64/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/burn-message/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/deposit-for-burn/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/handle-receive-message/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/index.ts create mode 100644 src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/init.ts create mode 100644 src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/message-transmitter-authenticator/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/state/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917/index.ts create mode 100644 src/services/models/sui/_dependencies/source/0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917/init.ts create mode 100644 src/services/models/sui/_dependencies/source/0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917/mint-allowance/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917/treasury/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/index.ts create mode 100644 src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/init.ts create mode 100644 src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/message/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/receive-message/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/state/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/bytes20/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/bytes32/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/consumed-vaas/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/cursor/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/emitter/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/external-address/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/fee-collector/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/guardian-set/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/guardian/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/index.ts create mode 100644 src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/init.ts create mode 100644 src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/publish-message/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/set/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/state/structs.ts create mode 100644 src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/vaa/structs.ts create mode 100644 src/services/models/sui/_framework/init-loader.ts create mode 100644 src/services/models/sui/_framework/loader.ts create mode 100644 src/services/models/sui/_framework/reified.ts create mode 100644 src/services/models/sui/_framework/util.ts create mode 100644 src/services/models/sui/_framework/vector.ts create mode 100644 src/services/models/sui/bridge/another-bridge/functions.ts create mode 100644 src/services/models/sui/bridge/another-bridge/structs.ts create mode 100644 src/services/models/sui/bridge/bridge-interface/functions.ts create mode 100644 src/services/models/sui/bridge/bridge/functions.ts create mode 100644 src/services/models/sui/bridge/bridge/structs.ts create mode 100644 src/services/models/sui/bridge/events/functions.ts create mode 100644 src/services/models/sui/bridge/events/structs.ts create mode 100644 src/services/models/sui/bridge/index.ts create mode 100644 src/services/models/sui/bridge/init.ts create mode 100644 src/services/models/sui/bridge/pool-rewards/functions.ts create mode 100644 src/services/models/sui/bridge/pool-rewards/structs.ts create mode 100644 src/services/models/sui/bridge/pool-state/functions.ts create mode 100644 src/services/models/sui/bridge/pool-state/structs.ts create mode 100644 src/services/models/sui/bridge/pool/functions.ts create mode 100644 src/services/models/sui/bridge/pool/structs.ts create mode 100644 src/services/models/sui/bridge/user-deposit/functions.ts create mode 100644 src/services/models/sui/bridge/user-deposit/structs.ts create mode 100644 src/services/models/sui/cctp-bridge/cctp-bridge-interface/functions.ts create mode 100644 src/services/models/sui/cctp-bridge/cctp-bridge/functions.ts create mode 100644 src/services/models/sui/cctp-bridge/cctp-bridge/structs.ts create mode 100644 src/services/models/sui/cctp-bridge/events/functions.ts create mode 100644 src/services/models/sui/cctp-bridge/events/structs.ts create mode 100644 src/services/models/sui/cctp-bridge/index.ts create mode 100644 src/services/models/sui/cctp-bridge/init.ts create mode 100644 src/services/models/sui/cctp-bridge/message-transmitter-authenticator/functions.ts create mode 100644 src/services/models/sui/cctp-bridge/message-transmitter-authenticator/structs.ts create mode 100644 src/services/models/sui/gas-oracle/gas-oracle-interface/functions.ts create mode 100644 src/services/models/sui/gas-oracle/gas-oracle/functions.ts create mode 100644 src/services/models/sui/gas-oracle/gas-oracle/structs.ts create mode 100644 src/services/models/sui/gas-oracle/index.ts create mode 100644 src/services/models/sui/gas-oracle/init.ts create mode 100644 src/services/models/sui/messenger/events/functions.ts create mode 100644 src/services/models/sui/messenger/events/structs.ts create mode 100644 src/services/models/sui/messenger/index.ts create mode 100644 src/services/models/sui/messenger/init.ts create mode 100644 src/services/models/sui/messenger/messenger-interface/functions.ts create mode 100644 src/services/models/sui/messenger/messenger/functions.ts create mode 100644 src/services/models/sui/messenger/messenger/structs.ts create mode 100644 src/services/models/sui/sui/address/functions.ts create mode 100644 src/services/models/sui/sui/authenticator-state/functions.ts create mode 100644 src/services/models/sui/sui/authenticator-state/structs.ts create mode 100644 src/services/models/sui/sui/bag/functions.ts create mode 100644 src/services/models/sui/sui/bag/structs.ts create mode 100644 src/services/models/sui/sui/balance/functions.ts create mode 100644 src/services/models/sui/sui/balance/structs.ts create mode 100644 src/services/models/sui/sui/bcs/functions.ts create mode 100644 src/services/models/sui/sui/bcs/structs.ts create mode 100644 src/services/models/sui/sui/bls12381/functions.ts create mode 100644 src/services/models/sui/sui/bls12381/structs.ts create mode 100644 src/services/models/sui/sui/borrow/functions.ts create mode 100644 src/services/models/sui/sui/borrow/structs.ts create mode 100644 src/services/models/sui/sui/clock/functions.ts create mode 100644 src/services/models/sui/sui/clock/structs.ts create mode 100644 src/services/models/sui/sui/coin/functions.ts create mode 100644 src/services/models/sui/sui/coin/structs.ts create mode 100644 src/services/models/sui/sui/config/functions.ts create mode 100644 src/services/models/sui/sui/config/structs.ts create mode 100644 src/services/models/sui/sui/deny-list/functions.ts create mode 100644 src/services/models/sui/sui/deny-list/structs.ts create mode 100644 src/services/models/sui/sui/display/functions.ts create mode 100644 src/services/models/sui/sui/display/structs.ts create mode 100644 src/services/models/sui/sui/dynamic-field/functions.ts create mode 100644 src/services/models/sui/sui/dynamic-field/structs.ts create mode 100644 src/services/models/sui/sui/dynamic-object-field/functions.ts create mode 100644 src/services/models/sui/sui/dynamic-object-field/structs.ts create mode 100644 src/services/models/sui/sui/ecdsa-k1/functions.ts create mode 100644 src/services/models/sui/sui/ecdsa-r1/functions.ts create mode 100644 src/services/models/sui/sui/ecvrf/functions.ts create mode 100644 src/services/models/sui/sui/ed25519/functions.ts create mode 100644 src/services/models/sui/sui/event/functions.ts create mode 100644 src/services/models/sui/sui/groth16/functions.ts create mode 100644 src/services/models/sui/sui/groth16/structs.ts create mode 100644 src/services/models/sui/sui/group-ops/functions.ts create mode 100644 src/services/models/sui/sui/group-ops/structs.ts create mode 100644 src/services/models/sui/sui/hash/functions.ts create mode 100644 src/services/models/sui/sui/hex/functions.ts create mode 100644 src/services/models/sui/sui/hmac/functions.ts create mode 100644 src/services/models/sui/sui/index.ts create mode 100644 src/services/models/sui/sui/init.ts create mode 100644 src/services/models/sui/sui/kiosk-extension/functions.ts create mode 100644 src/services/models/sui/sui/kiosk-extension/structs.ts create mode 100644 src/services/models/sui/sui/kiosk/functions.ts create mode 100644 src/services/models/sui/sui/kiosk/structs.ts create mode 100644 src/services/models/sui/sui/linked-table/functions.ts create mode 100644 src/services/models/sui/sui/linked-table/structs.ts create mode 100644 src/services/models/sui/sui/math/functions.ts create mode 100644 src/services/models/sui/sui/object-bag/functions.ts create mode 100644 src/services/models/sui/sui/object-bag/structs.ts create mode 100644 src/services/models/sui/sui/object-table/functions.ts create mode 100644 src/services/models/sui/sui/object-table/structs.ts create mode 100644 src/services/models/sui/sui/object/functions.ts create mode 100644 src/services/models/sui/sui/object/structs.ts create mode 100644 src/services/models/sui/sui/package/functions.ts create mode 100644 src/services/models/sui/sui/package/structs.ts create mode 100644 src/services/models/sui/sui/pay/functions.ts create mode 100644 src/services/models/sui/sui/poseidon/functions.ts create mode 100644 src/services/models/sui/sui/priority-queue/functions.ts create mode 100644 src/services/models/sui/sui/priority-queue/structs.ts create mode 100644 src/services/models/sui/sui/random/functions.ts create mode 100644 src/services/models/sui/sui/random/structs.ts create mode 100644 src/services/models/sui/sui/sui/functions.ts create mode 100644 src/services/models/sui/sui/sui/structs.ts create mode 100644 src/services/models/sui/sui/table-vec/functions.ts create mode 100644 src/services/models/sui/sui/table-vec/structs.ts create mode 100644 src/services/models/sui/sui/table/functions.ts create mode 100644 src/services/models/sui/sui/table/structs.ts create mode 100644 src/services/models/sui/sui/token/functions.ts create mode 100644 src/services/models/sui/sui/token/structs.ts create mode 100644 src/services/models/sui/sui/transfer-policy/functions.ts create mode 100644 src/services/models/sui/sui/transfer-policy/structs.ts create mode 100644 src/services/models/sui/sui/transfer/functions.ts create mode 100644 src/services/models/sui/sui/transfer/structs.ts create mode 100644 src/services/models/sui/sui/tx-context/functions.ts create mode 100644 src/services/models/sui/sui/tx-context/structs.ts create mode 100644 src/services/models/sui/sui/types/functions.ts create mode 100644 src/services/models/sui/sui/url/functions.ts create mode 100644 src/services/models/sui/sui/url/structs.ts create mode 100644 src/services/models/sui/sui/vdf/functions.ts create mode 100644 src/services/models/sui/sui/vec-map/functions.ts create mode 100644 src/services/models/sui/sui/vec-map/structs.ts create mode 100644 src/services/models/sui/sui/vec-set/functions.ts create mode 100644 src/services/models/sui/sui/vec-set/structs.ts create mode 100644 src/services/models/sui/sui/versioned/functions.ts create mode 100644 src/services/models/sui/sui/versioned/structs.ts create mode 100644 src/services/models/sui/sui/zklogin-verified-id/functions.ts create mode 100644 src/services/models/sui/sui/zklogin-verified-id/structs.ts create mode 100644 src/services/models/sui/sui/zklogin-verified-issuer/functions.ts create mode 100644 src/services/models/sui/sui/zklogin-verified-issuer/structs.ts create mode 100644 src/services/models/sui/utils/bytes32/functions.ts create mode 100644 src/services/models/sui/utils/bytes32/structs.ts create mode 100644 src/services/models/sui/utils/fee-collector/functions.ts create mode 100644 src/services/models/sui/utils/fee-collector/structs.ts create mode 100644 src/services/models/sui/utils/index.ts create mode 100644 src/services/models/sui/utils/init.ts create mode 100644 src/services/models/sui/utils/message/functions.ts create mode 100644 src/services/models/sui/utils/message/structs.ts create mode 100644 src/services/models/sui/utils/messenger-protocol/functions.ts create mode 100644 src/services/models/sui/utils/messenger-protocol/structs.ts create mode 100644 src/services/models/sui/utils/set/functions.ts create mode 100644 src/services/models/sui/utils/set/structs.ts create mode 100644 src/services/models/sui/utils/version/functions.ts create mode 100644 src/services/models/sui/utils/version/structs.ts create mode 100644 src/services/models/sui/wormhole-messenger/events/functions.ts create mode 100644 src/services/models/sui/wormhole-messenger/events/structs.ts create mode 100644 src/services/models/sui/wormhole-messenger/index.ts create mode 100644 src/services/models/sui/wormhole-messenger/init.ts create mode 100644 src/services/models/sui/wormhole-messenger/wh-messenger-interface/functions.ts create mode 100644 src/services/models/sui/wormhole-messenger/wormhole-messenger/functions.ts create mode 100644 src/services/models/sui/wormhole-messenger/wormhole-messenger/structs.ts create mode 100644 src/services/token/sui/index.ts create mode 100644 src/services/utils/sui/coins.ts create mode 100644 src/services/utils/sui/paginated.ts create mode 100644 src/services/utils/sui/view.ts diff --git a/.cspell.json b/.cspell.json index 2de86fe9..3440709e 100644 --- a/.cspell.json +++ b/.cspell.json @@ -47,7 +47,8 @@ "Vals", "Amoy", "Celo", - "crossrate" + "crossrate", + "mysten" ], "flagWords": [], "ignorePaths": [ @@ -58,8 +59,9 @@ "node_modules/**", "src/configs/", "src/__tests__/services/liquidity-pool/sol/data/", - "src/services/models/srb/", "src/services/models/abi/", + "src/services/models/srb/", + "src/services/models/sui/", "src/services/utils/srb/assembled-tx.ts" ] } diff --git a/.editorconfig b/.editorconfig index 1997e4f9..bf502056 100644 --- a/.editorconfig +++ b/.editorconfig @@ -7,6 +7,6 @@ indent_style = space indent_size = 2 insert_final_newline = true # trim_trailing_whitespace = true -max_line_length = off +# max_line_length = off max_line_length = 120 diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 00000000..d598c0af --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,3 @@ +{ + "trailingComma" : "es5" +} \ No newline at end of file diff --git a/eslint.config.mjs b/eslint.config.mjs index 840011a5..51c5258d 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -17,7 +17,7 @@ const compat = new FlatCompat({ }); export default [{ - ignores: ["scripts/*", "**/esbuild-hook.js"], + ignores: ["scripts/*", "**/esbuild-hook.js", "src/services/models/sui/*"], }, ...fixupConfigRules(compat.extends( "eslint:recommended", "plugin:eslint-comments/recommended", diff --git a/examples/package.json b/examples/package.json index 7e119fd1..634bb86a 100644 --- a/examples/package.json +++ b/examples/package.json @@ -4,7 +4,7 @@ "main": "index.js", "description": "", "scripts": { - "pnpmi": "cd ../ && pnpm build && cd examples && rm -rf node_modules && pnpm i", + "pnpmi": "cd ../ && pnpm i && pnpm build && cd examples && rm -rf node_modules && pnpm i", "compile": "tsc", "prettier": "prettier \"src/**/*.ts\" --write", "lint": "eslint src --ext .ts", @@ -12,11 +12,14 @@ "run:getTokensInfo": "tsx src/examples/get-tokens-info.ts", + "run:test": "tsx src/examples/test.ts", "run:bridge:evm:send": "tsx src/examples/bridge/evm/evm-build-send-tx.ts", "run:bridge:evm:sendWithStables": "tsx src/examples/bridge/evm/evm-build-send-tx-gas-fee-with-stables.ts", "run:bridge:evm:swap": "tsx src/examples/bridge/evm/evm-build-swap-tx.ts", - "run:bridge:solana:send": "tsx src/examples/bridge/solana/sol-build-send-tx.ts", + "run:bridge:solana:send": "pnpm pnpmi && tsx src/examples/bridge/solana/sol-build-send-tx.ts", "run:bridge:solana:swap": "tsx src/examples/bridge/solana/sol-build-swap-tx.ts", + "run:bridge:sui:send": "tsx src/examples/bridge/sui/sui-build-send-tx.ts", + "run:bridge:sui:swap": "tsx src/examples/bridge/sui/sui-build-swap-tx.ts", "run:bridge:srb:fullExample": "tsx src/examples/bridge/srb/srb-send-full-example.ts", "run:bridge:trx:send": "tsx src/examples/bridge/trx/trx-build-send-tx.ts", "run:bridge:trx:sendWithStables": "tsx src/examples/bridge/trx/trx-build-send-tx-gas-fee-with-stables.ts", @@ -30,6 +33,7 @@ "run:general:evm:approveTokens": "tsx src/examples/general/evm/evm-approve-tokens.ts", "run:general:evm:getTokenBalance": "tsx src/examples/general/evm/evm-get-token-balance.ts", "run:general:solana:getTokenBalance": "tsx src/examples/general/solana/sol-get-token-balance.ts", + "run:general:sui:getTokenBalance": "tsx src/examples/general/sui/sui-get-token-balance.ts", "run:liquidity-pool:evm:claimRewards": "tsx src/examples/liquidity-pool/evm/evm-build-claim-rewards-tx.ts", "run:liquidity-pool:evm:deposit": "tsx src/examples/liquidity-pool/evm/evm-build-deposit-tx.ts", @@ -43,6 +47,12 @@ "run:liquidity-pool:solana:getAmountToBeWithdrawn": "tsx src/examples/liquidity-pool/solana/get-amount-to-be-withdrawn.ts", "run:liquidity-pool:solana:getBalance": "tsx src/examples/liquidity-pool/solana/get-liquidity-balance.ts", "run:liquidity-pool:solana:getLPamountOnDeposit": "tsx src/examples/liquidity-pool/solana/get-lp-amount-on-deposit.ts", + "run:liquidity-pool:sui:getAmountToBeWithdrawn": "tsx src/examples/liquidity-pool/sui/get-amount-to-be-withdrawn.ts", + "run:liquidity-pool:sui:getBalance": "tsx src/examples/liquidity-pool/sui/get-liquidity-balance.ts", + "run:liquidity-pool:sui:getLPamountOnDeposit": "tsx src/examples/liquidity-pool/sui/get-lp-amount-on-deposit.ts", + "run:liquidity-pool:sui:claimRewards": "tsx src/examples/liquidity-pool/sui/sui-build-claim-rewards-tx.ts", + "run:liquidity-pool:sui:deposit": "tsx src/examples/liquidity-pool/sui/sui-build-deposit-tx.ts", + "run:liquidity-pool:sui:withdraw": "tsx src/examples/liquidity-pool/sui/sui-build-withdraw-tx.ts", "run:liquidity-pool:trx:claimRewards": "tsx src/examples/liquidity-pool/trx/trx-build-claim-rewards-tx.ts", "run:liquidity-pool:trx:deposit": "tsx src/examples/liquidity-pool/trx/trx-build-deposit-tx.ts", "run:liquidity-pool:trx:withdraw": "tsx src/examples/liquidity-pool/trx/trx-build-withdraw-tx.ts", diff --git a/examples/pnpm-lock.yaml b/examples/pnpm-lock.yaml index 2944bb11..56599a7b 100644 --- a/examples/pnpm-lock.yaml +++ b/examples/pnpm-lock.yaml @@ -66,6 +66,20 @@ importers: packages: + '@0no-co/graphql.web@1.0.13': + resolution: {integrity: sha512-jqYxOevheVTU1S36ZdzAkJIdvRp2m3OYIG5SEoKDw5NI8eVwkoI0D/Q3DYNGmXCxkA6CQuoa7zvMiDPTLqUNuw==} + peerDependencies: + graphql: ^14.0.0 || ^15.0.0 || ^16.0.0 + peerDependenciesMeta: + graphql: + optional: true + + '@0no-co/graphqlsp@1.12.16': + resolution: {integrity: sha512-B5pyYVH93Etv7xjT6IfB7QtMBdaaC07yjbhN6v8H7KgFStMkPvi+oWYBTibMFRMY89qwc9H8YixXg8SXDVgYWw==} + peerDependencies: + graphql: ^15.5.0 || ^16.0.0 || ^17.0.0 + typescript: ^5.0.0 + '@aashutoshrathi/word-wrap@1.2.6': resolution: {integrity: sha512-1Yjs2SvM8TflER/OD3cOjhWWOZb58A2t7wpE2S9XfBYTiIl+XFhQG2bjy4Pu1I+EAlCNUzRDYDdFwFYUKvXcIA==} engines: {node: '>=0.10.0'} @@ -350,6 +364,31 @@ packages: '@ethersproject/wordlists@5.7.0': resolution: {integrity: sha512-S2TFNJNfHWVHNE6cNDjbVlZ6MgE17MIxMbMg2zv3wn+3XSJGosL1m9ZVv3GXCf/2ymSsQ+hRI5IzoMJTG6aoVA==} + '@gql.tada/cli-utils@1.6.3': + resolution: {integrity: sha512-jFFSY8OxYeBxdKi58UzeMXG1tdm4FVjXa8WHIi66Gzu9JWtCE6mqom3a8xkmSw+mVaybFW5EN2WXf1WztJVNyQ==} + peerDependencies: + '@0no-co/graphqlsp': ^1.12.13 + '@gql.tada/svelte-support': 1.0.1 + '@gql.tada/vue-support': 1.0.1 + graphql: ^15.5.0 || ^16.0.0 || ^17.0.0 + typescript: ^5.0.0 + peerDependenciesMeta: + '@gql.tada/svelte-support': + optional: true + '@gql.tada/vue-support': + optional: true + + '@gql.tada/internal@1.0.8': + resolution: {integrity: sha512-XYdxJhtHC5WtZfdDqtKjcQ4d7R1s0d1rnlSs3OcBEUbYiPoJJfZU7tWsVXuv047Z6msvmr4ompJ7eLSK5Km57g==} + peerDependencies: + graphql: ^15.5.0 || ^16.0.0 || ^17.0.0 + typescript: ^5.0.0 + + '@graphql-typed-document-node/core@3.2.0': + resolution: {integrity: sha512-mB9oAsNCm9aM3/SOv4YtBMqZbYj10R7dkq8byBqxGY/ncFwhf2oQzMV+LCRlWoDSEBJ3COiR1yeDvMtsoOsuFQ==} + peerDependencies: + graphql: ^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0 + '@humanwhocodes/config-array@0.11.11': resolution: {integrity: sha512-N2brEuAadi0CcdeMXUkhbZB84eskAc8MEX1By6qEchoVywSgXPIjou4rYsl0V3Hj0ZnuGycGCjdNgockbzeWNA==} engines: {node: '>=10.10.0'} @@ -361,6 +400,13 @@ packages: '@humanwhocodes/object-schema@1.2.1': resolution: {integrity: sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==} + '@mysten/bcs@1.2.0': + resolution: {integrity: sha512-LuKonrGdGW7dq/EM6U2L9/as7dFwnhZnsnINzB/vu08Xfrj0qzWwpLOiXagAa5yZOPLK7anRZydMonczFkUPzA==} + + '@mysten/sui@1.18.0': + resolution: {integrity: sha512-cFh5LxXZrXb/ZAD1dkKeQxzhgRYFXreyFGmI7w/JQWwdl+/0FrHJBwaWyTmGxJ/6ZC9SlaOPOk63flN7DbUurg==} + engines: {node: '>=18'} + '@noble/curves@1.2.0': resolution: {integrity: sha512-oYclrNgRaM9SsBUBVbb8M6DTV7ZHRTKugureoYEncY5c65HOmRzvSiTE3y5CYaPYJA/GVkrhXEoF0M3Ya9PMnw==} @@ -414,6 +460,10 @@ packages: '@scure/bip39@1.3.0': resolution: {integrity: sha512-disdg7gHuTDZtY+ZdkmLpPCk7fxZSu3gBiEGuoC1XYxv9cGx3Z6cpTggCgW6odSOOIXCiDjuGejW+aJKCY/pIQ==} + '@simplewebauthn/typescript-types@7.4.0': + resolution: {integrity: sha512-8/ZjHeUPe210Bt5oyaOIGx4h8lHdsQs19BiOT44gi/jBEgK7uBGA0Fy7NRsyh777al3m6WM0mBf0UR7xd4R7WQ==} + deprecated: This package has been renamed to @simplewebauthn/types. Please install @simplewebauthn/types instead to ensure you receive future updates. + '@sindresorhus/is@4.6.0': resolution: {integrity: sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==} engines: {node: '>=10'} @@ -453,6 +503,9 @@ packages: '@stellar/stellar-sdk@13.1.0': resolution: {integrity: sha512-ARQkUdyGefXdTgwSF0eONkzv/geAqUfyfheJ9Nthz6GAr5b41fNwWW9UtE8JpXC4IpvE3t5elIUN5hKJzASN9w==} + '@suchipi/femver@1.0.0': + resolution: {integrity: sha512-bprE8+K5V+DPX7q2e2K57ImqNBdfGHDIWaGI5xHxZoxbKOuQZn4wzPiUxOAHnsUr3w3xHrWXwN7gnG/iIuEMIg==} + '@swc/helpers@0.5.15': resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==} @@ -644,6 +697,9 @@ packages: resolution: {integrity: sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==} engines: {node: '>=0.8'} + assert@2.1.0: + resolution: {integrity: sha512-eLHpSK/Y4nhMJ07gDaAzoX/XAKS8PSaojml3M0DM4JpV1LAi5JOJ/p6H/XWrl8L+DzVEvVCW1z3vWAaB9oTsQw==} + async-limiter@1.0.1: resolution: {integrity: sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ==} @@ -678,6 +734,9 @@ packages: base-x@4.0.0: resolution: {integrity: sha512-FuwxlW4H5kh37X/oW59pwTzzTKRzfrrQwhmyspRM7swOEZcHtDZSCt45U6oKgtuFE+WYPblePMVIPR4RZrh/hw==} + base-x@5.0.0: + resolution: {integrity: sha512-sMW3VGSX1QWVFA6l8U62MLKz29rRfpTlYdCqLdpLo1/Yd4zZwSbnUaDfciIAowAqvq7YFnWq9hrhdg1KYgc1lQ==} + base32.js@0.1.0: resolution: {integrity: sha512-n3TkB02ixgBOhTvANakDb4xaMXnYUVkNoRFJjQflcqMQhyEKxEHdj3E6N8t8sUQ0mjH/3/JxzlXuz3ul/J90pQ==} engines: {node: '>=0.12.0'} @@ -691,6 +750,9 @@ packages: bech32@1.1.4: resolution: {integrity: sha512-s0IrSOzLlbvX7yp4WBfPITzpAU8sqQcpsmwXDiKwrG4r491vwCO/XpejasRNl0piBMe/DvP4Tz0mIS/X1DPJBQ==} + bech32@2.0.0: + resolution: {integrity: sha512-LcknSilhIGatDAsY1ak2I8VtGaHNhgMSYVxFrGLXv+xLHytaKZKcaUJJUE7qmBr7h33o5YQwP55pMI0xmkpJwg==} + big.js@6.2.2: resolution: {integrity: sha512-y/ie+Faknx7sZA5MfGA2xKlu0GDv8RWrXGsmlteyJQ2lvoKv9GBK/fpRMc2qlSoBAgNxrixICFCBefIq8WCQpQ==} @@ -749,6 +811,9 @@ packages: bs58@5.0.0: resolution: {integrity: sha512-r+ihvQJvahgYT50JD05dyJNKlmmSlMoOGwn1lCcEzanPglg7TxYjioQUYehQ9mAR/+hOSd2jRc/Z2y5UxBymvQ==} + bs58@6.0.0: + resolution: {integrity: sha512-PD0wEnEYg6ijszw/u8s+iI3H17cTymlrwkKhDhPZq+Sokl3AU4htyBFTjAeNAlCCmg0f53g6ih3jATyCKftTfw==} + bs58check@2.1.2: resolution: {integrity: sha512-0TS1jicxdU09dwJMNZtVAfzPi6Q6QeN0pM1Fkzrjn+XYHvzMKPU3pHVpva+769iNVSfIYWf7LJ6WR+BuuMf8cA==} @@ -788,9 +853,21 @@ packages: resolution: {integrity: sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==} engines: {node: '>=8'} + call-bind-apply-helpers@1.0.1: + resolution: {integrity: sha512-BhYE+WDaywFg2TBWYNXAE+8B1ATnThNBqXHP5nQu0jWJdVvY2hvkpyB3qOmtmDePiS5/BDQ8wASEWGMWRG148g==} + engines: {node: '>= 0.4'} + call-bind@1.0.2: resolution: {integrity: sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==} + call-bind@1.0.8: + resolution: {integrity: sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww==} + engines: {node: '>= 0.4'} + + call-bound@1.0.3: + resolution: {integrity: sha512-YTd+6wGlNlPxSuri7Y6X8tY2dmm12UMH66RpKMhiX6rsk5wXXnYgbUcOt8kiS31/AjfoTOvCsE+w8nZQLQnzHA==} + engines: {node: '>= 0.4'} + callsites@3.1.0: resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} engines: {node: '>=6'} @@ -933,6 +1010,14 @@ packages: resolution: {integrity: sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==} engines: {node: '>=10'} + define-data-property@1.1.4: + resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==} + engines: {node: '>= 0.4'} + + define-properties@1.2.1: + resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} + engines: {node: '>= 0.4'} + delay@5.0.0: resolution: {integrity: sha512-ReEBKkIfe4ya47wlPYf/gu5ib6yUG0/Aez0JQZQz94kiWtRQvZIQbTiehsnwHvLSWJnQdhVeqYue7Id1dKr0qw==} engines: {node: '>=10'} @@ -967,6 +1052,10 @@ packages: resolution: {integrity: sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ==} engines: {node: '>=12'} + dunder-proto@1.0.1: + resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} + engines: {node: '>= 0.4'} + ecc-jsbn@0.1.2: resolution: {integrity: sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==} @@ -983,6 +1072,18 @@ packages: end-of-stream@1.4.4: resolution: {integrity: sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==} + es-define-property@1.0.1: + resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} + engines: {node: '>= 0.4'} + + es-errors@1.3.0: + resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} + engines: {node: '>= 0.4'} + + es-object-atoms@1.1.1: + resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==} + engines: {node: '>= 0.4'} + es5-ext@0.10.62: resolution: {integrity: sha512-BHLqn0klhEpnOKSrzn/Xsz2UIW8j+cGmo9JLzr8BiUapV8hPL9+FliFqjwr9ngW7jWdnxv6eO+/LqyhJVqgrjA==} engines: {node: '>=0.10'} @@ -1267,9 +1368,20 @@ packages: function-bind@1.1.1: resolution: {integrity: sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==} + function-bind@1.1.2: + resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + get-intrinsic@1.2.1: resolution: {integrity: sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==} + get-intrinsic@1.2.7: + resolution: {integrity: sha512-VW6Pxhsrk0KAOqs3WEd0klDiF/+V7gQOpAvY1jVU/LHmaD/kQO4523aiJuikX/QAKYiW6x8Jh+RJej1almdtCA==} + engines: {node: '>= 0.4'} + + get-proto@1.0.1: + resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} + engines: {node: '>= 0.4'} + get-stream@5.2.0: resolution: {integrity: sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==} engines: {node: '>=8'} @@ -1309,6 +1421,10 @@ packages: gopd@1.0.1: resolution: {integrity: sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==} + gopd@1.2.0: + resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} + engines: {node: '>= 0.4'} + got@11.8.6: resolution: {integrity: sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g==} engines: {node: '>=10.19.0'} @@ -1317,12 +1433,22 @@ packages: resolution: {integrity: sha512-hBv2ty9QN2RdbJJMK3hesmSkFTjVIHyIDDbssCKnSmq62edGgImJWD10Eb1k77TiV1bxloxqcFAVK8+9pkhOig==} engines: {node: '>=14.16'} + gql.tada@1.8.10: + resolution: {integrity: sha512-FrvSxgz838FYVPgZHGOSgbpOjhR+yq44rCzww3oOPJYi0OvBJjAgCiP6LEokZIYND2fUTXzQAyLgcvgw1yNP5A==} + hasBin: true + peerDependencies: + typescript: ^5.0.0 + graceful-fs@4.2.11: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} graphemer@1.4.0: resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==} + graphql@16.10.0: + resolution: {integrity: sha512-AjqGKbDGUFRKIRCP9tCKiIGHyriz2oHEbPIbEtcSLSs4YjReZOIPQQWek4+6hjw62H9QShXHyaGivGiYVLeYFQ==} + engines: {node: ^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0} + har-schema@2.0.0: resolution: {integrity: sha512-Oqluz6zhGX8cyRaTQlFMPw80bSJVG2x/cFb8ZPhUILGgHka9SsokCCOQgpveePerqidZOrT14ipqfJb7ILcW5Q==} engines: {node: '>=4'} @@ -1336,6 +1462,9 @@ packages: resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} engines: {node: '>=8'} + has-property-descriptors@1.0.2: + resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} + has-proto@1.0.1: resolution: {integrity: sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==} engines: {node: '>= 0.4'} @@ -1344,6 +1473,10 @@ packages: resolution: {integrity: sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==} engines: {node: '>= 0.4'} + has-symbols@1.1.0: + resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} + engines: {node: '>= 0.4'} + has-tostringtag@1.0.0: resolution: {integrity: sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==} engines: {node: '>= 0.4'} @@ -1359,6 +1492,10 @@ packages: hash.js@1.1.7: resolution: {integrity: sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==} + hasown@2.0.2: + resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==} + engines: {node: '>= 0.4'} + hmac-drbg@1.0.1: resolution: {integrity: sha512-Tti3gMqLdZfhOQY1Mzf/AanLiqh1WTiJgEj26ZuYQ9fbkLomzGchCws4FyrSd4VkpBfiNhaE1On+lOz894jvXg==} @@ -1450,6 +1587,10 @@ packages: resolution: {integrity: sha512-WvtOiug1VFrE9v1Cydwm+FnXd3+w9GaeVUss5W4v/SLy3UW00vP+6iNF2SdnfiBoLy4bTqVdkftNGTUeOFVsbA==} engines: {node: '>=6.5.0', npm: '>=3'} + is-nan@1.3.2: + resolution: {integrity: sha512-E+zBKpQ2t6MEo1VsonYmluk9NxGrbzpeeLC2xIViuO2EjU2xsXsBPwTr3Ykv9l08UYEVEdWeRZNouaZqF6RN0w==} + engines: {node: '>= 0.4'} + is-number@7.0.0: resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} engines: {node: '>=0.12.0'} @@ -1495,6 +1636,9 @@ packages: engines: {node: '>=8'} hasBin: true + jose@5.9.6: + resolution: {integrity: sha512-AMlnetc9+CV9asI19zHmrgS/WYsWUwCn2R7RzlbJWD7F9eWYUTGyBmU9o6PxngtLGOiDGPRu+Uc4fhKzbpteZQ==} + js-sha256@0.9.0: resolution: {integrity: sha512-sga3MHh9sgQN2+pJ9VYZ+1LPwXOxuBJBA5nrR5/ofPfuiJBE2hnjsaN8se8JznOmGLN2p49Pe5U/ttafcs/apA==} @@ -1573,6 +1717,10 @@ packages: resolution: {integrity: sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==} engines: {node: '>=10'} + math-intrinsics@1.1.0: + resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} + engines: {node: '>= 0.4'} + md5.js@1.3.5: resolution: {integrity: sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==} @@ -1739,6 +1887,18 @@ packages: object-inspect@1.12.3: resolution: {integrity: sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g==} + object-is@1.1.6: + resolution: {integrity: sha512-F8cZ+KfGlSGi09lJT7/Nd6KJZ9ygtvYC0/UYYLI9nmQKLMnydpB9yvbv9K1uSkEu7FU9vYPmVwLg328tX+ot3Q==} + engines: {node: '>= 0.4'} + + object-keys@1.1.1: + resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==} + engines: {node: '>= 0.4'} + + object.assign@4.1.7: + resolution: {integrity: sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==} + engines: {node: '>= 0.4'} + oboe@2.1.5: resolution: {integrity: sha512-zRFWiF+FoicxEs3jNI/WYUrVEgA7DeET/InK0XQuudGHRg8iIob3cNPrJTKaz4004uaA9Pbe+Dwa8iluhjLZWA==} @@ -1813,6 +1973,9 @@ packages: resolution: {integrity: sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==} engines: {node: '>=8.6'} + poseidon-lite@0.2.1: + resolution: {integrity: sha512-xIr+G6HeYfOhCuswdqcFpSX47SPhm0EpisWJ6h7fHlWwaVIvH3dLnejpatrtw6Xc6HaLrpq05y7VRfvDmDGIog==} + prelude-ls@1.2.1: resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} engines: {node: '>= 0.8.0'} @@ -1863,6 +2026,11 @@ packages: resolution: {integrity: sha512-gjWOsm2SoGlgLEdAGt7a6slVOk9mGiXmPFMqrEhLQ68rhQuBnpfs3+EmlvqKyxnCo9/PPlF+9MtY02S1aFg+Jw==} engines: {node: '>=0.10.0'} + querystring@0.2.1: + resolution: {integrity: sha512-wkvS7mL/JMugcup3/rMitHmd9ecIGd2lhFhK9N3UUQ450h66d1r3Y9nvXzQAW1Lq+wyx61k/1pfKS5KuKiyEbg==} + engines: {node: '>=0.4.x'} + deprecated: The querystring API is considered Legacy. new code should use the URLSearchParams API instead. + queue-microtask@1.2.3: resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==} @@ -1971,6 +2139,10 @@ packages: resolution: {integrity: sha512-/xE6GvsKKqyo1BAY+KxOWXcLpPsUUyji7Qg3bVD7hh1eRze5bR1uYiuDA/k3Gof1s9BTzQZEJK8sNcNGFIzeWw==} engines: {node: '>=6'} + set-function-length@1.2.2: + resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==} + engines: {node: '>= 0.4'} + setimmediate@1.0.5: resolution: {integrity: sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==} @@ -2211,6 +2383,9 @@ packages: resolution: {integrity: sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==} hasBin: true + valibot@0.36.0: + resolution: {integrity: sha512-CjF1XN4sUce8sBK9TixrDqFM7RwNkuXdJu174/AwmQUB62QbCQADg5lLe8ldBalFgtj1uKj+pKwDJiNo4Mn+eQ==} + validator@13.11.0: resolution: {integrity: sha512-Ii+sehpSfZy+At5nPdnyMhx78fEoPDkR2XW/zimHEL3MyGJQOCQ7WeP20jPYRz7ZCpcKLB21NxuXHF3bxjStBQ==} engines: {node: '>= 0.10'} @@ -2523,6 +2698,16 @@ packages: snapshots: + '@0no-co/graphql.web@1.0.13(graphql@16.10.0)': + optionalDependencies: + graphql: 16.10.0 + + '@0no-co/graphqlsp@1.12.16(graphql@16.10.0)(typescript@5.4.5)': + dependencies: + '@gql.tada/internal': 1.0.8(graphql@16.10.0)(typescript@5.4.5) + graphql: 16.10.0 + typescript: 5.4.5 + '@aashutoshrathi/word-wrap@1.2.6': {} '@adraffy/ens-normalize@1.10.1': {} @@ -2531,13 +2716,16 @@ snapshots: '@allbridge/bridge-core-sdk@file:..(bufferutil@4.0.7)(typescript@5.4.5)(utf-8-validate@5.0.10)(zod@3.24.1)': dependencies: + '@mysten/sui': 1.18.0(typescript@5.4.5) '@project-serum/anchor': 0.25.0(bufferutil@4.0.7)(utf-8-validate@5.0.10) '@solana/spl-token': 0.3.8(@solana/web3.js@1.98.0(bufferutil@4.0.7)(utf-8-validate@5.0.10))(bufferutil@4.0.7)(utf-8-validate@5.0.10) '@solana/web3.js': 1.98.0(bufferutil@4.0.7)(utf-8-validate@5.0.10) '@stellar/stellar-sdk': 13.1.0 + assert: 2.1.0 axios: 1.7.9 big.js: 6.2.2 bn.js: 5.2.1 + querystring: 0.2.1 randombytes: 2.1.0 timed-cache: 2.0.0 tronweb: 6.0.0(bufferutil@4.0.7)(utf-8-validate@5.0.10) @@ -2545,6 +2733,8 @@ snapshots: web3-eth-contract: 4.7.2(bufferutil@4.0.7)(typescript@5.4.5)(utf-8-validate@5.0.10)(zod@3.24.1) web3-types: 1.10.0 transitivePeerDependencies: + - '@gql.tada/svelte-support' + - '@gql.tada/vue-support' - bufferutil - debug - encoding @@ -2921,6 +3111,23 @@ snapshots: '@ethersproject/properties': 5.7.0 '@ethersproject/strings': 5.7.0 + '@gql.tada/cli-utils@1.6.3(@0no-co/graphqlsp@1.12.16(graphql@16.10.0)(typescript@5.4.5))(graphql@16.10.0)(typescript@5.4.5)': + dependencies: + '@0no-co/graphqlsp': 1.12.16(graphql@16.10.0)(typescript@5.4.5) + '@gql.tada/internal': 1.0.8(graphql@16.10.0)(typescript@5.4.5) + graphql: 16.10.0 + typescript: 5.4.5 + + '@gql.tada/internal@1.0.8(graphql@16.10.0)(typescript@5.4.5)': + dependencies: + '@0no-co/graphql.web': 1.0.13(graphql@16.10.0) + graphql: 16.10.0 + typescript: 5.4.5 + + '@graphql-typed-document-node/core@3.2.0(graphql@16.10.0)': + dependencies: + graphql: 16.10.0 + '@humanwhocodes/config-array@0.11.11': dependencies: '@humanwhocodes/object-schema': 1.2.1 @@ -2933,6 +3140,31 @@ snapshots: '@humanwhocodes/object-schema@1.2.1': {} + '@mysten/bcs@1.2.0': + dependencies: + bs58: 6.0.0 + + '@mysten/sui@1.18.0(typescript@5.4.5)': + dependencies: + '@graphql-typed-document-node/core': 3.2.0(graphql@16.10.0) + '@mysten/bcs': 1.2.0 + '@noble/curves': 1.8.0 + '@noble/hashes': 1.7.0 + '@scure/bip32': 1.4.0 + '@scure/bip39': 1.3.0 + '@simplewebauthn/typescript-types': 7.4.0 + '@suchipi/femver': 1.0.0 + bech32: 2.0.0 + gql.tada: 1.8.10(graphql@16.10.0)(typescript@5.4.5) + graphql: 16.10.0 + jose: 5.9.6 + poseidon-lite: 0.2.1 + valibot: 0.36.0 + transitivePeerDependencies: + - '@gql.tada/svelte-support' + - '@gql.tada/vue-support' + - typescript + '@noble/curves@1.2.0': dependencies: '@noble/hashes': 1.3.2 @@ -3004,6 +3236,8 @@ snapshots: '@noble/hashes': 1.4.0 '@scure/base': 1.1.9 + '@simplewebauthn/typescript-types@7.4.0': {} + '@sindresorhus/is@4.6.0': {} '@solana/buffer-layout-utils@0.2.0(bufferutil@4.0.7)(utf-8-validate@5.0.10)': @@ -3125,6 +3359,8 @@ snapshots: transitivePeerDependencies: - debug + '@suchipi/femver@1.0.0': {} + '@swc/helpers@0.5.15': dependencies: tslib: 2.8.1 @@ -3339,6 +3575,14 @@ snapshots: assert-plus@1.0.0: {} + assert@2.1.0: + dependencies: + call-bind: 1.0.2 + is-nan: 1.3.2 + object-is: 1.1.6 + object.assign: 4.1.7 + util: 0.12.5 + async-limiter@1.0.1: {} asynckit@0.4.0: {} @@ -3379,6 +3623,8 @@ snapshots: base-x@4.0.0: {} + base-x@5.0.0: {} + base32.js@0.1.0: {} base64-js@1.5.1: {} @@ -3389,6 +3635,8 @@ snapshots: bech32@1.1.4: {} + bech32@2.0.0: {} + big.js@6.2.2: {} bigint-buffer@1.1.5: @@ -3479,6 +3727,10 @@ snapshots: dependencies: base-x: 4.0.0 + bs58@6.0.0: + dependencies: + base-x: 5.0.0 + bs58check@2.1.2: dependencies: bs58: 4.0.1 @@ -3521,11 +3773,28 @@ snapshots: normalize-url: 6.1.0 responselike: 2.0.1 + call-bind-apply-helpers@1.0.1: + dependencies: + es-errors: 1.3.0 + function-bind: 1.1.2 + call-bind@1.0.2: dependencies: function-bind: 1.1.1 get-intrinsic: 1.2.1 + call-bind@1.0.8: + dependencies: + call-bind-apply-helpers: 1.0.1 + es-define-property: 1.0.1 + get-intrinsic: 1.2.7 + set-function-length: 1.2.2 + + call-bound@1.0.3: + dependencies: + call-bind-apply-helpers: 1.0.1 + get-intrinsic: 1.2.7 + callsites@3.1.0: {} camelcase@5.3.1: {} @@ -3665,6 +3934,18 @@ snapshots: defer-to-connect@2.0.1: {} + define-data-property@1.1.4: + dependencies: + es-define-property: 1.0.1 + es-errors: 1.3.0 + gopd: 1.0.1 + + define-properties@1.2.1: + dependencies: + define-data-property: 1.1.4 + has-property-descriptors: 1.0.2 + object-keys: 1.1.1 + delay@5.0.0: {} delayed-stream@1.0.0: {} @@ -3690,6 +3971,12 @@ snapshots: dotenv@16.3.1: {} + dunder-proto@1.0.1: + dependencies: + call-bind-apply-helpers: 1.0.1 + es-errors: 1.3.0 + gopd: 1.2.0 + ecc-jsbn@0.1.2: dependencies: jsbn: 0.1.1 @@ -3713,6 +4000,14 @@ snapshots: dependencies: once: 1.4.0 + es-define-property@1.0.1: {} + + es-errors@1.3.0: {} + + es-object-atoms@1.1.1: + dependencies: + es-errors: 1.3.0 + es5-ext@0.10.62: dependencies: es6-iterator: 2.0.3 @@ -4146,6 +4441,8 @@ snapshots: function-bind@1.1.1: {} + function-bind@1.1.2: {} + get-intrinsic@1.2.1: dependencies: function-bind: 1.1.1 @@ -4153,6 +4450,24 @@ snapshots: has-proto: 1.0.1 has-symbols: 1.0.3 + get-intrinsic@1.2.7: + dependencies: + call-bind-apply-helpers: 1.0.1 + es-define-property: 1.0.1 + es-errors: 1.3.0 + es-object-atoms: 1.1.1 + function-bind: 1.1.2 + get-proto: 1.0.1 + gopd: 1.2.0 + has-symbols: 1.1.0 + hasown: 2.0.2 + math-intrinsics: 1.1.0 + + get-proto@1.0.1: + dependencies: + dunder-proto: 1.0.1 + es-object-atoms: 1.1.1 + get-stream@5.2.0: dependencies: pump: 3.0.0 @@ -4206,6 +4521,8 @@ snapshots: dependencies: get-intrinsic: 1.2.1 + gopd@1.2.0: {} + got@11.8.6: dependencies: '@sindresorhus/is': 4.6.0 @@ -4236,10 +4553,24 @@ snapshots: p-cancelable: 3.0.0 responselike: 2.0.1 + gql.tada@1.8.10(graphql@16.10.0)(typescript@5.4.5): + dependencies: + '@0no-co/graphql.web': 1.0.13(graphql@16.10.0) + '@0no-co/graphqlsp': 1.12.16(graphql@16.10.0)(typescript@5.4.5) + '@gql.tada/cli-utils': 1.6.3(@0no-co/graphqlsp@1.12.16(graphql@16.10.0)(typescript@5.4.5))(graphql@16.10.0)(typescript@5.4.5) + '@gql.tada/internal': 1.0.8(graphql@16.10.0)(typescript@5.4.5) + typescript: 5.4.5 + transitivePeerDependencies: + - '@gql.tada/svelte-support' + - '@gql.tada/vue-support' + - graphql + graceful-fs@4.2.11: {} graphemer@1.4.0: {} + graphql@16.10.0: {} + har-schema@2.0.0: {} har-validator@5.1.5: @@ -4249,10 +4580,16 @@ snapshots: has-flag@4.0.0: {} + has-property-descriptors@1.0.2: + dependencies: + es-define-property: 1.0.1 + has-proto@1.0.1: {} has-symbols@1.0.3: {} + has-symbols@1.1.0: {} + has-tostringtag@1.0.0: dependencies: has-symbols: 1.0.3 @@ -4272,6 +4609,10 @@ snapshots: inherits: 2.0.4 minimalistic-assert: 1.0.1 + hasown@2.0.2: + dependencies: + function-bind: 1.1.2 + hmac-drbg@1.0.1: dependencies: hash.js: 1.1.7 @@ -4361,6 +4702,11 @@ snapshots: is-hex-prefixed@1.0.0: {} + is-nan@1.3.2: + dependencies: + call-bind: 1.0.2 + define-properties: 1.2.1 + is-number@7.0.0: {} is-path-inside@3.0.3: {} @@ -4425,6 +4771,8 @@ snapshots: - bufferutil - utf-8-validate + jose@5.9.6: {} + js-sha256@0.9.0: {} js-sha3@0.5.7: {} @@ -4495,6 +4843,8 @@ snapshots: dependencies: yallist: 4.0.0 + math-intrinsics@1.1.0: {} + md5.js@1.3.5: dependencies: hash-base: 3.1.0 @@ -4631,6 +4981,22 @@ snapshots: object-inspect@1.12.3: {} + object-is@1.1.6: + dependencies: + call-bind: 1.0.8 + define-properties: 1.2.1 + + object-keys@1.1.1: {} + + object.assign@4.1.7: + dependencies: + call-bind: 1.0.8 + call-bound: 1.0.3 + define-properties: 1.2.1 + es-object-atoms: 1.1.1 + has-symbols: 1.1.0 + object-keys: 1.1.1 + oboe@2.1.5: dependencies: http-https: 1.0.0 @@ -4696,6 +5062,8 @@ snapshots: picomatch@2.3.1: {} + poseidon-lite@0.2.1: {} + prelude-ls@1.2.1: {} prettier-linter-helpers@1.0.0: @@ -4736,6 +5104,8 @@ snapshots: object-assign: 4.1.1 strict-uri-encode: 1.1.0 + querystring@0.2.1: {} + queue-microtask@1.2.3: {} quick-lru@5.1.1: {} @@ -4900,6 +5270,15 @@ snapshots: transitivePeerDependencies: - supports-color + set-function-length@1.2.2: + dependencies: + define-data-property: 1.1.4 + es-errors: 1.3.0 + function-bind: 1.1.2 + get-intrinsic: 1.2.7 + gopd: 1.0.1 + has-property-descriptors: 1.0.2 + setimmediate@1.0.5: {} setprototypeof@1.2.0: {} @@ -5161,6 +5540,8 @@ snapshots: uuid@9.0.1: {} + valibot@0.36.0: {} + validator@13.11.0: {} varint@5.0.2: {} diff --git a/examples/src/examples/bridge/sui/sui-build-send-tx.ts b/examples/src/examples/bridge/sui/sui-build-send-tx.ts new file mode 100644 index 00000000..cb15859d --- /dev/null +++ b/examples/src/examples/bridge/sui/sui-build-send-tx.ts @@ -0,0 +1,53 @@ +import { + AllbridgeCoreSdk, + ChainSymbol, + Messenger, + nodeRpcUrlsDefault, + RawSuiTransaction, +} from "@allbridge/bridge-core-sdk"; +import * as dotenv from "dotenv"; +import { getEnvVar } from "../../../utils/env"; +import { ensure } from "../../../utils/utils"; +import { sendSuiRawTransaction } from "../../../utils/sui"; + +dotenv.config({ path: ".env" }); + +const main = async () => { + // sender address + const accountAddress = getEnvVar("SUI_ACCOUNT_ADDRESS"); + const toAddress = getEnvVar("ETH_ACCOUNT_ADDRESS"); // recipient address + + const sdk = new AllbridgeCoreSdk(nodeRpcUrlsDefault); + + const chains = await sdk.chainDetailsMap(); + + const sourceChain = chains[ChainSymbol.SUI]; + const sourceToken = ensure(sourceChain.tokens.find((tokenInfo) => tokenInfo.symbol === "USDC")); + + const destinationChain = chains[ChainSymbol.ETH]; + const destinationToken = ensure(destinationChain.tokens.find((tokenInfo) => tokenInfo.symbol === "USDC")); + + const amount = "100"; + + // initiate transfer + const xdr = (await sdk.bridge.rawTxBuilder.send({ + amount: amount, + fromAccountAddress: accountAddress, + toAccountAddress: toAddress, + sourceToken: sourceToken, + destinationToken: destinationToken, + messenger: Messenger.ALLBRIDGE, + // gasFeePaymentMethod: FeePaymentMethod.WITH_STABLECOIN, + })) as RawSuiTransaction; + + const txReceipt = await sendSuiRawTransaction(xdr); + console.log("tx id:", txReceipt); +}; + +main() + .then(() => { + console.log("Done"); + }) + .catch((e) => { + console.error(e); + }); diff --git a/examples/src/examples/bridge/sui/sui-build-swap-tx.ts b/examples/src/examples/bridge/sui/sui-build-swap-tx.ts new file mode 100644 index 00000000..4256d0c7 --- /dev/null +++ b/examples/src/examples/bridge/sui/sui-build-swap-tx.ts @@ -0,0 +1,54 @@ +import { + AllbridgeCoreSdk, + ChainSymbol, + nodeRpcUrlsDefault, + RawSuiTransaction, + SwapParams, +} from "@allbridge/bridge-core-sdk"; +import * as dotenv from "dotenv"; +import { getEnvVar } from "../../../utils/env"; +import { ensure } from "../../../utils/utils"; +import { sendSuiRawTransaction } from "../../../utils/sui"; + +dotenv.config({ path: ".env" }); + +const main = async () => { + // sender address + const accountAddress = getEnvVar("SUI_ACCOUNT_ADDRESS"); + const tokenAddress = getEnvVar("SUI_TOKEN_ADDRESS"); + const tokenAddress2 = getEnvVar("SUI_TOKEN2_ADDRESS"); + + const sdk = new AllbridgeCoreSdk(nodeRpcUrlsDefault); + + const chains = await sdk.chainDetailsMap(); + + const sourceToken = ensure((await sdk.tokens()).find((tokenInfo) => tokenInfo.originTokenAddress === tokenAddress)); + + const destinationToken = ensure( + (await sdk.tokens()).find((tokenInfo) => tokenInfo.originTokenAddress === tokenAddress2) + ); + + const amount = "10"; + + // initiate transfer + const swapParams: SwapParams = { + amount: amount, + fromAccountAddress: accountAddress, + toAccountAddress: accountAddress, + sourceToken: sourceToken, + destinationToken: destinationToken, + minimumReceiveAmount: await sdk.getAmountToBeReceived(amount, sourceToken, destinationToken), + }; + const xdr = (await sdk.bridge.rawTxBuilder.send(swapParams)) as RawSuiTransaction; + + const txReceipt = await sendSuiRawTransaction(xdr); + console.log("tx id:", txReceipt); +}; + +main() + .then(() => { + console.log("Done"); + }) + .catch((e) => { + console.error(e); + }); diff --git a/examples/src/examples/general/sui/sui-get-token-balance.ts b/examples/src/examples/general/sui/sui-get-token-balance.ts new file mode 100644 index 00000000..877423d9 --- /dev/null +++ b/examples/src/examples/general/sui/sui-get-token-balance.ts @@ -0,0 +1,34 @@ +import * as dotenv from "dotenv"; +import { getEnvVar } from "../../../utils/env"; +import { AllbridgeCoreSdk, ChainSymbol, nodeRpcUrlsDefault } from "@allbridge/bridge-core-sdk"; +import { ensure } from "../../../utils/utils"; + +dotenv.config({ path: ".env" }); + +const main = async () => { + const tokenAddress = getEnvVar("SUI_TOKEN_ADDRESS"); + const accountAddress = getEnvVar("SUI_ACCOUNT_ADDRESS"); + + const sdk = new AllbridgeCoreSdk(nodeRpcUrlsDefault); + + const nativeTokenBalance = await sdk.getNativeTokenBalance({ account: accountAddress, chainSymbol: ChainSymbol.SUI }); + console.log("Native Token Balance: ", nativeTokenBalance); + + const tokenInfo = ensure((await sdk.tokens()).find((tokenInfo) => tokenInfo.originTokenAddress === tokenAddress)); + + const tokenBalanceData = { + account: accountAddress, + token: tokenInfo, + }; + + const tokenBalance = await sdk.getTokenBalance(tokenBalanceData); + console.log("Token Balance: ", tokenBalance); +}; + +main() + .then(() => { + console.log("Done"); + }) + .catch((e) => { + console.error(e); + }); diff --git a/examples/src/examples/liquidity-pool/sui/get-amount-to-be-withdrawn.ts b/examples/src/examples/liquidity-pool/sui/get-amount-to-be-withdrawn.ts new file mode 100644 index 00000000..7ea3189f --- /dev/null +++ b/examples/src/examples/liquidity-pool/sui/get-amount-to-be-withdrawn.ts @@ -0,0 +1,25 @@ +import * as dotenv from "dotenv"; +import { getEnvVar } from "../../../utils/env"; +import { AllbridgeCoreSdk, nodeRpcUrlsDefault } from "@allbridge/bridge-core-sdk"; +import { ensure } from "../../../utils/utils"; +dotenv.config({ path: ".env" }); + +const main = async () => { + const tokenAddress = getEnvVar("SUI_TOKEN_ADDRESS"); + const accountAddress = getEnvVar("SUI_ACCOUNT_ADDRESS"); + + const sdk = new AllbridgeCoreSdk(nodeRpcUrlsDefault); + const tokenInfo = ensure((await sdk.tokens()).find((tokenInfo) => tokenInfo.originTokenAddress === tokenAddress)); + + const halfToken = "0.5"; + const estimatedAmount = await sdk.pool.getAmountToBeWithdrawn(halfToken, accountAddress, tokenInfo); + console.log("If you withdraw %d LP tokens, then %d will be received", halfToken, estimatedAmount); +}; + +main() + .then(() => { + console.log("Done"); + }) + .catch((e) => { + console.error(e); + }); diff --git a/examples/src/examples/liquidity-pool/sui/get-liquidity-balance.ts b/examples/src/examples/liquidity-pool/sui/get-liquidity-balance.ts new file mode 100644 index 00000000..dd6beec3 --- /dev/null +++ b/examples/src/examples/liquidity-pool/sui/get-liquidity-balance.ts @@ -0,0 +1,29 @@ +import * as dotenv from "dotenv"; +import { getEnvVar } from "../../../utils/env"; +import { AllbridgeCoreSdk, nodeRpcUrlsDefault } from "@allbridge/bridge-core-sdk"; +import { ensure } from "../../../utils/utils"; + +dotenv.config({ path: ".env" }); + +const main = async () => { + const tokenAddress = getEnvVar("SUI_TOKEN_ADDRESS"); + const accountAddress = getEnvVar("SUI_ACCOUNT_ADDRESS"); + + const sdk = new AllbridgeCoreSdk(nodeRpcUrlsDefault); + const tokenInfo = ensure((await sdk.tokens()).find((tokenInfo) => tokenInfo.originTokenAddress === tokenAddress)); + + const userBalanceInfo = await sdk.pool.getUserBalanceInfo(accountAddress, tokenInfo); + const poolInfo = await sdk.pool.getPoolInfoFromChain(tokenInfo); + + console.log("User balance: ", userBalanceInfo.userLiquidity); + console.log("User rewards: ", userBalanceInfo.earned(poolInfo, tokenInfo.decimals)); + console.log("PoolInfo APR: ", sdk.aprInPercents(tokenInfo.apr7d)); +}; + +main() + .then(() => { + console.log("Done"); + }) + .catch((e) => { + console.error(e); + }); diff --git a/examples/src/examples/liquidity-pool/sui/get-lp-amount-on-deposit.ts b/examples/src/examples/liquidity-pool/sui/get-lp-amount-on-deposit.ts new file mode 100644 index 00000000..d9634758 --- /dev/null +++ b/examples/src/examples/liquidity-pool/sui/get-lp-amount-on-deposit.ts @@ -0,0 +1,25 @@ +import * as dotenv from "dotenv"; +import { getEnvVar } from "../../../utils/env"; +import { AllbridgeCoreSdk, nodeRpcUrlsDefault } from "@allbridge/bridge-core-sdk"; +import { ensure } from "../../../utils/utils"; + +dotenv.config({ path: ".env" }); + +const main = async () => { + const tokenAddress = getEnvVar("SUI_TOKEN_ADDRESS"); + + const sdk = new AllbridgeCoreSdk(nodeRpcUrlsDefault); + const tokenInfo = ensure((await sdk.tokens()).find((tokenInfo) => tokenInfo.originTokenAddress === tokenAddress)); + + const oneToken = "1"; + const estimatedAmount = await sdk.pool.getAmountToBeDeposited(oneToken, tokenInfo); + console.log("If you send %d , then %d of LP tokens will be deposited", oneToken, estimatedAmount); +}; + +main() + .then(() => { + console.log("Done"); + }) + .catch((e) => { + console.error(e); + }); diff --git a/examples/src/examples/liquidity-pool/sui/sui-build-claim-rewards-tx.ts b/examples/src/examples/liquidity-pool/sui/sui-build-claim-rewards-tx.ts new file mode 100644 index 00000000..9f99149d --- /dev/null +++ b/examples/src/examples/liquidity-pool/sui/sui-build-claim-rewards-tx.ts @@ -0,0 +1,33 @@ +import * as dotenv from "dotenv"; +import { getEnvVar } from "../../../utils/env"; +import { AllbridgeCoreSdk, nodeRpcUrlsDefault, RawSuiTransaction } from "@allbridge/bridge-core-sdk"; +import { ensure } from "../../../utils/utils"; +import { sendSuiRawTransaction } from "../../../utils/sui"; + +dotenv.config({ path: ".env" }); + +const main = async () => { + // sender address + const accountAddress = getEnvVar("SUI_ACCOUNT_ADDRESS"); + const tokenAddress = getEnvVar("SUI_TOKEN_ADDRESS"); + + const sdk = new AllbridgeCoreSdk(nodeRpcUrlsDefault); + const tokenInfo = ensure((await sdk.tokens()).find((tokenInfo) => tokenInfo.originTokenAddress === tokenAddress)); + + // create claim rewards raw transaction + const xdr = (await sdk.pool.rawTxBuilder.claimRewards({ + accountAddress: accountAddress, + token: tokenInfo, + })) as RawSuiTransaction; + + const txReceipt = await sendSuiRawTransaction(xdr); + console.log("Token claimRewards:", txReceipt); +}; + +main() + .then(() => { + console.log("Done"); + }) + .catch((e) => { + console.error(e); + }); diff --git a/examples/src/examples/liquidity-pool/sui/sui-build-deposit-tx.ts b/examples/src/examples/liquidity-pool/sui/sui-build-deposit-tx.ts new file mode 100644 index 00000000..f90358fd --- /dev/null +++ b/examples/src/examples/liquidity-pool/sui/sui-build-deposit-tx.ts @@ -0,0 +1,35 @@ +import * as dotenv from "dotenv"; +import { getEnvVar } from "../../../utils/env"; +import { AllbridgeCoreSdk, nodeRpcUrlsDefault, RawSuiTransaction } from "@allbridge/bridge-core-sdk"; +import { ensure } from "../../../utils/utils"; +import { sendSuiRawTransaction } from "../../../utils/sui"; + +dotenv.config({ path: ".env" }); + +const main = async () => { + // sender address + const accountAddress = getEnvVar("SUI_ACCOUNT_ADDRESS"); + const tokenAddress = getEnvVar("SUI_TOKEN_ADDRESS"); + + const sdk = new AllbridgeCoreSdk(nodeRpcUrlsDefault); + const tokenInfo = ensure((await sdk.tokens()).find((tokenInfo) => tokenInfo.originTokenAddress === tokenAddress)); + + const oneToken = "1"; + // create deposit raw transaction + const xdr = (await sdk.pool.rawTxBuilder.deposit({ + amount: oneToken, + accountAddress: accountAddress, + token: tokenInfo, + })) as RawSuiTransaction; + + const txReceipt = await sendSuiRawTransaction(xdr); + console.log("Token deposit:", txReceipt); +}; + +main() + .then(() => { + console.log("Done"); + }) + .catch((e) => { + console.error(e); + }); diff --git a/examples/src/examples/liquidity-pool/sui/sui-build-withdraw-tx.ts b/examples/src/examples/liquidity-pool/sui/sui-build-withdraw-tx.ts new file mode 100644 index 00000000..39b7e69f --- /dev/null +++ b/examples/src/examples/liquidity-pool/sui/sui-build-withdraw-tx.ts @@ -0,0 +1,35 @@ +import * as dotenv from "dotenv"; +import { getEnvVar } from "../../../utils/env"; +import { AllbridgeCoreSdk, nodeRpcUrlsDefault, RawSuiTransaction } from "@allbridge/bridge-core-sdk"; +import { ensure } from "../../../utils/utils"; +import { sendSuiRawTransaction } from "../../../utils/sui"; + +dotenv.config({ path: ".env" }); + +const main = async () => { + // sender address + const accountAddress = getEnvVar("SUI_ACCOUNT_ADDRESS"); + const tokenAddress = getEnvVar("SUI_TOKEN_ADDRESS"); + + const sdk = new AllbridgeCoreSdk(nodeRpcUrlsDefault); + const tokenInfo = ensure((await sdk.tokens()).find((tokenInfo) => tokenInfo.originTokenAddress === tokenAddress)); + + const halfToken = "0.5"; + // create withdraw raw transaction + const xdr = (await sdk.pool.rawTxBuilder.withdraw({ + amount: halfToken, + accountAddress: accountAddress, + token: tokenInfo, + })) as RawSuiTransaction; + + const txReceipt = await sendSuiRawTransaction(xdr); + console.log("Token withdraw:", txReceipt); +}; + +main() + .then(() => { + console.log("Done"); + }) + .catch((e) => { + console.error(e); + }); diff --git a/examples/src/utils/sui.ts b/examples/src/utils/sui.ts new file mode 100644 index 00000000..7d340d7c --- /dev/null +++ b/examples/src/utils/sui.ts @@ -0,0 +1,26 @@ +import { SuiClient, SuiTransactionBlockResponse } from "@mysten/sui/client"; +import { getEnvVar } from "./env"; +import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519"; +import { Transaction } from "@mysten/sui/transactions"; + +export async function sendSuiRawTransaction(xdr: string): Promise { + const tx = Transaction.from(xdr); + + const client = new SuiClient({ + url: getEnvVar("SUI_PROVIDER_URL"), + }); + const signer = Ed25519Keypair.fromSecretKey(getEnvVar("SUI_PRIVATE_KEY")); + const txBlockResponse = await client.signAndExecuteTransaction({ + signer: signer, + transaction: tx, + }); + + return await client.waitForTransaction({ + digest: txBlockResponse.digest, + pollInterval: 100, + options: { + showEffects: true, + showEvents: true, + }, + }); +} diff --git a/examples/tsconfig.json b/examples/tsconfig.json index 0d102e29..d9d80fe0 100644 --- a/examples/tsconfig.json +++ b/examples/tsconfig.json @@ -1,6 +1,6 @@ { "compilerOptions": { - "target": "es5", + "target": "ES2023", "module": "commonjs", "lib": [ "es6" diff --git a/package.json b/package.json index 3b5e0392..ad7f62e1 100644 --- a/package.json +++ b/package.json @@ -99,6 +99,7 @@ "semver-regex": "3.1.4" }, "dependencies": { + "@mysten/sui": "1.18.0", "@project-serum/anchor": "^0.25.0", "@solana/spl-token": "^0.3.8", "@solana/web3.js": "^1.98.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 58856cf6..df3db557 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,6 +8,9 @@ importers: .: dependencies: + '@mysten/sui': + specifier: 1.18.0 + version: 1.18.0(typescript@5.5.4) '@project-serum/anchor': specifier: ^0.25.0 version: 0.25.0(bufferutil@4.0.9)(utf-8-validate@5.0.10) @@ -192,6 +195,20 @@ importers: packages: + '@0no-co/graphql.web@1.0.13': + resolution: {integrity: sha512-jqYxOevheVTU1S36ZdzAkJIdvRp2m3OYIG5SEoKDw5NI8eVwkoI0D/Q3DYNGmXCxkA6CQuoa7zvMiDPTLqUNuw==} + peerDependencies: + graphql: ^14.0.0 || ^15.0.0 || ^16.0.0 + peerDependenciesMeta: + graphql: + optional: true + + '@0no-co/graphqlsp@1.12.16': + resolution: {integrity: sha512-B5pyYVH93Etv7xjT6IfB7QtMBdaaC07yjbhN6v8H7KgFStMkPvi+oWYBTibMFRMY89qwc9H8YixXg8SXDVgYWw==} + peerDependencies: + graphql: ^15.5.0 || ^16.0.0 || ^17.0.0 + typescript: ^5.0.0 + '@adraffy/ens-normalize@1.10.1': resolution: {integrity: sha512-96Z2IP3mYmF1Xg2cDm8f1gWGf/HUVedQ3FMifV4kG/PQ4yEP51xDtRAEfhVNt5f/uzpNkZHwWQuUcu6D6K+Ekw==} @@ -817,6 +834,31 @@ packages: '@gerrit0/mini-shiki@1.26.1': resolution: {integrity: sha512-gHFUvv9f1fU2Piou/5Y7Sx5moYxcERbC7CXc6rkDLQTUBg5Dgg9L4u29/nHqfoQ3Y9R0h0BcOhd14uOEZIBP7Q==} + '@gql.tada/cli-utils@1.6.3': + resolution: {integrity: sha512-jFFSY8OxYeBxdKi58UzeMXG1tdm4FVjXa8WHIi66Gzu9JWtCE6mqom3a8xkmSw+mVaybFW5EN2WXf1WztJVNyQ==} + peerDependencies: + '@0no-co/graphqlsp': ^1.12.13 + '@gql.tada/svelte-support': 1.0.1 + '@gql.tada/vue-support': 1.0.1 + graphql: ^15.5.0 || ^16.0.0 || ^17.0.0 + typescript: ^5.0.0 + peerDependenciesMeta: + '@gql.tada/svelte-support': + optional: true + '@gql.tada/vue-support': + optional: true + + '@gql.tada/internal@1.0.8': + resolution: {integrity: sha512-XYdxJhtHC5WtZfdDqtKjcQ4d7R1s0d1rnlSs3OcBEUbYiPoJJfZU7tWsVXuv047Z6msvmr4ompJ7eLSK5Km57g==} + peerDependencies: + graphql: ^15.5.0 || ^16.0.0 || ^17.0.0 + typescript: ^5.0.0 + + '@graphql-typed-document-node/core@3.2.0': + resolution: {integrity: sha512-mB9oAsNCm9aM3/SOv4YtBMqZbYj10R7dkq8byBqxGY/ncFwhf2oQzMV+LCRlWoDSEBJ3COiR1yeDvMtsoOsuFQ==} + peerDependencies: + graphql: ^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0 + '@humanfs/core@0.19.1': resolution: {integrity: sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==} engines: {node: '>=18.18.0'} @@ -936,6 +978,13 @@ packages: '@jspm/core@2.1.0': resolution: {integrity: sha512-3sRl+pkyFY/kLmHl0cgHiFp2xEqErA8N3ECjMs7serSUBmoJ70lBa0PG5t0IM6WJgdZNyyI0R8YFfi5wM8+mzg==} + '@mysten/bcs@1.2.0': + resolution: {integrity: sha512-LuKonrGdGW7dq/EM6U2L9/as7dFwnhZnsnINzB/vu08Xfrj0qzWwpLOiXagAa5yZOPLK7anRZydMonczFkUPzA==} + + '@mysten/sui@1.18.0': + resolution: {integrity: sha512-cFh5LxXZrXb/ZAD1dkKeQxzhgRYFXreyFGmI7w/JQWwdl+/0FrHJBwaWyTmGxJ/6ZC9SlaOPOk63flN7DbUurg==} + engines: {node: '>=18'} + '@noble/curves@1.2.0': resolution: {integrity: sha512-oYclrNgRaM9SsBUBVbb8M6DTV7ZHRTKugureoYEncY5c65HOmRzvSiTE3y5CYaPYJA/GVkrhXEoF0M3Ya9PMnw==} @@ -1119,6 +1168,10 @@ packages: '@shikijs/vscode-textmate@10.0.1': resolution: {integrity: sha512-fTIQwLF+Qhuws31iw7Ncl1R3HUDtGwIipiJ9iU+UsDUwMhegFcQKQHd51nZjb7CArq0MvON8rbgCGQYWHUKAdg==} + '@simplewebauthn/typescript-types@7.4.0': + resolution: {integrity: sha512-8/ZjHeUPe210Bt5oyaOIGx4h8lHdsQs19BiOT44gi/jBEgK7uBGA0Fy7NRsyh777al3m6WM0mBf0UR7xd4R7WQ==} + deprecated: This package has been renamed to @simplewebauthn/types. Please install @simplewebauthn/types instead to ensure you receive future updates. + '@sinclair/typebox@0.27.8': resolution: {integrity: sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==} @@ -1209,6 +1262,9 @@ packages: '@stellar/stellar-sdk@13.1.0': resolution: {integrity: sha512-ARQkUdyGefXdTgwSF0eONkzv/geAqUfyfheJ9Nthz6GAr5b41fNwWW9UtE8JpXC4IpvE3t5elIUN5hKJzASN9w==} + '@suchipi/femver@1.0.0': + resolution: {integrity: sha512-bprE8+K5V+DPX7q2e2K57ImqNBdfGHDIWaGI5xHxZoxbKOuQZn4wzPiUxOAHnsUr3w3xHrWXwN7gnG/iIuEMIg==} + '@swc/helpers@0.5.15': resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==} @@ -1570,6 +1626,9 @@ packages: base64-js@1.5.1: resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} + bech32@2.0.0: + resolution: {integrity: sha512-LcknSilhIGatDAsY1ak2I8VtGaHNhgMSYVxFrGLXv+xLHytaKZKcaUJJUE7qmBr7h33o5YQwP55pMI0xmkpJwg==} + before-after-hook@3.0.2: resolution: {integrity: sha512-Nik3Sc0ncrMK4UUdXQmAnRtzmNQTAAXmXIopizwZ1W1t8QmfJj+zL4OA2I7XPTPW5z5TDqv4hRo/JzouDJnX3A==} @@ -2656,6 +2715,12 @@ packages: resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} engines: {node: '>= 0.4'} + gql.tada@1.8.10: + resolution: {integrity: sha512-FrvSxgz838FYVPgZHGOSgbpOjhR+yq44rCzww3oOPJYi0OvBJjAgCiP6LEokZIYND2fUTXzQAyLgcvgw1yNP5A==} + hasBin: true + peerDependencies: + typescript: ^5.0.0 + graceful-fs@4.2.10: resolution: {integrity: sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==} @@ -2665,6 +2730,10 @@ packages: graphemer@1.4.0: resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==} + graphql@16.10.0: + resolution: {integrity: sha512-AjqGKbDGUFRKIRCP9tCKiIGHyriz2oHEbPIbEtcSLSs4YjReZOIPQQWek4+6hjw62H9QShXHyaGivGiYVLeYFQ==} + engines: {node: ^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0} + handlebars@4.7.8: resolution: {integrity: sha512-vafaFqs8MZkRrSX7sFVUdo3ap/eNiLnb4IakshzvP56X5Nr1iGKAIqdX6tMlm6HcNRIkr6AxO5jFEoJzzpT8aQ==} engines: {node: '>=0.4.7'} @@ -3208,6 +3277,9 @@ packages: resolution: {integrity: sha512-rg9zJN+G4n2nfJl5MW3BMygZX56zKPNVEYYqq7adpmMh4Jn2QNEwhvQlFy6jPVdcod7txZtKHWnyZiA3a0zP7A==} hasBin: true + jose@5.9.6: + resolution: {integrity: sha512-AMlnetc9+CV9asI19zHmrgS/WYsWUwCn2R7RzlbJWD7F9eWYUTGyBmU9o6PxngtLGOiDGPRu+Uc4fhKzbpteZQ==} + js-sha256@0.9.0: resolution: {integrity: sha512-sga3MHh9sgQN2+pJ9VYZ+1LPwXOxuBJBA5nrR5/ofPfuiJBE2hnjsaN8se8JznOmGLN2p49Pe5U/ttafcs/apA==} @@ -3846,6 +3918,9 @@ packages: resolution: {integrity: sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==} engines: {node: '>=8'} + poseidon-lite@0.2.1: + resolution: {integrity: sha512-xIr+G6HeYfOhCuswdqcFpSX47SPhm0EpisWJ6h7fHlWwaVIvH3dLnejpatrtw6Xc6HaLrpq05y7VRfvDmDGIog==} + possible-typed-array-names@1.0.0: resolution: {integrity: sha512-d7Uw+eZoloe0EHDIYoe+bQ5WXnGMOpmiZFTuMWCwpjzzkL2nTjcKiAk4hh8TjnGye2TwWOk3UXucZ+3rbmBa8Q==} engines: {node: '>= 0.4'} @@ -4584,6 +4659,9 @@ packages: resolution: {integrity: sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==} engines: {node: '>=10.12.0'} + valibot@0.36.0: + resolution: {integrity: sha512-CjF1XN4sUce8sBK9TixrDqFM7RwNkuXdJu174/AwmQUB62QbCQADg5lLe8ldBalFgtj1uKj+pKwDJiNo4Mn+eQ==} + validate-npm-package-license@3.0.4: resolution: {integrity: sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==} @@ -4842,6 +4920,16 @@ packages: snapshots: + '@0no-co/graphql.web@1.0.13(graphql@16.10.0)': + optionalDependencies: + graphql: 16.10.0 + + '@0no-co/graphqlsp@1.12.16(graphql@16.10.0)(typescript@5.5.4)': + dependencies: + '@gql.tada/internal': 1.0.8(graphql@16.10.0)(typescript@5.5.4) + graphql: 16.10.0 + typescript: 5.5.4 + '@adraffy/ens-normalize@1.10.1': {} '@adraffy/ens-normalize@1.11.0': {} @@ -5425,6 +5513,23 @@ snapshots: '@shikijs/types': 1.26.1 '@shikijs/vscode-textmate': 10.0.1 + '@gql.tada/cli-utils@1.6.3(@0no-co/graphqlsp@1.12.16(graphql@16.10.0)(typescript@5.5.4))(graphql@16.10.0)(typescript@5.5.4)': + dependencies: + '@0no-co/graphqlsp': 1.12.16(graphql@16.10.0)(typescript@5.5.4) + '@gql.tada/internal': 1.0.8(graphql@16.10.0)(typescript@5.5.4) + graphql: 16.10.0 + typescript: 5.5.4 + + '@gql.tada/internal@1.0.8(graphql@16.10.0)(typescript@5.5.4)': + dependencies: + '@0no-co/graphql.web': 1.0.13(graphql@16.10.0) + graphql: 16.10.0 + typescript: 5.5.4 + + '@graphql-typed-document-node/core@3.2.0(graphql@16.10.0)': + dependencies: + graphql: 16.10.0 + '@humanfs/core@0.19.1': {} '@humanfs/node@0.16.6': @@ -5638,6 +5743,31 @@ snapshots: '@jspm/core@2.1.0': {} + '@mysten/bcs@1.2.0': + dependencies: + bs58: 6.0.0 + + '@mysten/sui@1.18.0(typescript@5.5.4)': + dependencies: + '@graphql-typed-document-node/core': 3.2.0(graphql@16.10.0) + '@mysten/bcs': 1.2.0 + '@noble/curves': 1.8.0 + '@noble/hashes': 1.7.0 + '@scure/bip32': 1.4.0 + '@scure/bip39': 1.3.0 + '@simplewebauthn/typescript-types': 7.4.0 + '@suchipi/femver': 1.0.0 + bech32: 2.0.0 + gql.tada: 1.8.10(graphql@16.10.0)(typescript@5.5.4) + graphql: 16.10.0 + jose: 5.9.6 + poseidon-lite: 0.2.1 + valibot: 0.36.0 + transitivePeerDependencies: + - '@gql.tada/svelte-support' + - '@gql.tada/vue-support' + - typescript + '@noble/curves@1.2.0': dependencies: '@noble/hashes': 1.3.2 @@ -5916,6 +6046,8 @@ snapshots: '@shikijs/vscode-textmate@10.0.1': {} + '@simplewebauthn/typescript-types@7.4.0': {} + '@sinclair/typebox@0.27.8': {} '@sindresorhus/is@4.6.0': {} @@ -6071,6 +6203,8 @@ snapshots: transitivePeerDependencies: - debug + '@suchipi/femver@1.0.0': {} + '@swc/helpers@0.5.15': dependencies: tslib: 2.8.1 @@ -6515,6 +6649,8 @@ snapshots: base64-js@1.5.1: {} + bech32@2.0.0: {} + before-after-hook@3.0.2: {} big.js@6.2.2: {} @@ -7831,12 +7967,26 @@ snapshots: gopd@1.2.0: {} + gql.tada@1.8.10(graphql@16.10.0)(typescript@5.5.4): + dependencies: + '@0no-co/graphql.web': 1.0.13(graphql@16.10.0) + '@0no-co/graphqlsp': 1.12.16(graphql@16.10.0)(typescript@5.5.4) + '@gql.tada/cli-utils': 1.6.3(@0no-co/graphqlsp@1.12.16(graphql@16.10.0)(typescript@5.5.4))(graphql@16.10.0)(typescript@5.5.4) + '@gql.tada/internal': 1.0.8(graphql@16.10.0)(typescript@5.5.4) + typescript: 5.5.4 + transitivePeerDependencies: + - '@gql.tada/svelte-support' + - '@gql.tada/vue-support' + - graphql + graceful-fs@4.2.10: {} graceful-fs@4.2.11: {} graphemer@1.4.0: {} + graphql@16.10.0: {} + handlebars@4.7.8: dependencies: minimist: 1.2.8 @@ -8575,6 +8725,8 @@ snapshots: jiti@2.4.2: optional: true + jose@5.9.6: {} + js-sha256@0.9.0: {} js-sha3@0.8.0: {} @@ -9118,6 +9270,8 @@ snapshots: dependencies: find-up: 4.1.0 + poseidon-lite@0.2.1: {} + possible-typed-array-names@1.0.0: {} prelude-ls@1.2.1: {} @@ -9922,6 +10076,8 @@ snapshots: '@types/istanbul-lib-coverage': 2.0.6 convert-source-map: 2.0.0 + valibot@0.36.0: {} + validate-npm-package-license@3.0.4: dependencies: spdx-correct: 3.2.0 diff --git a/src/__tests__/client/core-api/index.test.ts b/src/__tests__/client/core-api/index.test.ts index a5f21969..0ca591eb 100644 --- a/src/__tests__/client/core-api/index.test.ts +++ b/src/__tests__/client/core-api/index.test.ts @@ -26,7 +26,7 @@ describe("AllbridgeCoreClient", () => { const api = new AllbridgeCoreClientImpl( new ApiClientImpl({ coreApiUrl: "http://localhost", - }), + }) ); describe("given /token-info endpoint", () => { @@ -117,7 +117,7 @@ describe("AllbridgeCoreClient", () => { new ApiClientImpl({ coreApiUrl: "http://localhost", coreApiHeaders: customHeaders, - }), + }) ); it("☀️ should be present", async () => { diff --git a/src/__tests__/index.test.ts b/src/__tests__/index.test.ts index bf17ccf2..144f352b 100644 --- a/src/__tests__/index.test.ts +++ b/src/__tests__/index.test.ts @@ -268,7 +268,7 @@ describe("SDK", () => { const actual = await sdk.calculateFeePercentOnDestinationChain( amountToSend, sourceChainToken, - destinationChainToken, + destinationChainToken ); expect(actual).toBeCloseTo(expectedPercent, 2); }); @@ -287,7 +287,7 @@ describe("SDK", () => { const feePercentOnDestination = await sdk.calculateFeePercentOnDestinationChain( amountToSend, sourceChainToken, - destinationChainToken, + destinationChainToken ); const partAfterFeeOnSource = 1 - feePercentOnSource / 100; const partAfterFeeOnDestination = partAfterFeeOnSource - (partAfterFeeOnSource * feePercentOnDestination) / 100; @@ -324,7 +324,7 @@ describe("SDK", () => { const actual = sdk.getAverageTransferTime( sourceChainToken, destinationChainToken, - unsupportedMessenger as Messenger, + unsupportedMessenger as Messenger ); expect(actual).toBeNull(); }); @@ -475,7 +475,7 @@ describe("SDK", () => { expect(methodCallMock).toHaveBeenCalledTimes(1); expect(actual).toEqual(expected); scope.done(); - }, + } ); test.each([ @@ -536,7 +536,7 @@ describe("SDK", () => { expect(methodCallMock).toHaveBeenCalledTimes(1); expect(actual).toEqual(expected); scope.done(); - }, + } ); }); @@ -604,7 +604,7 @@ describe("SDK", () => { expect(methodCallMock).toHaveBeenCalledTimes(1); expect(actual).toEqual(expected); scope.done(); - }, + } ); }); }); @@ -735,7 +735,7 @@ describe("SDK", () => { formatAddress(trxChainToken.tokenAddress, ChainType.TRX, ChainType.EVM), "0x" + nonceBuffer.toString("hex"), Messenger.ALLBRIDGE, - 0, + 0 ); expect(transactionResponse).toEqual({ txId: transactionHash }); scope.done(); @@ -820,7 +820,7 @@ describe("SDK", () => { { type: "uint8", value: Messenger.ALLBRIDGE }, { type: "uint256", value: 0 }, ], - fromAccountAddress, + fromAccountAddress ); expect(methodSignMock).toHaveBeenCalledTimes(1); expect(methodSignMock).toBeCalledWith(rawTx); @@ -914,7 +914,7 @@ describe("SDK", () => { formatAddress(trxChainToken.tokenAddress, ChainType.TRX, ChainType.EVM), "0x" + nonceBuffer.toString("hex"), Messenger.ALLBRIDGE, - expectedFeeAmount, + expectedFeeAmount ); expect(transactionResponse).toEqual({ txId: transactionHash }); scope.done(); @@ -991,7 +991,7 @@ describe("SDK", () => { value: convertFloatAmountToInt(minimumReceiveAmount, trxChainToken.decimals).toFixed(), }, ], - accountAddress, + accountAddress ); expect(rawTransactionTransfer).toEqual(rawTx); }); @@ -1045,14 +1045,14 @@ describe("SDK", () => { [AmountFormat.INT]: fee, [AmountFormat.FLOAT]: convertIntAmountToFloat( fee, - Chains.getChainDecimalsByType(sourceChainToken.chainType), + Chains.getChainDecimalsByType(sourceChainToken.chainType) ).toFixed(), }, [FeePaymentMethod.WITH_STABLECOIN]: { [AmountFormat.INT]: expectedFeeAmountInStablecoin, [AmountFormat.FLOAT]: convertIntAmountToFloat( expectedFeeAmountInStablecoin, - sourceChainToken.decimals, + sourceChainToken.decimals ).toFixed(), }, }; @@ -1076,7 +1076,7 @@ describe("SDK", () => { [AmountFormat.INT]: fee, [AmountFormat.FLOAT]: convertIntAmountToFloat( fee, - Chains.getChainDecimalsByType(sourceChainToken.chainType), + Chains.getChainDecimalsByType(sourceChainToken.chainType) ).toFixed(), }, }; diff --git a/src/__tests__/mock/bridge/models/bridge.ts b/src/__tests__/mock/bridge/models/bridge.ts index 5237f59d..cbdb7d84 100644 --- a/src/__tests__/mock/bridge/models/bridge.ts +++ b/src/__tests__/mock/bridge/models/bridge.ts @@ -17,7 +17,7 @@ export class TestBridge extends ChainBridgeService { constructor( public params: SolanaBridgeParams, public api: AllbridgeCoreClient, - public chainType: ChainType, + public chainType: ChainType ) { super(); } diff --git a/src/__tests__/mock/utils.ts b/src/__tests__/mock/utils.ts index 2ad871b4..7cd50b2a 100644 --- a/src/__tests__/mock/utils.ts +++ b/src/__tests__/mock/utils.ts @@ -19,7 +19,7 @@ export function initChainsWithTestnet() { export function mockTokenInfoEndpoint( scope: nock.Scope, - pools: { token: TokenWithChainDetails; poolInfo: PoolInfo }[], + pools: { token: TokenWithChainDetails; poolInfo: PoolInfo }[] ) { let resultInfo = {}; for (const pool of pools) { diff --git a/src/__tests__/services/bridge/trx/index.test.ts b/src/__tests__/services/bridge/trx/index.test.ts index 4ce06efd..35d740a3 100644 --- a/src/__tests__/services/bridge/trx/index.test.ts +++ b/src/__tests__/services/bridge/trx/index.test.ts @@ -87,7 +87,7 @@ describe("TrxBridge", () => { { type: "uint8", value: messenger }, { type: "uint256", value: 0 }, ], - from, + from ); }); }); diff --git a/src/__tests__/services/liquidity-pool/trx/index.test.ts b/src/__tests__/services/liquidity-pool/trx/index.test.ts index 0a54501c..84f1aaf9 100644 --- a/src/__tests__/services/liquidity-pool/trx/index.test.ts +++ b/src/__tests__/services/liquidity-pool/trx/index.test.ts @@ -25,7 +25,7 @@ describe("TronPool", () => { const tronPool = new TronPoolService( tronWebMock as any as TronWeb, api as AllbridgeCoreClientWithPoolInfo, - LOCAL_NODE_URL, + LOCAL_NODE_URL ); beforeAll(() => { @@ -66,7 +66,7 @@ describe("TronPool", () => { value: amount, }, ], - ACCOUNT_ADDRESS, + ACCOUNT_ADDRESS ); }); @@ -95,7 +95,7 @@ describe("TronPool", () => { value: amount, }, ], - ACCOUNT_ADDRESS, + ACCOUNT_ADDRESS ); }); @@ -117,7 +117,7 @@ describe("TronPool", () => { callValue: +"0", }, [], - ACCOUNT_ADDRESS, + ACCOUNT_ADDRESS ); }); diff --git a/src/__tests__/utils/calculation/index.test.ts b/src/__tests__/utils/calculation/index.test.ts index 4b852b89..197f4b33 100644 --- a/src/__tests__/utils/calculation/index.test.ts +++ b/src/__tests__/utils/calculation/index.test.ts @@ -54,7 +54,7 @@ describe("Calculation", () => { "☀️ Convert %d with decimals %d to system precision -> %s", (amount, decimals, expectedSystemPrecisionAmount) => { expect(toSystemPrecision(amount, decimals)).toStrictEqual(expectedSystemPrecisionAmount); - }, + } ); test.each([ @@ -68,7 +68,7 @@ describe("Calculation", () => { "☀️ Convert %d from system precision to amount with decimals %d -> %s", (systemPrecisionAmount, decimals, expectedAmount) => { expect(fromSystemPrecision(systemPrecisionAmount, decimals)).toStrictEqual(expectedAmount); - }, + } ); }); diff --git a/src/chains/chain.enums.ts b/src/chains/chain.enums.ts index d342823c..b6aa13a3 100644 --- a/src/chains/chain.enums.ts +++ b/src/chains/chain.enums.ts @@ -58,6 +58,11 @@ export enum ChainSymbol { * The OP Mainnet network. */ OPT = "OPT", + + /** + * The SUI network. + */ + SUI = "SUI", } export enum ChainType { @@ -65,4 +70,5 @@ export enum ChainType { SOLANA = "SOLANA", TRX = "TRX", SRB = "SRB", + SUI = "SUI", } diff --git a/src/chains/index.ts b/src/chains/index.ts index 2088fcc9..9a90b4a3 100644 --- a/src/chains/index.ts +++ b/src/chains/index.ts @@ -10,6 +10,7 @@ const chainDecimalsByType: Record = { SOLANA: 9, TRX: 6, SRB: 7, + SUI: 9, }; const defaultProperties: Record = { @@ -81,6 +82,11 @@ const defaultProperties: Record = { name: "Stellar", chainType: ChainType.SRB, }, + [ChainSymbol.SUI]: { + chainSymbol: ChainSymbol.SUI, + name: "Sui", + chainType: ChainType.SUI, + }, }; export const Chains = (() => { diff --git a/src/client/core-api/api-client.ts b/src/client/core-api/api-client.ts index 15c7697b..7e4fcf16 100644 --- a/src/client/core-api/api-client.ts +++ b/src/client/core-api/api-client.ts @@ -96,7 +96,7 @@ export class ApiClientImpl implements ApiClient { headers: { "Content-Type": "application/json", }, - }, + } ); return mapPoolInfoResponseToPoolInfoMap(data); } diff --git a/src/client/core-api/core-api-mapper.ts b/src/client/core-api/core-api-mapper.ts index bfc43a5e..3bb471bd 100644 --- a/src/client/core-api/core-api-mapper.ts +++ b/src/client/core-api/core-api-mapper.ts @@ -103,6 +103,7 @@ function mapChainDetailsFromDto(chainSymbol: string, dto: ChainDetailsDTO): Chai transferTime: mapTransferTimeFromDto(dto.transferTime), txCostAmount: dto.txCostAmount, confirmations: dto.confirmations, + suiAddresses: dto.suiAddresses, }; return { ...chainDetails, diff --git a/src/client/core-api/core-api.model.ts b/src/client/core-api/core-api.model.ts index 83ce5fcf..a3a02c3b 100644 --- a/src/client/core-api/core-api.model.ts +++ b/src/client/core-api/core-api.model.ts @@ -1,5 +1,5 @@ import { ChainSymbol } from "../../chains/chain.enums"; -import { PoolInfo } from "../../tokens-info"; +import { PoolInfo, SuiAddresses } from "../../tokens-info"; export type ChainDetailsResponse = Record; @@ -10,6 +10,7 @@ export interface ChainDetailsDTO { transferTime: TransferTimeDTO; txCostAmount: TxCostAmountDTO; confirmations: number; + suiAddresses?: SuiAddresses; } export enum AddressStatus { diff --git a/src/client/core-api/core-client-filtered.ts b/src/client/core-api/core-client-filtered.ts index 0b60f2a1..42a14c6f 100644 --- a/src/client/core-api/core-client-filtered.ts +++ b/src/client/core-api/core-client-filtered.ts @@ -27,7 +27,7 @@ export class AllbridgeCoreClientFilteredImpl implements AllbridgeCoreClientFilte constructor( private client: AllbridgeCoreClientWithTokens & AllbridgeCoreClientPoolsExt, - params: AllbridgeCoreSdkOptions, + params: AllbridgeCoreSdkOptions ) { this.isStaging = params.coreApiQueryParams?.staging === "true"; } @@ -84,7 +84,7 @@ export class AllbridgeCoreClientFilteredImpl implements AllbridgeCoreClientFilte function filterAndConvertToTokenWithChainDetails( tokens: TokenWithChainDetailsWithFlags[], type: "swap" | "pool", - isStaging: boolean, + isStaging: boolean ): TokenWithChainDetails[] { return tokens.filter((token) => (isStaging ? true : token.flags[type])).map(convertToTokenWithChainDetails); } diff --git a/src/client/core-api/core-client-pool-info-caching.ts b/src/client/core-api/core-client-pool-info-caching.ts index 4d8a430e..127dde0a 100644 --- a/src/client/core-api/core-client-pool-info-caching.ts +++ b/src/client/core-api/core-client-pool-info-caching.ts @@ -71,7 +71,7 @@ export class AllbridgeCoreClientPoolInfoCaching implements AllbridgeCoreClientWi return result; } throw new SdkError( - "Cannot find pool info for " + poolKeyObject.poolAddress + " on chain " + poolKeyObject.chainSymbol, + "Cannot find pool info for " + poolKeyObject.poolAddress + " on chain " + poolKeyObject.chainSymbol ); } } diff --git a/src/configs/mainnet.ts b/src/configs/mainnet.ts index 064df3b2..d913de8f 100644 --- a/src/configs/mainnet.ts +++ b/src/configs/mainnet.ts @@ -12,7 +12,7 @@ export const mainnet: AllbridgeCoreSdkOptions = { cctpParams: { cctpTransmitterProgramId: "CCTPmbSD7gX1bxKPAmg77w8oFzNFpaQiQUWD43TKaecd", cctpTokenMessengerMinter: "CCTPiPYPc6AsJuwueEnWgSgucamXDZwBd53dQ11YiKX3", - cctpDomains: { ETH: 0, AVA: 1, OPT: 2, ARB: 3, SOL: 5, BAS: 6, POL: 7 }, + cctpDomains: { ETH: 0, AVA: 1, OPT: 2, ARB: 3, SOL: 5, BAS: 6, POL: 7, SUI: 8 }, }, cachePoolInfoChainSec: 20, }; @@ -34,4 +34,5 @@ export const nodeRpcUrlsDefault: NodeRpcUrls = { TRX: "https://api.trongrid.io", SRB: "https://rpc.stellar.org:443", STLR: "https://horizon.stellar.org", + SUI: "https://fullnode.mainnet.sui.io", }; diff --git a/src/exceptions/exceptions.ts b/src/exceptions/exceptions.ts index ff972c44..b1651c72 100644 --- a/src/exceptions/exceptions.ts +++ b/src/exceptions/exceptions.ts @@ -77,7 +77,7 @@ export class ArgumentInvalidDecimalsError extends SdkRootError { constructor(argName: string, decimalsIs: number, decimalsRequired: number) { super( ErrorCode.ARGUMENT_INVALID_DECIMALS_ERROR, - `Argument '${argName}' decimals '${decimalsIs}' cannot be greater than '${decimalsRequired}'`, + `Argument '${argName}' decimals '${decimalsIs}' cannot be greater than '${decimalsRequired}'` ); } } @@ -104,7 +104,7 @@ export class TxTooLargeError extends SdkRootError { constructor() { super( ErrorCode.TX_TOO_LARGE, - "Transaction too large: try again later or switch to another messenger or pay relayer fee in native gas currency", + "Transaction too large: try again later or switch to another messenger or pay relayer fee in native gas currency" ); } } diff --git a/src/index.ts b/src/index.ts index 373a3b13..77574f15 100644 --- a/src/index.ts +++ b/src/index.ts @@ -195,7 +195,7 @@ export class AllbridgeCoreSdk { // eslint-disable-next-line @typescript-eslint/no-unused-vars recipientAddress: string, // eslint-disable-next-line @typescript-eslint/no-unused-vars - tokenAddress?: string, + tokenAddress?: string ): Promise { return await this.service.checkAddress(); } @@ -212,7 +212,7 @@ export class AllbridgeCoreSdk { amount: string, amountFormat: AmountFormat, sourceToken: TokenWithChainDetails, - destToken: TokenWithChainDetails, + destToken: TokenWithChainDetails ): Promise { return this.service.getPendingStatusInfo(amount, amountFormat, sourceToken, destToken); } @@ -247,7 +247,7 @@ export class AllbridgeCoreSdk { */ async calculateFeePercentOnSourceChain( amountFloat: BigSource, - sourceChainToken: TokenWithChainDetails, + sourceChainToken: TokenWithChainDetails ): Promise { return this.service.calculateFeePercentOnSourceChain(amountFloat, sourceChainToken); } @@ -265,7 +265,7 @@ export class AllbridgeCoreSdk { async calculateFeePercentOnDestinationChain( amountFloat: BigSource, sourceChainToken: TokenWithChainDetails, - destinationChainToken: TokenWithChainDetails, + destinationChainToken: TokenWithChainDetails ): Promise { return this.service.calculateFeePercentOnDestinationChain(amountFloat, sourceChainToken, destinationChainToken); } @@ -282,13 +282,13 @@ export class AllbridgeCoreSdk { amountToSendFloat: BigSource, sourceChainToken: TokenWithChainDetails, destinationChainToken: TokenWithChainDetails, - messenger: Messenger, + messenger: Messenger ): Promise { return this.service.getAmountToBeReceivedAndGasFeeOptions( amountToSendFloat, sourceChainToken, destinationChainToken, - messenger, + messenger ); } @@ -304,13 +304,13 @@ export class AllbridgeCoreSdk { amountToBeReceivedFloat: BigSource, sourceChainToken: TokenWithChainDetails, destinationChainToken: TokenWithChainDetails, - messenger: Messenger, + messenger: Messenger ): Promise { return this.service.getAmountToSendAndGasFeeOptions( amountToBeReceivedFloat, sourceChainToken, destinationChainToken, - messenger, + messenger ); } @@ -330,7 +330,7 @@ export class AllbridgeCoreSdk { * Optional. * The {@link Messenger.ALLBRIDGE}, {@link Messenger.WORMHOLE} by default. */ - messenger?: Messenger, + messenger?: Messenger ): Promise { return this.service.getAmountToBeReceived(amountToSendFloat, sourceChainToken, destinationChainToken, messenger); } @@ -355,7 +355,7 @@ export class AllbridgeCoreSdk { */ messenger?: Messenger, sourceProvider?: Provider, - destinationProvider?: Provider, + destinationProvider?: Provider ): Promise { return this.service.getAmountToBeReceivedFromChain( amountToSendFloat, @@ -363,7 +363,7 @@ export class AllbridgeCoreSdk { destinationChainToken, messenger, sourceProvider, - destinationProvider, + destinationProvider ); } @@ -382,7 +382,7 @@ export class AllbridgeCoreSdk { destinationChainToken: TokenWithChainDetails, sourcePool: PoolInfo, destinationPool: PoolInfo, - messenger?: Messenger, + messenger?: Messenger ): string { return this.service.getAmountToBeReceivedFromPools( amountToSendFloat, @@ -390,7 +390,7 @@ export class AllbridgeCoreSdk { destinationChainToken, sourcePool, destinationPool, - messenger, + messenger ); } @@ -410,7 +410,7 @@ export class AllbridgeCoreSdk { * Optional. * The {@link Messenger.ALLBRIDGE}, {@link Messenger.WORMHOLE} by default. */ - messenger?: Messenger, + messenger?: Messenger ): Promise { return this.service.getAmountToSend(amountToBeReceivedFloat, sourceChainToken, destinationChainToken, messenger); } @@ -435,7 +435,7 @@ export class AllbridgeCoreSdk { */ messenger?: Messenger, sourceProvider?: Provider, - destinationProvider?: Provider, + destinationProvider?: Provider ): Promise { return this.service.getAmountToSendFromChain( amountToBeReceivedFloat, @@ -443,7 +443,7 @@ export class AllbridgeCoreSdk { destinationChainToken, messenger, sourceProvider, - destinationProvider, + destinationProvider ); } @@ -462,7 +462,7 @@ export class AllbridgeCoreSdk { destinationChainToken: TokenWithChainDetails, sourcePool: PoolInfo, destinationPool: PoolInfo, - messenger?: Messenger, + messenger?: Messenger ): string { return this.service.getAmountToSendFromPools( amountToBeReceivedFloat, @@ -470,7 +470,7 @@ export class AllbridgeCoreSdk { destinationChainToken, sourcePool, destinationPool, - messenger, + messenger ); } @@ -484,7 +484,7 @@ export class AllbridgeCoreSdk { async getGasFeeOptions( sourceChainToken: TokenWithChainDetails, destinationChainToken: TokenWithChainDetails, - messenger: Messenger, + messenger: Messenger ): Promise { return this.service.getGasFeeOptions(sourceChainToken, destinationChainToken, messenger); } @@ -499,7 +499,7 @@ export class AllbridgeCoreSdk { getAverageTransferTime( sourceChainToken: TokenWithChainDetails, destinationChainToken: TokenWithChainDetails, - messenger: Messenger, + messenger: Messenger ): number | null { return this.service.getAverageTransferTime(sourceChainToken, destinationChainToken, messenger); } @@ -541,7 +541,7 @@ export class AllbridgeCoreSdk { */ async getExtraGasMaxLimits( sourceChainToken: TokenWithChainDetails, - destinationChainToken: TokenWithChainDetails, + destinationChainToken: TokenWithChainDetails ): Promise { return this.service.getExtraGasMaxLimits(sourceChainToken, destinationChainToken); } @@ -555,7 +555,7 @@ export class AllbridgeCoreSdk { async getVUsdFromAmount( amount: string, amountFormat: AmountFormat, - sourceToken: TokenWithChainDetails, + sourceToken: TokenWithChainDetails ): Promise { return this.service.getVUsdFromAmount(amount, amountFormat, sourceToken); } @@ -578,7 +578,7 @@ export class AllbridgeCoreSdk { async swapAndBridgeFeeCalculation( amountInTokenPrecision: string, sourceToken: TokenWithChainDetails, - destToken: TokenWithChainDetails, + destToken: TokenWithChainDetails ): Promise { return this.service.swapAndBridgeFeeCalculation(amountInTokenPrecision, sourceToken, destToken); } @@ -592,7 +592,7 @@ export class AllbridgeCoreSdk { async swapAndBridgeFeeCalculationReverse( amountInTokenPrecision: string, sourceToken: TokenWithChainDetails, - destToken: TokenWithChainDetails, + destToken: TokenWithChainDetails ): Promise { return this.service.swapAndBridgeFeeCalculationReverse(amountInTokenPrecision, sourceToken, destToken); } @@ -604,7 +604,7 @@ export class AllbridgeCoreSdk { amount: string, amountFormat: AmountFormat, sourceToken: TokenWithChainDetails, - destToken: TokenWithChainDetails, + destToken: TokenWithChainDetails ): Promise { return this.service.getSendAmountDetails(amount, amountFormat, sourceToken, destToken); } diff --git a/src/models/index.ts b/src/models/index.ts index cccbf064..fc568751 100644 --- a/src/models/index.ts +++ b/src/models/index.ts @@ -26,6 +26,7 @@ export { TokenWithChainDetails, TransferTime, TxCostAmount, + SuiAddresses, MessengerTransferTime, } from "../tokens-info/tokens-info.model"; export { diff --git a/src/services/bridge/evm/index.ts b/src/services/bridge/evm/index.ts index d55bed8f..6b83c591 100644 --- a/src/services/bridge/evm/index.ts +++ b/src/services/bridge/evm/index.ts @@ -1,5 +1,3 @@ -import * as anchor from "@project-serum/anchor"; -import { PublicKey } from "@solana/web3.js"; import { Big } from "big.js"; import BN from "bn.js"; import { Contract, Transaction as Web3Transaction } from "web3"; @@ -11,7 +9,6 @@ import { FeePaymentMethod, Messenger, EssentialWeb3, - SdkError, SwapParams, TransactionResponse, } from "../../../models"; @@ -19,10 +16,9 @@ import { NodeRpcUrlsConfig } from "../../index"; import { RawTransaction } from "../../models"; import Bridge from "../../models/abi/Bridge"; import CctpBridge from "../../models/abi/CctpBridge"; -import { getAssociatedAccount } from "../../utils/sol/accounts"; -import { buildAnchorProvider } from "../../utils/sol/anchor-provider"; +import { getCctpSolTokenRecipientAddress } from "../get-cctp-sol-token-recipient-address"; import { SendParams, ChainBridgeService, TxSwapParamsEvm, TxSendParamsEvm } from "../models"; -import { formatAddress, getNonce, prepareTxSendParams, prepareTxSwapParams } from "../utils"; +import { getNonce, prepareTxSendParams, prepareTxSwapParams } from "../utils"; export class EvmBridgeService extends ChainBridgeService { chainType: ChainType.EVM = ChainType.EVM; @@ -30,7 +26,7 @@ export class EvmBridgeService extends ChainBridgeService { constructor( public web3: EssentialWeb3, public api: AllbridgeCoreClient, - private nodeRpcUrlsConfig: NodeRpcUrlsConfig, + private nodeRpcUrlsConfig: NodeRpcUrlsConfig ) { super(); } @@ -63,7 +59,7 @@ export class EvmBridgeService extends ChainBridgeService { fromTokenAddress, toTokenAddress, toAccountAddress, - minimumReceiveAmount, + minimumReceiveAmount ); return Promise.resolve({ @@ -112,7 +108,7 @@ export class EvmBridgeService extends ChainBridgeService { toTokenAddress, nonce, messenger, - totalFee, + totalFee ); value = "0"; } else { @@ -124,7 +120,7 @@ export class EvmBridgeService extends ChainBridgeService { toTokenAddress, nonce, messenger, - 0, + 0 ); value = totalFee; } @@ -141,7 +137,7 @@ export class EvmBridgeService extends ChainBridgeService { private async buildRawTransactionCctpSend( params: SendParams, txSendParams: TxSendParamsEvm, - totalFee: string, + totalFee: string ): Promise<{ sendMethod: PayableMethodObject; value: string; @@ -153,52 +149,29 @@ export class EvmBridgeService extends ChainBridgeService { let value: string; if (params.destinationToken.chainType === ChainType.SOLANA) { - let recipientWalletAddress: string; - const receiverAccount = new PublicKey(params.toAccountAddress); - const receiveMint = new PublicKey(params.destinationToken.tokenAddress); - const receiveUserToken = await getAssociatedAccount(receiverAccount, receiveMint); - const provider = buildAnchorProvider( - this.nodeRpcUrlsConfig.getNodeRpcUrl(ChainSymbol.SOL), + const recipient = await getCctpSolTokenRecipientAddress( + this.chainType, params.toAccountAddress, + params.destinationToken.tokenAddress, + this.nodeRpcUrlsConfig.getNodeRpcUrl(ChainSymbol.SOL) ); - anchor.setProvider(provider); - const accountData = await anchor.Spl.token(provider).account.token.fetchNullable(receiveUserToken); - if (accountData?.authority.equals(receiverAccount)) { - recipientWalletAddress = formatAddress(receiveUserToken.toBase58(), ChainType.SOLANA, this.chainType); - } else { - const tokenAccounts = await provider.connection.getTokenAccountsByOwner(receiverAccount, { - mint: receiveMint, - }); - if (tokenAccounts.value.length === 0 && !accountData) { - recipientWalletAddress = formatAddress(receiveUserToken.toBase58(), ChainType.SOLANA, this.chainType); - } else if (tokenAccounts.value.length > 0) { - const firstTokenAccount = tokenAccounts.value[0]; - - if (!firstTokenAccount?.pubkey) { - throw new SdkError("First token account or its public key is undefined"); - } - recipientWalletAddress = formatAddress(firstTokenAccount.pubkey.toBase58(), ChainType.SOLANA, this.chainType); - } else { - throw new SdkError("Associated account has wrong owner"); - } - } if (gasFeePaymentMethod === FeePaymentMethod.WITH_STABLECOIN) { sendMethod = cctpBridgeContract.methods.bridgeWithWalletAddress( amount, - recipientWalletAddress, + recipient, toAccountAddress, toChainId, - totalFee, + totalFee ); value = "0"; } else { sendMethod = cctpBridgeContract.methods.bridgeWithWalletAddress( amount, - recipientWalletAddress, + recipient, toAccountAddress, toChainId, - 0, + 0 ); value = totalFee; } diff --git a/src/services/bridge/get-cctp-sol-token-recipient-address.ts b/src/services/bridge/get-cctp-sol-token-recipient-address.ts new file mode 100644 index 00000000..e5eeacdc --- /dev/null +++ b/src/services/bridge/get-cctp-sol-token-recipient-address.ts @@ -0,0 +1,69 @@ +import * as anchor from "@project-serum/anchor"; +import { PublicKey } from "@solana/web3.js"; +import { ChainType } from "../../chains/chain.enums"; +import { SdkError } from "../../exceptions"; +import { getAssociatedAccount } from "../utils/sol/accounts"; +import { buildAnchorProvider } from "../utils/sol/anchor-provider"; +import { formatAddress } from "./utils"; + +// 1. OVERLOADS +export function getCctpSolTokenRecipientAddress( + chainType: ChainType.EVM | ChainType.SUI, + toAccountAddress: string, + destinationTokenAddress: string, + solRpcUrl: string +): Promise; +export function getCctpSolTokenRecipientAddress( + chainType: ChainType.TRX, + toAccountAddress: string, + destinationTokenAddress: string, + solRpcUrl: string +): Promise; +export function getCctpSolTokenRecipientAddress( + chainType: ChainType.SOLANA | ChainType.SRB, + toAccountAddress: string, + destinationTokenAddress: string, + solRpcUrl: string +): Promise; +export function getCctpSolTokenRecipientAddress( + chainType: ChainType, + toAccountAddress: string, + destinationTokenAddress: string, + solRpcUrl: string +): Promise; + +// 2. COMMON Realization +export async function getCctpSolTokenRecipientAddress( + chainType: ChainType, + toAccountAddress: string, + destinationTokenAddress: string, + solRpcUrl: string +): Promise { + let recipientWalletAddress: string | number[] | Buffer; + const receiverAccount = new PublicKey(toAccountAddress); + const receiveMint = new PublicKey(destinationTokenAddress); + const receiveUserToken = await getAssociatedAccount(receiverAccount, receiveMint); + const provider = buildAnchorProvider(solRpcUrl, toAccountAddress); + anchor.setProvider(provider); + const accountData = await anchor.Spl.token(provider).account.token.fetchNullable(receiveUserToken); + if (accountData?.authority.equals(receiverAccount)) { + recipientWalletAddress = formatAddress(receiveUserToken.toBase58(), ChainType.SOLANA, chainType); + } else { + const tokenAccounts = await provider.connection.getTokenAccountsByOwner(receiverAccount, { + mint: receiveMint, + }); + if (tokenAccounts.value.length === 0 && !accountData) { + recipientWalletAddress = formatAddress(receiveUserToken.toBase58(), ChainType.SOLANA, chainType); + } else if (tokenAccounts.value.length > 0) { + const firstTokenAccount = tokenAccounts.value[0]; + + if (!firstTokenAccount?.pubkey) { + throw new SdkError("First token account or its public key is undefined"); + } + recipientWalletAddress = formatAddress(firstTokenAccount.pubkey.toBase58(), ChainType.SOLANA, chainType); + } else { + throw new SdkError("Associated account has wrong owner"); + } + } + return recipientWalletAddress; +} diff --git a/src/services/bridge/index.ts b/src/services/bridge/index.ts index d12643b1..5bce420a 100644 --- a/src/services/bridge/index.ts +++ b/src/services/bridge/index.ts @@ -15,6 +15,7 @@ import { ApproveParams, CheckAllowanceParams, GetAllowanceParams, SendParams, Ch import { DefaultRawBridgeTransactionBuilder, RawBridgeTransactionBuilder } from "./raw-bridge-transaction-builder"; import { SolanaBridgeService } from "./sol"; import { SrbBridgeService } from "./srb"; +import { SuiBridgeService } from "./sui"; import { TronBridgeService } from "./trx"; export interface BridgeService { @@ -77,7 +78,7 @@ export class DefaultBridgeService implements BridgeService { private api: AllbridgeCoreClient, private nodeRpcUrlsConfig: NodeRpcUrlsConfig, private params: AllbridgeCoreSdkOptions, - private tokenService: TokenService, + private tokenService: TokenService ) { this.rawTxBuilder = new DefaultRawBridgeTransactionBuilder(api, nodeRpcUrlsConfig, params, tokenService); } @@ -121,7 +122,7 @@ export class DefaultBridgeService implements BridgeService { this.api, this.nodeRpcUrlsConfig, this.params, - provider, + provider ).send(params); } } @@ -143,7 +144,7 @@ export function getChainBridgeService( api: AllbridgeCoreClient, nodeRpcUrlsConfig: NodeRpcUrlsConfig, params: AllbridgeCoreSdkOptions, - provider?: Provider, + provider?: Provider ): ChainBridgeService { switch (Chains.getChainProperty(chainSymbol).chainType) { case ChainType.EVM: { @@ -165,7 +166,7 @@ export function getChainBridgeService( solidityNode: nodeRpcUrl, eventServer: nodeRpcUrl, }), - api, + api ); } } @@ -179,11 +180,14 @@ export function getChainBridgeService( jupiterUrl: params.jupiterUrl, jupiterMaxAccounts: params.jupiterMaxAccounts, }, - api, + api ); } case ChainType.SRB: { return new SrbBridgeService(nodeRpcUrlsConfig, params, api); } + case ChainType.SUI: { + return new SuiBridgeService(nodeRpcUrlsConfig, api); + } } } diff --git a/src/services/bridge/models/bridge.model.ts b/src/services/bridge/models/bridge.model.ts index eb8feec1..35e01d96 100644 --- a/src/services/bridge/models/bridge.model.ts +++ b/src/services/bridge/models/bridge.model.ts @@ -170,6 +170,7 @@ export interface CheckAllowanceParams extends GetAllowanceParams { * @internal */ export type TxSwapParamsEvm = TxSwapParamsTyped; +export type TxSwapParamsSui = TxSwapParamsTyped; export type TxSwapParamsTrx = TxSwapParamsTyped; export type TxSwapParamsSol = TxSwapParamsTyped; export type TxSwapParamsSrb = TxSwapParamsTyped; @@ -184,12 +185,13 @@ export interface TxSwapParamsTyped { minimumReceiveAmount: string; } -export type TxSwapParams = TxSwapParamsEvm | TxSwapParamsTrx | TxSwapParamsSol | TxSwapParamsSrb; +export type TxSwapParams = TxSwapParamsEvm | TxSwapParamsTrx | TxSwapParamsSol | TxSwapParamsSrb | TxSwapParamsSui; /** * @internal */ export type TxSendParamsEvm = TxSendParamsTyped; +export type TxSendParamsSui = TxSendParamsTyped; export type TxSendParamsTrx = TxSendParamsTyped; export type TxSendParamsSol = TxSendParamsTyped; export type TxSendParamsSrb = TxSendParamsTyped; @@ -216,4 +218,4 @@ export interface TxSendParamsTyped { gasFeePaymentMethod: FeePaymentMethod; } -export type TxSendParams = TxSendParamsEvm | TxSendParamsTrx | TxSendParamsSol | TxSendParamsSrb; +export type TxSendParams = TxSendParamsEvm | TxSendParamsTrx | TxSendParamsSol | TxSendParamsSrb | TxSendParamsSui; diff --git a/src/services/bridge/raw-bridge-transaction-builder.ts b/src/services/bridge/raw-bridge-transaction-builder.ts index 96913dc7..c0af1665 100644 --- a/src/services/bridge/raw-bridge-transaction-builder.ts +++ b/src/services/bridge/raw-bridge-transaction-builder.ts @@ -33,7 +33,7 @@ export class DefaultRawBridgeTransactionBuilder implements RawBridgeTransactionB private api: AllbridgeCoreClient, private nodeRpcUrlsConfig: NodeRpcUrlsConfig, private params: AllbridgeCoreSdkOptions, - private tokenService: TokenService, + private tokenService: TokenService ) {} async approve(a: Provider | ApproveParams, b?: ApproveParams): Promise { @@ -51,7 +51,7 @@ export class DefaultRawBridgeTransactionBuilder implements RawBridgeTransactionB ...approveData, spender, }, - provider, + provider ); } @@ -64,7 +64,7 @@ export class DefaultRawBridgeTransactionBuilder implements RawBridgeTransactionB this.api, this.nodeRpcUrlsConfig, this.params, - provider, + provider ).buildRawTransactionSend(params); } return getChainBridgeService( @@ -72,7 +72,7 @@ export class DefaultRawBridgeTransactionBuilder implements RawBridgeTransactionB this.api, this.nodeRpcUrlsConfig, this.params, - provider, + provider ).buildRawTransactionSwap(params); } } diff --git a/src/services/bridge/sol/index.ts b/src/services/bridge/sol/index.ts index 5327b9c6..b21c9b95 100644 --- a/src/services/bridge/sol/index.ts +++ b/src/services/bridge/sol/index.ts @@ -88,7 +88,7 @@ export class SolanaBridgeService extends ChainBridgeService { constructor( public solanaRpcUrl: string, public params: SolanaBridgeParams, - public api: AllbridgeCoreClient, + public api: AllbridgeCoreClient ) { super(); this.jupiterService = new JupiterService(solanaRpcUrl, params.jupiterUrl, params.jupiterMaxAccounts); @@ -100,7 +100,7 @@ export class SolanaBridgeService extends ChainBridgeService { txSwapParams, params.sourceToken.poolAddress, params.destinationToken.poolAddress, - params.txFeeParams, + params.txFeeParams ); } @@ -108,7 +108,7 @@ export class SolanaBridgeService extends ChainBridgeService { params: TxSwapParamsSol, poolAddress: string, toPoolAddress: string, - txFeeParams?: TxFeeParams, + txFeeParams?: TxFeeParams ): Promise { const { fromAccountAddress, @@ -238,7 +238,7 @@ export class SolanaBridgeService extends ChainBridgeService { const swapAndBridgeSolData = await this.prepareSwapAndBridgeCctpData(solTxSendParams); const { transaction, messageSentEventDataKeypair } = await this.buildSwapAndBridgeCctpTransaction( params.destinationToken.chainSymbol, - swapAndBridgeSolData, + swapAndBridgeSolData ); swapAndBridgeTx = transaction; requiredMessageSigner = messageSentEventDataKeypair; @@ -264,7 +264,7 @@ export class SolanaBridgeService extends ChainBridgeService { private async processJup( solTxSendParams: SolTxSendParams, params: SendParams, - exactOut: boolean, + exactOut: boolean ): Promise<{ tx: VersionedTransaction; solTxSendUpdatedParams: { @@ -276,7 +276,7 @@ export class SolanaBridgeService extends ChainBridgeService { }> { const { fee, extraGas, gasFeePaymentMethod } = await this.convertStableCoinFeeAndExtraGasToNativeCurrency( params.sourceToken.decimals, - solTxSendParams, + solTxSendParams ); let amountToProcess = exactOut ? Big(fee) : Big(solTxSendParams.fee); @@ -291,7 +291,7 @@ export class SolanaBridgeService extends ChainBridgeService { params.fromAccountAddress, params.sourceToken.tokenAddress, amountToProcess.toFixed(0), - exactOut, + exactOut ); let newAmount: string; @@ -307,8 +307,8 @@ export class SolanaBridgeService extends ChainBridgeService { throw new AmountNotEnoughError( `Amount not enough to pay fee, ${convertIntAmountToFloat( Big(newAmount).minus(1).neg(), - params.sourceToken.decimals, - ).toFixed()} stables is missing`, + params.sourceToken.decimals + ).toFixed()} stables is missing` ); } return { @@ -331,7 +331,7 @@ export class SolanaBridgeService extends ChainBridgeService { async convertStableCoinFeeAndExtraGasToNativeCurrency( tokenDecimals: number, - solTxSendParams: SolTxSendParams, + solTxSendParams: SolTxSendParams ): Promise<{ fee: string; extraGas?: string; gasFeePaymentMethod: FeePaymentMethod }> { if (solTxSendParams.gasFeePaymentMethod == FeePaymentMethod.WITH_STABLECOIN) { const sourceNativeTokenPrice = ( @@ -364,7 +364,7 @@ export class SolanaBridgeService extends ChainBridgeService { private getExtraGasInstruction( extraGas: string, userAccount: PublicKey, - configAccount: PublicKey, + configAccount: PublicKey ): TransactionInstruction | undefined { return web3.SystemProgram.transfer({ fromPubkey: userAccount, @@ -408,7 +408,7 @@ export class SolanaBridgeService extends ChainBridgeService { const otherBridgeTokenAccount = await getOtherChainTokenAccount( destinationChainId, Buffer.from(receiveTokenAddress), - bridge.programId, + bridge.programId ); const configAccount = await getConfigAccount(bridge.programId); @@ -455,14 +455,14 @@ export class SolanaBridgeService extends ChainBridgeService { swapAndBridgeData.extraGasInstruction = this.getExtraGasInstruction( extraGas, swapAndBridgeData.userAccount, - configAccount, + configAccount ); } return swapAndBridgeData; } private async buildSwapAndBridgeAllbridgeTransaction( - swapAndBridgeData: SwapAndBridgeSolData, + swapAndBridgeData: SwapAndBridgeSolData ): Promise { const { bridge, @@ -553,7 +553,7 @@ export class SolanaBridgeService extends ChainBridgeService { } private async buildSwapAndBridgeWormholeTransaction( - swapAndBridgeData: SwapAndBridgeSolData, + swapAndBridgeData: SwapAndBridgeSolData ): Promise<{ transaction: VersionedTransaction; messageAccount: Keypair }> { const { bridge, @@ -582,20 +582,20 @@ export class SolanaBridgeService extends ChainBridgeService { const [whBridgeAccount] = PublicKey.findProgramAddressSync( [Buffer.from("Bridge")], - new PublicKey(wormholeProgramId), + new PublicKey(wormholeProgramId) ); const [whFeeCollectorAccount] = PublicKey.findProgramAddressSync( [Buffer.from("fee_collector")], - new PublicKey(wormholeProgramId), + new PublicKey(wormholeProgramId) ); const [whSequenceAccount] = PublicKey.findProgramAddressSync( [Buffer.from("Sequence"), bridgeAuthority.toBuffer()], - new PublicKey(wormholeProgramId), + new PublicKey(wormholeProgramId) ); const messengerGasUsageAccount = await getGasUsageAccount( destinationChainId, - configAccountInfo.wormholeMessengerProgramId, + configAccountInfo.wormholeMessengerProgramId ); const wormholeMessengerConfigAccount = await getConfigAccount(configAccountInfo.wormholeMessengerProgramId); const messageAccount = Keypair.generate(); @@ -718,7 +718,7 @@ export class SolanaBridgeService extends ChainBridgeService { swapAndBridgeData.extraGasInstruction = this.getExtraGasInstruction( extraGas, swapAndBridgeData.userAccount, - cctpBridgeAccount, + cctpBridgeAccount ); } return swapAndBridgeData; @@ -726,7 +726,7 @@ export class SolanaBridgeService extends ChainBridgeService { async buildSwapAndBridgeCctpTransaction( destinationChainSymbol: string, - swapAndBridgeData: SwapAndBridgeSolDataCctpData, + swapAndBridgeData: SwapAndBridgeSolDataCctpData ): Promise<{ transaction: VersionedTransaction; messageSentEventDataKeypair: Keypair }> { const { cctpBridge, diff --git a/src/services/bridge/sol/jupiter.ts b/src/services/bridge/sol/jupiter.ts index 8a990d94..c8d4032b 100644 --- a/src/services/bridge/sol/jupiter.ts +++ b/src/services/bridge/sol/jupiter.ts @@ -19,7 +19,7 @@ export class JupiterService { userAddress: string, stableTokenAddress: string, amount: string, - exactOut: boolean, + exactOut: boolean ): Promise<{ tx: VersionedTransaction; amountIn?: string }> { let quoteResponse: any; try { @@ -73,7 +73,7 @@ export class JupiterService { async amendJupiterWithSdkTx( transaction: VersionedTransaction, - sdkTx: VersionedTransaction, + sdkTx: VersionedTransaction ): Promise { try { const addressLookupTableAccounts = await fetchAddressLookupTableAccountsFromTx(transaction, this.connection); diff --git a/src/services/bridge/srb/index.ts b/src/services/bridge/srb/index.ts index 50c7534b..68c9d195 100644 --- a/src/services/bridge/srb/index.ts +++ b/src/services/bridge/srb/index.ts @@ -18,7 +18,7 @@ export class SrbBridgeService extends ChainBridgeService { constructor( readonly nodeRpcUrlsConfig: NodeRpcUrlsConfig, readonly params: AllbridgeCoreSdkOptions, - readonly api: AllbridgeCoreClient, + readonly api: AllbridgeCoreClient ) { super(); } diff --git a/src/services/bridge/sui/index.ts b/src/services/bridge/sui/index.ts new file mode 100644 index 00000000..fa246afc --- /dev/null +++ b/src/services/bridge/sui/index.ts @@ -0,0 +1,315 @@ +import { SuiClient } from "@mysten/sui/client"; +import { CoinStruct } from "@mysten/sui/src/client/types/generated"; +import { coinWithBalance, Transaction, TransactionResult } from "@mysten/sui/transactions"; +import { SUI_CLOCK_OBJECT_ID } from "@mysten/sui/utils"; +import { Big } from "big.js"; +import { AllbridgeCoreClient } from "../../../client/core-api/core-client-base"; +import { + ChainSymbol, + ChainType, + FeePaymentMethod, + Messenger, + RawSuiTransaction, + SdkError, + SwapParams, + TransactionResponse, +} from "../../../models"; +import { SuiAddresses } from "../../../tokens-info"; +import { NodeRpcUrlsConfig } from "../../index"; +import { setAddress } from "../../models/sui/bridge"; +import { swap, swapAndBridge, swapAndBridgeWormhole } from "../../models/sui/bridge/bridge-interface/functions"; +import { setAddress as setCctpAddress } from "../../models/sui/cctp-bridge"; +import { bridge } from "../../models/sui/cctp-bridge/cctp-bridge-interface/functions"; +import { setAddress as setUtilsAddress } from "../../models/sui/utils"; +import { fromHex } from "../../models/sui/utils/bytes32/functions"; +import { fetchAllPagesRecursive } from "../../utils/sui/paginated"; +import { getCctpSolTokenRecipientAddress } from "../get-cctp-sol-token-recipient-address"; +import { ChainBridgeService, SendParams, TxSendParamsSui, TxSwapParamsSui } from "../models"; +import { getNonceBigInt, normalizeSuiHex, prepareTxSendParams, prepareTxSwapParams } from "../utils"; + +export class SuiBridgeService extends ChainBridgeService { + chainType: ChainType.SUI = ChainType.SUI; + chainSymbol: ChainSymbol.SUI = ChainSymbol.SUI; + + private readonly client: SuiClient; + + constructor( + private nodeRpcUrlsConfig: NodeRpcUrlsConfig, + public api: AllbridgeCoreClient + ) { + super(); + this.client = new SuiClient({ + url: nodeRpcUrlsConfig.getNodeRpcUrl(this.chainSymbol), + }); + } + + send(): Promise { + throw new SdkError("Method send not implemented."); + } + + async buildRawTransactionSwap(params: SwapParams): Promise { + const suiAddresses = params.sourceToken.suiAddresses; + if (!suiAddresses) { + throw new SdkError("SUI token must contain 'suiAddresses'"); + } + setAddress(suiAddresses.bridgeAddress, suiAddresses.bridgeAddressOrigin); + + const txSwapParams = prepareTxSwapParams(this.chainType, params); + return await this.buildRawTransactionSwapFromParams(txSwapParams, suiAddresses); + } + + async buildRawTransactionSwapFromParams( + params: TxSwapParamsSui, + suiAddresses: SuiAddresses + ): Promise { + const { amount, fromAccountAddress, fromTokenAddress, toTokenAddress, minimumReceiveAmount } = params; + + const tx = new Transaction(); + tx.setSender(fromAccountAddress); + + const args = { + bridge: suiAddresses.bridgeObjectAddress, + coin: coinWithBalance({ balance: BigInt(amount), type: fromTokenAddress }), + receiveAmountMin: BigInt(minimumReceiveAmount), + }; + const swapResult = swap(tx, [fromTokenAddress, toTokenAddress], args); + + const coins: CoinStruct[] = await fetchAllPagesRecursive((cursor: string | null | undefined) => + this.client.getCoins({ + owner: params.toAccountAddress, + coinType: toTokenAddress, + cursor, + }) + ); + if (coins.length === 0 || !coins[0]) { + tx.transferObjects([swapResult], params.toAccountAddress); + } else { + tx.mergeCoins(coins[0].coinObjectId, [swapResult]); + } + return await tx.toJSON({ client: this.client }); + } + + async buildRawTransactionSend(params: SendParams): Promise { + const txSendParams = await prepareTxSendParams(this.chainType, params, this.api); + const { messenger } = txSendParams; + + const suiAddresses = params.sourceToken.suiAddresses; + if (!suiAddresses) { + throw new SdkError("SUI token must contain 'suiAddresses'"); + } + setAddress(suiAddresses.bridgeAddress, suiAddresses.bridgeAddressOrigin); + setUtilsAddress(suiAddresses.utilsAddress); + + switch (messenger) { + case Messenger.ALLBRIDGE: + return this.buildRawTransactionAllbridgeSend(txSendParams, suiAddresses); + case Messenger.WORMHOLE: + return this.buildRawTransactionWormholeSend(txSendParams, suiAddresses); + case Messenger.CCTP: + return this.buildRawTransactionCctpSend(params, txSendParams, suiAddresses); + } + } + + private async buildRawTransactionAllbridgeSend( + txSendParams: TxSendParamsSui, + suiAddresses: SuiAddresses + ): Promise { + const { + amount, + fromAccountAddress, + fromTokenAddress, + toChainId, + toAccountAddress, + toTokenAddress, + fee, + gasFeePaymentMethod, + extraGas, + } = txSendParams; + let totalFee = fee; + if (extraGas) { + totalFee = Big(totalFee).plus(extraGas).toFixed(); + } + + const tx = new Transaction(); + tx.setSender(fromAccountAddress); + if (gasFeePaymentMethod === FeePaymentMethod.WITH_STABLECOIN) { + const amountWithoutFee = BigInt(amount) - BigInt(totalFee); + const args = { + bridge: suiAddresses.bridgeObjectAddress, + messenger: suiAddresses.allbridgeMessengerObjectAddress, + amount: coinWithBalance({ balance: amountWithoutFee, type: fromTokenAddress }), + destinationChainId: toChainId, + nonce: getNonceBigInt(), + recipient: fromHex(tx, normalizeSuiHex(toAccountAddress)), + receiveToken: fromHex(tx, normalizeSuiHex(toTokenAddress)), + gasOracle: suiAddresses.gasOracleObjectAddress, + feeTokenCoin: coinWithBalance({ balance: BigInt(totalFee), type: fromTokenAddress }), + feeSuiCoin: coinWithBalance({ balance: BigInt(0), useGasCoin: false }), + }; + swapAndBridge(tx, fromTokenAddress, args); + } else { + const totalFeeCoin = + totalFee === "0" + ? coinWithBalance({ balance: BigInt(totalFee), useGasCoin: false }) + : coinWithBalance({ balance: BigInt(totalFee) }); + const args = { + bridge: suiAddresses.bridgeObjectAddress, + messenger: suiAddresses.allbridgeMessengerObjectAddress, + amount: coinWithBalance({ balance: BigInt(amount), type: fromTokenAddress }), + destinationChainId: toChainId, + nonce: getNonceBigInt(), + recipient: fromHex(tx, normalizeSuiHex(toAccountAddress)), + receiveToken: fromHex(tx, normalizeSuiHex(toTokenAddress)), + gasOracle: suiAddresses.gasOracleObjectAddress, + feeTokenCoin: coinWithBalance({ balance: BigInt(0), type: fromTokenAddress }), + feeSuiCoin: totalFeeCoin, + }; + swapAndBridge(tx, fromTokenAddress, args); + } + return await tx.toJSON({ client: this.client }); + } + + private async buildRawTransactionWormholeSend( + txSendParams: TxSendParamsSui, + suiAddresses: SuiAddresses + ): Promise { + const { + amount, + fromAccountAddress, + fromTokenAddress, + toChainId, + toAccountAddress, + toTokenAddress, + fee, + gasFeePaymentMethod, + extraGas, + } = txSendParams; + let totalFee = fee; + if (extraGas) { + totalFee = Big(totalFee).plus(extraGas).toFixed(); + } + + const tx = new Transaction(); + tx.setSender(fromAccountAddress); + if (gasFeePaymentMethod === FeePaymentMethod.WITH_STABLECOIN) { + const amountWithoutFee = BigInt(amount) - BigInt(totalFee); + const args = { + bridge: suiAddresses.bridgeObjectAddress, + messenger: suiAddresses.wormholeMessengerObjectAddress, + wormholeState: suiAddresses.wormholeStateObjectAddress, + theClock: SUI_CLOCK_OBJECT_ID, + amount: coinWithBalance({ balance: amountWithoutFee, type: fromTokenAddress }), + destinationChainId: toChainId, + nonce: getNonceBigInt(), + recipient: fromHex(tx, normalizeSuiHex(toAccountAddress)), + receiveToken: fromHex(tx, normalizeSuiHex(toTokenAddress)), + gasOracle: suiAddresses.gasOracleObjectAddress, + feeTokenCoin: coinWithBalance({ balance: BigInt(totalFee), type: fromTokenAddress }), + feeSuiCoin: coinWithBalance({ balance: BigInt(0), useGasCoin: false }), + }; + swapAndBridgeWormhole(tx, fromTokenAddress, args); + } else { + const totalFeeCoin = + totalFee === "0" + ? coinWithBalance({ balance: BigInt(totalFee), useGasCoin: false }) + : coinWithBalance({ balance: BigInt(totalFee) }); + const args = { + bridge: suiAddresses.bridgeObjectAddress, + messenger: suiAddresses.wormholeMessengerObjectAddress, + wormholeState: suiAddresses.wormholeStateObjectAddress, + theClock: SUI_CLOCK_OBJECT_ID, + amount: coinWithBalance({ balance: BigInt(amount), type: fromTokenAddress }), + destinationChainId: toChainId, + nonce: getNonceBigInt(), + recipient: fromHex(tx, normalizeSuiHex(toAccountAddress)), + receiveToken: fromHex(tx, normalizeSuiHex(toTokenAddress)), + gasOracle: suiAddresses.gasOracleObjectAddress, + feeTokenCoin: coinWithBalance({ balance: BigInt(0), type: fromTokenAddress }), + feeSuiCoin: totalFeeCoin, + }; + swapAndBridgeWormhole(tx, fromTokenAddress, args); + } + return await tx.toJSON({ client: this.client }); + } + + private async buildRawTransactionCctpSend( + params: SendParams, + txSendParams: TxSendParamsSui, + suiAddresses: SuiAddresses + ): Promise { + const { + amount, + fromAccountAddress, + fromTokenAddress, + toChainId, + toAccountAddress, + fee, + gasFeePaymentMethod, + extraGas, + } = txSendParams; + + setCctpAddress(suiAddresses.cctpAddress, suiAddresses.cctpAddressOrigin); + + let totalFee = fee; + if (extraGas) { + totalFee = Big(totalFee).plus(extraGas).toFixed(); + } + + const tx = new Transaction(); + tx.setSender(fromAccountAddress); + + const recipientWalletAddress = fromHex(tx, normalizeSuiHex(toAccountAddress)); + let recipient: TransactionResult; + if (params.destinationToken.chainType === ChainType.SOLANA) { + const recipientStr = await getCctpSolTokenRecipientAddress( + this.chainType, + params.toAccountAddress, + params.destinationToken.tokenAddress, + this.nodeRpcUrlsConfig.getNodeRpcUrl(ChainSymbol.SOL) + ); + recipient = fromHex(tx, normalizeSuiHex(recipientStr)); + } else { + recipient = recipientWalletAddress; + } + + if (gasFeePaymentMethod === FeePaymentMethod.WITH_STABLECOIN) { + const amountWithoutFee = BigInt(amount) - BigInt(totalFee); + const args = { + cctpBridge: suiAddresses.cctpObjectAddress, + tokenMessengerMinterState: suiAddresses.cctpTokenMessengerMinterStateObjectAddress, + messageTransmitterState: suiAddresses.cctpMessageTransmitterStateObjectAddress, + treasury: suiAddresses.cctpTreasuryObjectAddress, + denyList: suiAddresses.cctpDenyListObjectAddress, + amount: coinWithBalance({ balance: amountWithoutFee, type: fromTokenAddress }), + destinationChainId: toChainId, + recipient: recipient, + recipientWalletAddress: recipientWalletAddress, + gasOracle: suiAddresses.gasOracleObjectAddress, + feeTokenCoin: coinWithBalance({ balance: BigInt(totalFee), type: fromTokenAddress }), + feeSuiCoin: coinWithBalance({ balance: BigInt(0), useGasCoin: false }), + }; + bridge(tx, fromTokenAddress, args); + } else { + const totalFeeCoin = + totalFee === "0" + ? coinWithBalance({ balance: BigInt(totalFee), useGasCoin: false }) + : coinWithBalance({ balance: BigInt(totalFee) }); + const args = { + cctpBridge: suiAddresses.cctpObjectAddress, + tokenMessengerMinterState: suiAddresses.cctpTokenMessengerMinterStateObjectAddress, + messageTransmitterState: suiAddresses.cctpMessageTransmitterStateObjectAddress, + treasury: suiAddresses.cctpTreasuryObjectAddress, + denyList: suiAddresses.cctpDenyListObjectAddress, + amount: coinWithBalance({ balance: BigInt(amount), type: fromTokenAddress }), + destinationChainId: toChainId, + recipient: recipient, + recipientWalletAddress: recipientWalletAddress, + gasOracle: suiAddresses.gasOracleObjectAddress, + feeTokenCoin: coinWithBalance({ balance: BigInt(0), type: fromTokenAddress }), + feeSuiCoin: totalFeeCoin, + }; + bridge(tx, fromTokenAddress, args); + } + return await tx.toJSON({ client: this.client }); + } +} diff --git a/src/services/bridge/trx/index.ts b/src/services/bridge/trx/index.ts index 03327bf5..771517c8 100644 --- a/src/services/bridge/trx/index.ts +++ b/src/services/bridge/trx/index.ts @@ -15,7 +15,7 @@ export class TronBridgeService extends ChainBridgeService { constructor( public tronWeb: TronWeb, - public api: AllbridgeCoreClient, + public api: AllbridgeCoreClient ) { super(); } @@ -137,7 +137,7 @@ export class TronBridgeService extends ChainBridgeService { methodSignature: string, parameters: SmartContractMethodParameter[], value: string, - fromAddress: string, + fromAddress: string ): Promise { const transactionObject = await this.tronWeb.transactionBuilder.triggerSmartContract( contractAddress, @@ -146,7 +146,7 @@ export class TronBridgeService extends ChainBridgeService { callValue: +value, }, parameters, - fromAddress, + fromAddress ); if (!transactionObject?.result?.result) { throw new SdkError("Unknown error: " + JSON.stringify(transactionObject, null, 2)); diff --git a/src/services/bridge/utils.ts b/src/services/bridge/utils.ts index 973ef31a..3c2db5d8 100644 --- a/src/services/bridge/utils.ts +++ b/src/services/bridge/utils.ts @@ -30,16 +30,18 @@ import { TxSendParamsEvm, TxSendParamsSol, TxSendParamsSrb, + TxSendParamsSui, TxSendParamsTrx, TxSwapParams, TxSwapParamsEvm, TxSwapParamsSol, TxSwapParamsSrb, + TxSwapParamsSui, TxSwapParamsTrx, } from "./models"; // 1. OVERLOADS -export function formatAddress(address: string, from: ChainType, to: ChainType.EVM): string; +export function formatAddress(address: string, from: ChainType, to: ChainType.EVM | ChainType.SUI): string; export function formatAddress(address: string, from: ChainType, to: ChainType.TRX): Buffer; export function formatAddress(address: string, from: ChainType, to: ChainType.SOLANA | ChainType.SRB): number[]; export function formatAddress(address: string, from: ChainType, to: ChainType): string | number[] | Buffer; @@ -64,6 +66,10 @@ export function formatAddress(address: string, from: ChainType, to: ChainType): buffer = new Address(address).toBuffer(); break; } + case ChainType.SUI: { + buffer = evmAddressToBuffer32(address); + break; + } } switch (to) { @@ -79,9 +85,16 @@ export function formatAddress(address: string, from: ChainType, to: ChainType): case ChainType.SRB: { return buffer.toJSON().data; } + case ChainType.SUI: { + return "0x" + buffer.toString("hex"); + } } } +export function normalizeSuiHex(hex: string): string { + return hex.replace(/^0x/i, ""); +} + export function hexToBuffer(hex: string): Buffer { return Buffer.from(hex.replace(/^0x/i, ""), "hex"); } @@ -116,7 +129,7 @@ function bufferToSize(buffer: Buffer, size: number): Buffer { export function getTokenByTokenAddress( chainDetailsMap: ChainDetailsMap, chainSymbol: string, - tokenAddress: string, + tokenAddress: string ): TokenWithChainDetails { const chainDetail = chainDetailsMap[chainSymbol]; if (!chainDetail) { @@ -142,11 +155,14 @@ export function getNonceBigInt(): bigint { } // 1. OVERLOADS -export function prepareTxSwapParams(bridgeChainType: ChainType.EVM, params: SwapParams): TxSwapParamsEvm; +export function prepareTxSwapParams( + bridgeChainType: ChainType.EVM | ChainType.SUI, + params: SwapParams +): TxSwapParamsEvm | TxSwapParamsSui; export function prepareTxSwapParams(bridgeChainType: ChainType.TRX, params: SwapParams): TxSwapParamsTrx; export function prepareTxSwapParams( bridgeChainType: ChainType.SOLANA | ChainType.SRB, - params: SwapParams, + params: SwapParams ): TxSwapParamsSol | TxSwapParamsSrb; export function prepareTxSwapParams(bridgeChainType: ChainType, params: SwapParams): TxSwapParams; @@ -157,9 +173,23 @@ export function prepareTxSwapParams(bridgeChainType: ChainType, params: SwapPara txSwapParams.amount = convertFloatAmountToInt(params.amount, sourceToken.decimals).toFixed(); txSwapParams.contractAddress = sourceToken.bridgeAddress; txSwapParams.fromAccountAddress = params.fromAccountAddress; - txSwapParams.fromTokenAddress = formatAddress(sourceToken.tokenAddress, bridgeChainType, bridgeChainType); + if (bridgeChainType === ChainType.SUI) { + if (!sourceToken.originTokenAddress) { + throw new SdkError("SUI sourceToken must contain 'originTokenAddress'"); + } + txSwapParams.fromTokenAddress = sourceToken.originTokenAddress; + } else { + txSwapParams.fromTokenAddress = formatAddress(sourceToken.tokenAddress, bridgeChainType, bridgeChainType); + } txSwapParams.toAccountAddress = params.toAccountAddress; - txSwapParams.toTokenAddress = formatAddress(params.destinationToken.tokenAddress, bridgeChainType, bridgeChainType); + if (bridgeChainType === ChainType.SUI) { + if (!params.destinationToken.originTokenAddress) { + throw new SdkError("SUI destinationToken must contain 'originTokenAddress'"); + } + txSwapParams.toTokenAddress = params.destinationToken.originTokenAddress; + } else { + txSwapParams.toTokenAddress = formatAddress(params.destinationToken.tokenAddress, bridgeChainType, bridgeChainType); + } txSwapParams.minimumReceiveAmount = params.minimumReceiveAmount ? convertFloatAmountToInt(params.minimumReceiveAmount, params.destinationToken.decimals).toFixed() : "0"; @@ -168,38 +198,45 @@ export function prepareTxSwapParams(bridgeChainType: ChainType, params: SwapPara // 1. OVERLOADS export function prepareTxSendParams( - bridgeChainType: ChainType.EVM, + bridgeChainType: ChainType.EVM | ChainType.SUI, params: SendParams, - api: AllbridgeCoreClient, -): Promise; + api: AllbridgeCoreClient +): Promise; export function prepareTxSendParams( bridgeChainType: ChainType.TRX, params: SendParams, - api: AllbridgeCoreClient, + api: AllbridgeCoreClient ): Promise; export function prepareTxSendParams( bridgeChainType: ChainType.SOLANA | ChainType.SRB, params: SendParams, - api: AllbridgeCoreClient, + api: AllbridgeCoreClient ): Promise; export function prepareTxSendParams( bridgeChainType: ChainType, params: SendParams, - api: AllbridgeCoreClient, + api: AllbridgeCoreClient ): Promise; // 2. COMMON Realization export async function prepareTxSendParams( bridgeChainType: ChainType, params: SendParams, - api: AllbridgeCoreClient, + api: AllbridgeCoreClient ): Promise { const txSendParams = {} as TxSendParams; txSendParams.fromChainId = params.sourceToken.allbridgeChainId; txSendParams.fromChainSymbol = params.sourceToken.chainSymbol; const toChainType = Chains.getChainProperty(params.destinationToken.chainSymbol).chainType; - txSendParams.fromTokenAddress = params.sourceToken.tokenAddress; + if (bridgeChainType === ChainType.SUI) { + if (!params.sourceToken.originTokenAddress) { + throw new SdkError("SUI token must contain 'originTokenAddress'"); + } + txSendParams.fromTokenAddress = params.sourceToken.originTokenAddress; + } else { + txSendParams.fromTokenAddress = params.sourceToken.tokenAddress; + } txSendParams.toChainId = params.destinationToken.allbridgeChainId; txSendParams.toTokenAddress = params.destinationToken.tokenAddress; @@ -232,7 +269,7 @@ export async function prepareTxSendParams( txSendParams.toChainId, sourceToken.decimals, txSendParams.messenger, - api, + api ); const gasFeeOption = gasFeeOptions[txSendParams.gasFeePaymentMethod]; @@ -246,7 +283,7 @@ export async function prepareTxSendParams( switch (txSendParams.gasFeePaymentMethod) { case FeePaymentMethod.WITH_NATIVE_CURRENCY: txSendParams.fee = convertFloatAmountToInt(fee, Chains.getChainDecimalsByType(sourceToken.chainType)).toFixed( - 0, + 0 ); break; case FeePaymentMethod.WITH_STABLECOIN: @@ -265,7 +302,7 @@ export async function prepareTxSendParams( case FeePaymentMethod.WITH_NATIVE_CURRENCY: txSendParams.extraGas = convertFloatAmountToInt( extraGas, - Chains.getChainDecimalsByType(sourceToken.chainType), + Chains.getChainDecimalsByType(sourceToken.chainType) ).toFixed(0); break; case FeePaymentMethod.WITH_STABLECOIN: @@ -280,11 +317,13 @@ export async function prepareTxSendParams( txSendParams.gasFeePaymentMethod, sourceToken, params.destinationToken, - api, + api ); } - txSendParams.fromTokenAddress = formatAddress(txSendParams.fromTokenAddress, bridgeChainType, bridgeChainType); + if (bridgeChainType !== ChainType.SUI) { + txSendParams.fromTokenAddress = formatAddress(txSendParams.fromTokenAddress, bridgeChainType, bridgeChainType); + } txSendParams.toAccountAddress = formatAddress(params.toAccountAddress, toChainType, bridgeChainType); txSendParams.toTokenAddress = formatAddress(txSendParams.toTokenAddress, toChainType, bridgeChainType); if (txSendParams.gasFeePaymentMethod == FeePaymentMethod.WITH_STABLECOIN) { @@ -297,7 +336,7 @@ function validateAmountEnough( amountInt: BigSource, decimals: number, feeInt: BigSource, - extraGasInt: BigSource | undefined, + extraGasInt: BigSource | undefined ) { const amountTotal = Big(amountInt) .minus(feeInt) @@ -306,8 +345,8 @@ function validateAmountEnough( throw new AmountNotEnoughError( `Amount not enough to pay fee, ${convertIntAmountToFloat( Big(amountTotal).minus(1).neg(), - decimals, - ).toFixed()} stables is missing`, + decimals + ).toFixed()} stables is missing` ); } } @@ -318,7 +357,7 @@ export async function getGasFeeOptions( destinationAllbridgeChainId: number, sourceChainTokenDecimals: number, messenger: Messenger, - api: AllbridgeCoreClient, + api: AllbridgeCoreClient ): Promise { const transactionCostResponse = await api.getReceiveTransactionCost({ sourceChainId: sourceAllbridgeChainId, @@ -331,7 +370,7 @@ export async function getGasFeeOptions( [AmountFormat.INT]: transactionCostResponse.fee, [AmountFormat.FLOAT]: convertIntAmountToFloat( transactionCostResponse.fee, - Chains.getChainDecimalsByType(sourceChainType), + Chains.getChainDecimalsByType(sourceChainType) ).toFixed(), }, }; @@ -339,7 +378,7 @@ export async function getGasFeeOptions( const gasFeeIntWithStables = convertAmountPrecision( new Big(transactionCostResponse.fee).mul(transactionCostResponse.sourceNativeTokenPrice), Chains.getChainDecimalsByType(sourceChainType), - sourceChainTokenDecimals, + sourceChainTokenDecimals ).toFixed(0, Big.roundUp); gasFeeOptions[FeePaymentMethod.WITH_STABLECOIN] = { [AmountFormat.INT]: gasFeeIntWithStables, @@ -355,7 +394,7 @@ async function validateExtraGasNotExceeded( gasFeePaymentMethod: FeePaymentMethod, sourceToken: TokenWithChainDetails, destinationToken: TokenWithChainDetails, - api: AllbridgeCoreClient, + api: AllbridgeCoreClient ) { const extraGasLimits = await getExtraGasMaxLimits(sourceToken, destinationToken, api); const extraGasMaxLimit = extraGasLimits.extraGasMax[gasFeePaymentMethod]; @@ -365,7 +404,7 @@ async function validateExtraGasNotExceeded( const extraGasMaxIntLimit = extraGasMaxLimit[AmountFormat.INT]; if (Big(extraGasInt).gt(extraGasMaxIntLimit)) { throw new ExtraGasMaxLimitExceededError( - `Extra gas ${extraGasInt} in int format, exceeded limit ${extraGasMaxIntLimit} for '${gasFeePaymentMethod}' payment method`, + `Extra gas ${extraGasInt} in int format, exceeded limit ${extraGasMaxIntLimit} for '${gasFeePaymentMethod}' payment method` ); } } @@ -373,7 +412,7 @@ async function validateExtraGasNotExceeded( export async function getExtraGasMaxLimits( sourceChainToken: TokenWithChainDetails, destinationChainToken: TokenWithChainDetails, - api: AllbridgeCoreClient, + api: AllbridgeCoreClient ): Promise { const extraGasMaxLimits: ExtraGasMaxLimits = {}; const transactionCostResponse = await api.getReceiveTransactionCost({ @@ -384,14 +423,14 @@ export async function getExtraGasMaxLimits( const maxAmount = destinationChainToken.txCostAmount.maxAmount; const maxAmountFloat = convertIntAmountToFloat( maxAmount, - Chains.getChainDecimalsByType(destinationChainToken.chainType), + Chains.getChainDecimalsByType(destinationChainToken.chainType) ).toFixed(); const maxAmountFloatInSourceNative = Big(maxAmountFloat) .div(transactionCostResponse.exchangeRate) .toFixed(Chains.getChainDecimalsByType(sourceChainToken.chainType), Big.roundDown); const maxAmountInSourceNative = convertFloatAmountToInt( maxAmountFloatInSourceNative, - Chains.getChainDecimalsByType(sourceChainToken.chainType), + Chains.getChainDecimalsByType(sourceChainToken.chainType) ).toFixed(0); extraGasMaxLimits[FeePaymentMethod.WITH_NATIVE_CURRENCY] = { [AmountFormat.INT]: maxAmountInSourceNative, @@ -417,14 +456,14 @@ export async function getExtraGasMaxLimits( [AmountFormat.INT]: destinationChainToken.txCostAmount.swap, [AmountFormat.FLOAT]: convertIntAmountToFloat( destinationChainToken.txCostAmount.swap, - Chains.getChainDecimalsByType(destinationChainToken.chainType), + Chains.getChainDecimalsByType(destinationChainToken.chainType) ).toFixed(), }, transfer: { [AmountFormat.INT]: destinationChainToken.txCostAmount.transfer, [AmountFormat.FLOAT]: convertIntAmountToFloat( destinationChainToken.txCostAmount.transfer, - Chains.getChainDecimalsByType(destinationChainToken.chainType), + Chains.getChainDecimalsByType(destinationChainToken.chainType) ).toFixed(), }, }, diff --git a/src/services/index.ts b/src/services/index.ts index 00326e47..482afe96 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -131,7 +131,7 @@ export class AllbridgeCoreSdkService { amount: string, amountFormat: AmountFormat, sourceToken: TokenWithChainDetails, - destToken: TokenWithChainDetails, + destToken: TokenWithChainDetails ): Promise { validateAmountGtZero(amount); let amountInTokenPrecision; @@ -145,13 +145,13 @@ export class AllbridgeCoreSdkService { const vUsdAmountInt = swapToVUsd( amountInTokenPrecision, sourceToken, - await getPoolInfoByToken(this.api, sourceToken), + await getPoolInfoByToken(this.api, sourceToken) ); const destPoolInfo = await getPoolInfoByToken(this.api, destToken); const amountResultIntFormatted: AmountFormatted = this.getAmountFromVUsdFormatted( vUsdAmountInt, destToken, - destPoolInfo, + destPoolInfo ); let pendingInfoDTO: PendingInfoDTO | undefined; @@ -168,7 +168,7 @@ export class AllbridgeCoreSdkService { const amountResultIntAfterPendingFormatted: AmountFormatted = this.getAmountFromVUsdFormatted( vUsdAmountInt, destToken, - destPoolAfterPending, + destPoolAfterPending ); let estimatedAmount: { min: AmountFormatted; max: AmountFormatted }; @@ -184,7 +184,7 @@ export class AllbridgeCoreSdkService { [AmountFormat.INT]: convertAmountPrecision( pendingInfoDTO.totalSentAmount, SYSTEM_PRECISION, - destToken.decimals, + destToken.decimals ).toFixed(0), [AmountFormat.FLOAT]: convertIntAmountToFloat(pendingInfoDTO.totalSentAmount, SYSTEM_PRECISION).toFixed(), }, @@ -214,7 +214,7 @@ export class AllbridgeCoreSdkService { async calculateFeePercentOnSourceChain( amountFloat: number | string | Big, - sourceChainToken: TokenWithChainDetails, + sourceChainToken: TokenWithChainDetails ): Promise { validateAmountGtZero(amountFloat); validateAmountDecimals("amountFloat", amountFloat, sourceChainToken.decimals); @@ -225,7 +225,7 @@ export class AllbridgeCoreSdkService { const vUsdInSystemPrecision = swapToVUsd( amountInt, sourceChainToken, - await getPoolInfoByToken(this.api, sourceChainToken), + await getPoolInfoByToken(this.api, sourceChainToken) ); const vUsdInSourcePrecision = fromSystemPrecision(vUsdInSystemPrecision, sourceChainToken.decimals); return getFeePercent(amountInt, vUsdInSourcePrecision); @@ -234,7 +234,7 @@ export class AllbridgeCoreSdkService { async calculateFeePercentOnDestinationChain( amountFloat: number | string | Big, sourceChainToken: TokenWithChainDetails, - destinationChainToken: TokenWithChainDetails, + destinationChainToken: TokenWithChainDetails ): Promise { validateAmountGtZero(amountFloat); validateAmountDecimals("amountFloat", amountFloat, sourceChainToken.decimals); @@ -245,12 +245,12 @@ export class AllbridgeCoreSdkService { const vUsdInSystemPrecision = swapToVUsd( amountInt, sourceChainToken, - await getPoolInfoByToken(this.api, sourceChainToken), + await getPoolInfoByToken(this.api, sourceChainToken) ); const usd = swapFromVUsd( vUsdInSystemPrecision, destinationChainToken, - await getPoolInfoByToken(this.api, destinationChainToken), + await getPoolInfoByToken(this.api, destinationChainToken) ); const vUsdInDestinationPrecision = fromSystemPrecision(vUsdInSystemPrecision, destinationChainToken.decimals); return getFeePercent(vUsdInDestinationPrecision, usd); @@ -260,7 +260,7 @@ export class AllbridgeCoreSdkService { amountToSendFloat: number | string | Big, sourceChainToken: TokenWithChainDetails, destinationChainToken: TokenWithChainDetails, - messenger: Messenger, + messenger: Messenger ): Promise { validateAmountGtZero(amountToSendFloat); validateAmountDecimals("amountToSendFloat", amountToSendFloat, sourceChainToken.decimals); @@ -270,7 +270,7 @@ export class AllbridgeCoreSdkService { amountToSendFloat, sourceChainToken, destinationChainToken, - messenger, + messenger ), gasFeeOptions: await this.getGasFeeOptions(sourceChainToken, destinationChainToken, messenger), }; @@ -280,7 +280,7 @@ export class AllbridgeCoreSdkService { amountToBeReceivedFloat: number | string | Big, sourceChainToken: TokenWithChainDetails, destinationChainToken: TokenWithChainDetails, - messenger: Messenger, + messenger: Messenger ): Promise { validateAmountGtZero(amountToBeReceivedFloat); validateAmountDecimals("amountToBeReceivedFloat", amountToBeReceivedFloat, destinationChainToken.decimals); @@ -289,7 +289,7 @@ export class AllbridgeCoreSdkService { amountToBeReceivedFloat, sourceChainToken, destinationChainToken, - messenger, + messenger ), amountToBeReceivedFloat: Big(amountToBeReceivedFloat).toFixed(), gasFeeOptions: await this.getGasFeeOptions(sourceChainToken, destinationChainToken, messenger), @@ -300,7 +300,7 @@ export class AllbridgeCoreSdkService { amountToSendFloat: number | string | Big, sourceChainToken: TokenWithChainDetails, destinationChainToken: TokenWithChainDetails, - messenger?: Messenger, + messenger?: Messenger ): Promise { const sourcePool: PoolInfo = await getPoolInfoByToken(this.api, sourceChainToken); const destPool: PoolInfo = await getPoolInfoByToken(this.api, destinationChainToken); @@ -310,7 +310,7 @@ export class AllbridgeCoreSdkService { destinationChainToken, sourcePool, destPool, - messenger, + messenger ); } @@ -320,7 +320,7 @@ export class AllbridgeCoreSdkService { destinationChainToken: TokenWithChainDetails, messenger?: Messenger, sourceProvider?: Provider, - destinationProvider?: Provider, + destinationProvider?: Provider ): Promise { const sourcePool: PoolInfo = await this.pool.getPoolInfoFromChain(sourceChainToken, sourceProvider); const destPool: PoolInfo = await this.pool.getPoolInfoFromChain(destinationChainToken, destinationProvider); @@ -330,7 +330,7 @@ export class AllbridgeCoreSdkService { destinationChainToken, sourcePool, destPool, - messenger, + messenger ); } @@ -340,7 +340,7 @@ export class AllbridgeCoreSdkService { destinationChainToken: TokenWithChainDetails, sourcePool: PoolInfo, destinationPool: PoolInfo, - messenger?: Messenger, + messenger?: Messenger ): string { validateAmountGtZero(amountToSendFloat); validateAmountDecimals("amountToSendFloat", amountToSendFloat, sourceChainToken.decimals); @@ -354,7 +354,7 @@ export class AllbridgeCoreSdkService { const resultInDestPrecision = convertAmountPrecision( result, sourceChainToken.decimals, - destinationChainToken.decimals, + destinationChainToken.decimals ).round(0); return convertIntAmountToFloat(resultInDestPrecision, destinationChainToken.decimals).toFixed(); } @@ -367,7 +367,7 @@ export class AllbridgeCoreSdkService { amountToBeReceivedFloat: number | string | Big, sourceChainToken: TokenWithChainDetails, destinationChainToken: TokenWithChainDetails, - messenger?: Messenger, + messenger?: Messenger ): Promise { const sourcePool: PoolInfo = await getPoolInfoByToken(this.api, sourceChainToken); const destPool: PoolInfo = await getPoolInfoByToken(this.api, destinationChainToken); @@ -377,7 +377,7 @@ export class AllbridgeCoreSdkService { destinationChainToken, sourcePool, destPool, - messenger, + messenger ); } @@ -387,7 +387,7 @@ export class AllbridgeCoreSdkService { destinationChainToken: TokenWithChainDetails, messenger?: Messenger, sourceProvider?: Provider, - destinationProvider?: Provider, + destinationProvider?: Provider ): Promise { const sourcePool: PoolInfo = await this.pool.getPoolInfoFromChain(sourceChainToken, sourceProvider); const destPool: PoolInfo = await this.pool.getPoolInfoFromChain(destinationChainToken, destinationProvider); @@ -397,7 +397,7 @@ export class AllbridgeCoreSdkService { destinationChainToken, sourcePool, destPool, - messenger, + messenger ); } @@ -407,7 +407,7 @@ export class AllbridgeCoreSdkService { destinationChainToken: TokenWithChainDetails, sourcePool: PoolInfo, destinationPool: PoolInfo, - messenger?: Messenger, + messenger?: Messenger ): string { validateAmountGtZero(amountToBeReceivedFloat); validateAmountDecimals("amountToBeReceivedFloat", amountToBeReceivedFloat, destinationChainToken.decimals); @@ -421,7 +421,7 @@ export class AllbridgeCoreSdkService { const resultInSourcePrecision = convertAmountPrecision( result, destinationChainToken.decimals, - sourceChainToken.decimals, + sourceChainToken.decimals ).round(0); return convertIntAmountToFloat(resultInSourcePrecision, sourceChainToken.decimals).toFixed(); } @@ -437,7 +437,7 @@ export class AllbridgeCoreSdkService { async getGasFeeOptions( sourceChainToken: TokenWithChainDetails, destinationChainToken: TokenWithChainDetails, - messenger: Messenger, + messenger: Messenger ): Promise { return getGasFeeOptions( sourceChainToken.allbridgeChainId, @@ -445,14 +445,14 @@ export class AllbridgeCoreSdkService { destinationChainToken.allbridgeChainId, sourceChainToken.decimals, messenger, - this.api, + this.api ); } getAverageTransferTime( sourceChainToken: TokenWithChainDetails, destinationChainToken: TokenWithChainDetails, - messenger: Messenger, + messenger: Messenger ): number | null { return sourceChainToken.transferTime?.[destinationChainToken.chainSymbol]?.[messenger] ?? null; } @@ -478,7 +478,7 @@ export class AllbridgeCoreSdkService { async getExtraGasMaxLimits( sourceChainToken: TokenWithChainDetails, - destinationChainToken: TokenWithChainDetails, + destinationChainToken: TokenWithChainDetails ): Promise { return await getExtraGasMaxLimits(sourceChainToken, destinationChainToken, this.api); } @@ -486,7 +486,7 @@ export class AllbridgeCoreSdkService { async getVUsdFromAmount( amount: string, amountFormat: AmountFormat, - sourceToken: TokenWithChainDetails, + sourceToken: TokenWithChainDetails ): Promise { validateAmountGtZero(amount); let amountInTokenPrecision; @@ -511,7 +511,7 @@ export class AllbridgeCoreSdkService { private getAmountFromVUsdFormatted( vUsdAmountInt: string, destToken: TokenWithChainDetails, - destPoolInfo: Pick, + destPoolInfo: Pick ): AmountFormatted { validateAmountGtZero(vUsdAmountInt); const amountResultInt = swapFromVUsd(vUsdAmountInt, destToken, destPoolInfo); @@ -527,7 +527,7 @@ export class AllbridgeCoreSdkService { async swapAndBridgeFeeCalculation( amountInTokenPrecision: string, sourceToken: TokenWithChainDetails, - destToken: TokenWithChainDetails, + destToken: TokenWithChainDetails ): Promise { return swapAndBridgeFeeCalculation( amountInTokenPrecision, @@ -540,14 +540,14 @@ export class AllbridgeCoreSdkService { decimals: destToken.decimals, feeShare: destToken.feeShare, poolInfo: await getPoolInfoByToken(this.api, destToken), - }, + } ); } async swapAndBridgeFeeCalculationReverse( amountInTokenPrecision: string, sourceToken: TokenWithChainDetails, - destToken: TokenWithChainDetails, + destToken: TokenWithChainDetails ): Promise { const result = swapAndBridgeFeeCalculationReverse( amountInTokenPrecision, @@ -560,7 +560,7 @@ export class AllbridgeCoreSdkService { decimals: destToken.decimals, feeShare: destToken.feeShare, poolInfo: await getPoolInfoByToken(this.api, destToken), - }, + } ); const newAmount = result.swapFromVUsdCalcResult.amountIncludingCommissionInTokenPrecision; if (Big(newAmount).lt(0)) { @@ -573,7 +573,7 @@ export class AllbridgeCoreSdkService { amount: string, amountFormat: AmountFormat, sourceToken: TokenWithChainDetails, - destToken: TokenWithChainDetails, + destToken: TokenWithChainDetails ): Promise { validateAmountGtZero(amount); let amountInTokenPrecision; @@ -589,7 +589,7 @@ export class AllbridgeCoreSdkService { sourceToken, await getPoolInfoByToken(this.api, sourceToken), destToken, - await getPoolInfoByToken(this.api, destToken), + await getPoolInfoByToken(this.api, destToken) ); } } diff --git a/src/services/liquidity-pool/evm/index.ts b/src/services/liquidity-pool/evm/index.ts index 7e319bfe..075ba3a8 100644 --- a/src/services/liquidity-pool/evm/index.ts +++ b/src/services/liquidity-pool/evm/index.ts @@ -20,7 +20,7 @@ export class EvmPoolService extends ChainPoolService { constructor( public web3: EssentialWeb3, - public api: AllbridgeCoreClient, + public api: AllbridgeCoreClient ) { super(); } @@ -31,14 +31,14 @@ export class EvmPoolService extends ChainPoolService { userBalanceInfo = await promiseWithTimeout( this.getUserBalanceInfoByBatch(accountAddress, token), `Cannot get UserBalanceInfo for ${token.name} on ${token.chainSymbol}`, - 5000, + 5000 ); } catch (ignoreError) { userBalanceInfo = await promiseWithTimeoutAndRetries( () => this.getUserBalanceInfoPerProperty(accountAddress, token), `Cannot get UserBalanceInfo for ${token.name} on ${token.chainSymbol}`, 5, - 2000, + 2000 ); } return userBalanceInfo; @@ -50,14 +50,14 @@ export class EvmPoolService extends ChainPoolService { poolInfo = await promiseWithTimeout( this.getPoolInfoByBatch(token), `Cannot get PoolInfo for ${token.name} on ${token.chainSymbol}`, - 5000, + 5000 ); } catch (ignoreError) { poolInfo = await promiseWithTimeoutAndRetries( () => this.getPoolInfoPerProperty(token), `Cannot get PoolInfo for ${token.name} on ${token.chainSymbol}`, 5, - 2000, + 2000 ); } return poolInfo; @@ -65,7 +65,7 @@ export class EvmPoolService extends ChainPoolService { private async getUserBalanceInfoByBatch( accountAddress: string, - token: TokenWithChainDetails, + token: TokenWithChainDetails ): Promise { const batch = new this.web3.eth.BatchRequest(); const poolContract = this.getPoolContract(token.poolAddress); @@ -95,7 +95,7 @@ export class EvmPoolService extends ChainPoolService { private async getUserBalanceInfoPerProperty( accountAddress: string, - token: TokenWithChainDetails, + token: TokenWithChainDetails ): Promise { const rewardDebt = ( await this.getPoolContract(token.poolAddress).methods.userRewardDebt(accountAddress).call() diff --git a/src/services/liquidity-pool/index.ts b/src/services/liquidity-pool/index.ts index 353f3a85..70ee99f9 100644 --- a/src/services/liquidity-pool/index.ts +++ b/src/services/liquidity-pool/index.ts @@ -19,6 +19,7 @@ import { ApproveParams, ChainPoolService, CheckAllowanceParams, GetAllowancePara import { DefaultRawPoolTransactionBuilder, RawPoolTransactionBuilder } from "./raw-pool-transaction-builder"; import { SolanaPoolService } from "./sol"; import { SrbPoolService } from "./srb"; +import { SuiPoolService } from "./sui"; import { TronPoolService } from "./trx"; export interface LiquidityPoolService { @@ -86,7 +87,7 @@ export interface LiquidityPoolService { amount: string, accountAddress: string, token: TokenWithChainDetails, - provider?: Provider, + provider?: Provider ): Promise; /** @@ -99,7 +100,7 @@ export interface LiquidityPoolService { getUserBalanceInfo( accountAddress: string, token: TokenWithChainDetails, - provider?: Provider, + provider?: Provider ): Promise; /** @@ -119,7 +120,7 @@ export class DefaultLiquidityPoolService implements LiquidityPoolService { private api: AllbridgeCoreClientFiltered, private nodeRpcUrlsConfig: NodeRpcUrlsConfig, private params: AllbridgeCoreSdkOptions, - private tokenService: TokenService, + private tokenService: TokenService ) { this.rawTxBuilder = new DefaultRawPoolTransactionBuilder(api, nodeRpcUrlsConfig, this.params, tokenService); const ttl = params.cachePoolInfoChainSec > 0 ? params.cachePoolInfoChainSec * 1000 : 20 * 1000; @@ -165,7 +166,7 @@ export class DefaultLiquidityPoolService implements LiquidityPoolService { amount: string, accountAddress: string, token: TokenWithChainDetails, - provider?: Provider, + provider?: Provider ): Promise { validateAmountGtZero(amount); validateAmountDecimals("amount", amount, token.decimals); @@ -181,14 +182,14 @@ export class DefaultLiquidityPoolService implements LiquidityPoolService { async getUserBalanceInfo( accountAddress: string, token: TokenWithChainDetails, - provider?: Provider, + provider?: Provider ): Promise { return getChainPoolService( token.chainSymbol, this.api, this.nodeRpcUrlsConfig, this.params, - provider, + provider ).getUserBalanceInfo(accountAddress, token); } @@ -203,7 +204,7 @@ export class DefaultLiquidityPoolService implements LiquidityPoolService { this.api, this.nodeRpcUrlsConfig, this.params, - provider, + provider ).getPoolInfoFromChain(token); this.cache.put(poolKey, poolInfo); this.api.cachePut({ chainSymbol: token.chainSymbol, poolAddress: token.poolAddress }, poolInfo); @@ -217,7 +218,7 @@ export function getChainPoolService( api: AllbridgeCoreClient, nodeRpcUrlsConfig: NodeRpcUrlsConfig, params: AllbridgeCoreSdkOptions, - provider?: Provider, + provider?: Provider ): ChainPoolService { switch (Chains.getChainProperty(chainSymbol).chainType) { case ChainType.EVM: { @@ -247,5 +248,8 @@ export function getChainPoolService( case ChainType.SRB: { return new SrbPoolService(nodeRpcUrlsConfig, params, api); } + case ChainType.SUI: { + return new SuiPoolService(nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol), api); + } } } diff --git a/src/services/liquidity-pool/raw-pool-transaction-builder.ts b/src/services/liquidity-pool/raw-pool-transaction-builder.ts index 88fbf3d1..c6298211 100644 --- a/src/services/liquidity-pool/raw-pool-transaction-builder.ts +++ b/src/services/liquidity-pool/raw-pool-transaction-builder.ts @@ -49,7 +49,7 @@ export class DefaultRawPoolTransactionBuilder implements RawPoolTransactionBuild private api: AllbridgeCoreClient, private nodeRpcUrlsConfig: NodeRpcUrlsConfig, private params: AllbridgeCoreSdkOptions, - private tokenService: TokenService, + private tokenService: TokenService ) {} async approve(a: Provider | ApproveParams, b?: ApproveParams): Promise { @@ -61,7 +61,7 @@ export class DefaultRawPoolTransactionBuilder implements RawPoolTransactionBuild ...approveData, spender: approveData.token.poolAddress, }, - provider, + provider ); } else { const approveData: ApproveParams = a as ApproveParams; @@ -81,7 +81,7 @@ export class DefaultRawPoolTransactionBuilder implements RawPoolTransactionBuild this.api, this.nodeRpcUrlsConfig, this.params, - provider, + provider ).buildRawTransactionDeposit(params); } @@ -94,7 +94,7 @@ export class DefaultRawPoolTransactionBuilder implements RawPoolTransactionBuild this.api, this.nodeRpcUrlsConfig, this.params, - provider, + provider ).buildRawTransactionWithdraw(params); } @@ -104,7 +104,7 @@ export class DefaultRawPoolTransactionBuilder implements RawPoolTransactionBuild this.api, this.nodeRpcUrlsConfig, this.params, - provider, + provider ).buildRawTransactionClaimRewards(params); } } diff --git a/src/services/liquidity-pool/sol/index.ts b/src/services/liquidity-pool/sol/index.ts index 9befaacc..3bb499fe 100644 --- a/src/services/liquidity-pool/sol/index.ts +++ b/src/services/liquidity-pool/sol/index.ts @@ -40,7 +40,7 @@ export class SolanaPoolService extends ChainPoolService { constructor( public solanaRpcUrl: string, - public api: AllbridgeCoreClient, + public api: AllbridgeCoreClient ) { super(); } @@ -54,7 +54,7 @@ export class SolanaPoolService extends ChainPoolService { const userDepositAccount = await getUserDepositAccount( new PublicKey(accountAddress), poolAccountInfo.mint, - bridge.programId, + bridge.programId ); const { lpAmount, rewardDebt } = await bridge.account.userDeposit.fetch(userDepositAccount); return new UserBalance({ @@ -136,7 +136,7 @@ export class SolanaPoolService extends ChainPoolService { bridge, params.token.poolAddress, params.accountAddress, - provider, + provider ); return { bridge, accounts, preInstructions }; } @@ -157,7 +157,7 @@ export class SolanaPoolService extends ChainPoolService { { preflightCommitment: "confirmed", commitment: "confirmed", - }, + } ); } @@ -165,7 +165,7 @@ export class SolanaPoolService extends ChainPoolService { bridge: Program, poolAddress: string, account: string, - provider: Provider, + provider: Provider ): Promise { const user = new PublicKey(account); const configAccount = await getConfigAccount(bridge.programId); diff --git a/src/services/liquidity-pool/srb/index.ts b/src/services/liquidity-pool/srb/index.ts index cc727d85..5900d2e3 100644 --- a/src/services/liquidity-pool/srb/index.ts +++ b/src/services/liquidity-pool/srb/index.ts @@ -23,7 +23,7 @@ export class SrbPoolService extends ChainPoolService { constructor( readonly nodeRpcUrlsConfig: NodeRpcUrlsConfig, readonly params: AllbridgeCoreSdkOptions, - readonly api: AllbridgeCoreClient, + readonly api: AllbridgeCoreClient ) { super(); } diff --git a/src/services/liquidity-pool/sui/index.ts b/src/services/liquidity-pool/sui/index.ts new file mode 100644 index 00000000..3aa7b5df --- /dev/null +++ b/src/services/liquidity-pool/sui/index.ts @@ -0,0 +1,281 @@ +import { SuiClient } from "@mysten/sui/client"; +import { CoinStruct, SuiObjectResponse } from "@mysten/sui/src/client/types/generated"; +import { Transaction, TransactionResult } from "@mysten/sui/transactions"; +import { ChainType } from "../../../chains/chain.enums"; +import { AllbridgeCoreClient } from "../../../client/core-api/core-client-base"; +import { InvalidAmountError, SdkError } from "../../../exceptions"; +import { PoolInfo, TokenWithChainDetails } from "../../../tokens-info"; +import { calculatePoolInfoImbalance } from "../../../utils/calculation"; +import { RawSuiTransaction } from "../../models"; +import { phantom } from "../../models/sui/_framework/reified"; +import { setAddress } from "../../models/sui/bridge"; +import { + claimReward, + deposit, + newUserDeposit, + pool, + withdraw, +} from "../../models/sui/bridge/bridge-interface/functions"; +import { Pool } from "../../models/sui/bridge/pool/structs"; +import { UserDeposit } from "../../models/sui/bridge/user-deposit/structs"; +import { getCoinsWithAmounts } from "../../utils/sui/coins"; +import { fetchAllPagesRecursive } from "../../utils/sui/paginated"; +import { suiView } from "../../utils/sui/view"; +import { + ChainPoolService, + LiquidityPoolsParams, + LiquidityPoolsParamsWithAmount, + UserBalance, + UserBalanceInfo, +} from "../models"; + +export class SuiPoolService extends ChainPoolService { + chainType: ChainType.SUI = ChainType.SUI; + + private readonly client: SuiClient; + + constructor( + public suiRpcUrl: string, + public api: AllbridgeCoreClient + ) { + super(); + this.client = new SuiClient({ + url: suiRpcUrl, + }); + } + + async getUserBalanceInfo(accountAddress: string, token: TokenWithChainDetails): Promise { + if (!token.originTokenAddress) { + throw new SdkError("SUI token must contain 'originTokenAddress'"); + } + const suiAddresses = token.suiAddresses; + if (!suiAddresses) { + throw new SdkError("SUI token must contain 'suiAddresses'"); + } + setAddress(suiAddresses.bridgeAddress, suiAddresses.bridgeAddressOrigin); + + const deposits = await this.fetchDeposits(accountAddress, token.originTokenAddress); + const total = deposits.reduce( + (total, element) => { + if (element.data) { + total.lpAmount += BigInt((element.data.content as any).fields.lp_amount); + total.rewardDebt += BigInt((element.data.content as any).fields.reward_debt); + return total; + } else { + throw new SdkError("Deposits fetch failed"); + } + }, + { lpAmount: BigInt(0), rewardDebt: BigInt(0) } + ); + return new UserBalance({ lpAmount: total.lpAmount.toString(), rewardDebt: total.rewardDebt.toString() }); + } + + private async fetchDeposits(accountAddress: string, tokenAddress: string): Promise { + return await fetchAllPagesRecursive((cursor: string | null | undefined) => + this.client.getOwnedObjects({ + owner: accountAddress, + filter: { StructType: UserDeposit.phantom(phantom(tokenAddress)).phantomType }, + options: { showContent: true }, + cursor, + }) + ); + } + + async getPoolInfoFromChain(token: TokenWithChainDetails): Promise { + const suiAddresses = token.suiAddresses; + if (!suiAddresses) { + throw new SdkError("SUI token must contain 'suiAddresses'"); + } + setAddress(suiAddresses.bridgeAddress, suiAddresses.bridgeAddressOrigin); + + if (!token.originTokenAddress) { + throw new SdkError("SUI token must contain 'originTokenAddress'"); + } + + const P = 48; + const tx = new Transaction(); + pool(tx, token.originTokenAddress, suiAddresses.bridgeObjectAddress); + const res = await suiView(this.client, tx, Pool.reified(phantom(token.originTokenAddress))); + + const tokenBalance = res.state.tokenBalance; + const vUsdBalance = res.state.vusdBalance; + const imbalance = calculatePoolInfoImbalance({ tokenBalance, vUsdBalance }); + + return { + dValue: res.state.d, + aValue: res.state.a, + totalLpAmount: res.rewards.lpSupply, + vUsdBalance: vUsdBalance, + tokenBalance: tokenBalance, + accRewardPerShareP: res.rewards.accRewardPerShareP, + p: P, + imbalance, + }; + } + + async buildRawTransactionDeposit(params: LiquidityPoolsParamsWithAmount): Promise { + const suiAddresses = params.token.suiAddresses; + if (!suiAddresses) { + throw new SdkError("SUI token must contain 'suiAddresses'"); + } + setAddress(suiAddresses.bridgeAddress, suiAddresses.bridgeAddressOrigin); + + if (!params.token.originTokenAddress) { + throw new SdkError("SUI token must contain 'originTokenAddress'"); + } + const coins: CoinStruct[] = await fetchAllPagesRecursive((cursor: string | null | undefined) => + this.client.getCoins({ + owner: params.accountAddress, + coinType: params.token.originTokenAddress, + cursor, + }) + ); + if (coins.length === 0 || !coins[0]) { + throw new InvalidAmountError("No coins to deposit"); + } + const firstCoin = coins[0]; + + const tx = new Transaction(); + tx.setSender(params.accountAddress); + const { depositObj, isNewDeposit } = await this.getDepositObject( + params.accountAddress, + params.token.originTokenAddress, + tx + ); + const [amountCoin] = getCoinsWithAmounts([params.amount], coins, tx); + if (!amountCoin) { + throw new InvalidAmountError("No coins to deposit"); + } + if (!params.token.originTokenAddress) { + throw new SdkError("SUI token must contain 'originTokenAddress'"); + } + const rewards = deposit(tx, params.token.originTokenAddress, { + bridge: suiAddresses.bridgeObjectAddress, + userDeposit: depositObj, + coin: amountCoin, + }); + tx.mergeCoins(firstCoin.coinObjectId, [rewards]); + if (isNewDeposit) { + tx.transferObjects([depositObj], params.accountAddress); + } + return await tx.toJSON({ client: this.client }); + } + + private async getDepositObject( + accountAddress: string, + tokenAddress: string, + tx: Transaction + ): Promise<{ + depositObj: string | TransactionResult; + isNewDeposit: boolean; + }> { + const deposits = await this.fetchDeposits(accountAddress, tokenAddress); + if (deposits.length === 0 || !deposits[0]) { + const tokenType = phantom(tokenAddress).phantomType; + const depositObj = newUserDeposit(tx, tokenType); + return { depositObj, isNewDeposit: true }; + } else { + if (deposits[0].data?.objectId) { + return { depositObj: deposits[0].data.objectId, isNewDeposit: false }; + } else { + throw new SdkError("Something went wrong while deposit"); + } + } + } + + async buildRawTransactionWithdraw(params: LiquidityPoolsParamsWithAmount): Promise { + const suiAddresses = params.token.suiAddresses; + if (!suiAddresses) { + throw new SdkError("SUI token must contain 'suiAddresses'"); + } + setAddress(suiAddresses.bridgeAddress, suiAddresses.bridgeAddressOrigin); + + if (!params.token.originTokenAddress) { + throw new SdkError("SUI token must contain 'originTokenAddress'"); + } + const tokenType = phantom(params.token.originTokenAddress).phantomType; + + const tx = new Transaction(); + tx.setSender(params.accountAddress); + + const { depositObj, isNewDeposit } = await this.getDepositObject( + params.accountAddress, + params.token.originTokenAddress, + tx + ); + if (isNewDeposit) { + throw new InvalidAmountError("No deposit found"); + } + + const rewards = withdraw(tx, tokenType, { + bridge: suiAddresses.bridgeObjectAddress, + userDeposit: depositObj, + amountLp: BigInt(params.amount), + }); + + const coins: CoinStruct[] = await fetchAllPagesRecursive((cursor: string | null | undefined) => + this.client.getCoins({ + owner: params.accountAddress, + coinType: params.token.originTokenAddress, + cursor, + }) + ); + + if (!rewards[0] || !rewards[1]) { + throw new SdkError("No rewards found"); + } + + if (coins[0]) { + tx.mergeCoins(coins[0].coinObjectId, [rewards[0], rewards[1]]); + } else { + tx.mergeCoins(rewards[0], [rewards[1]]); + tx.transferObjects([rewards[0]], params.accountAddress); + } + return await tx.toJSON({ client: this.client }); + } + + async buildRawTransactionClaimRewards(params: LiquidityPoolsParams): Promise { + const suiAddresses = params.token.suiAddresses; + if (!suiAddresses) { + throw new SdkError("SUI token must contain 'suiAddresses'"); + } + setAddress(suiAddresses.bridgeAddress, suiAddresses.bridgeAddressOrigin); + + if (!params.token.originTokenAddress) { + throw new SdkError("SUI token must contain 'originTokenAddress'"); + } + const tokenType = phantom(params.token.originTokenAddress).phantomType; + + const tx = new Transaction(); + tx.setSender(params.accountAddress); + + const { depositObj, isNewDeposit } = await this.getDepositObject( + params.accountAddress, + params.token.originTokenAddress, + tx + ); + if (isNewDeposit) { + throw new InvalidAmountError("No deposit found"); + } + + const reward = claimReward(tx, tokenType, { + bridge: suiAddresses.bridgeObjectAddress, + userDeposit: depositObj, + }); + + const coins: CoinStruct[] = await fetchAllPagesRecursive((cursor: string | null | undefined) => + this.client.getCoins({ + owner: params.accountAddress, + coinType: params.token.originTokenAddress, + cursor, + }) + ); + + if (coins[0]) { + tx.mergeCoins(coins[0].coinObjectId, [reward]); + } else { + tx.transferObjects([reward], params.accountAddress); + } + return await tx.toJSON({ client: this.client }); + } +} diff --git a/src/services/liquidity-pool/trx/index.ts b/src/services/liquidity-pool/trx/index.ts index 4d9d99f3..d0515475 100644 --- a/src/services/liquidity-pool/trx/index.ts +++ b/src/services/liquidity-pool/trx/index.ts @@ -24,7 +24,7 @@ export class TronPoolService extends ChainPoolService { constructor( public tronWeb: TronWeb, public api: AllbridgeCoreClient, - tronJsonRpc: string | undefined, + tronJsonRpc: string | undefined ) { super(); if (tronJsonRpc) { @@ -49,7 +49,7 @@ export class TronPoolService extends ChainPoolService { private async getUserBalanceInfoByBatch( web3: Web3, accountAddress: string, - token: TokenWithChainDetails, + token: TokenWithChainDetails ): Promise { const batch = new web3.BatchRequest(); const contract = new web3.eth.Contract(Pool.abi, tronAddressToEthAddress(token.poolAddress)); @@ -79,7 +79,7 @@ export class TronPoolService extends ChainPoolService { private async getUserBalanceInfoPerProperty( accountAddress: string, - token: TokenWithChainDetails, + token: TokenWithChainDetails ): Promise { if (!this.tronWeb.defaultAddress.base58) { this.tronWeb.setAddress(accountAddress); @@ -234,7 +234,7 @@ export class TronPoolService extends ChainPoolService { methodSignature: string, parameter: SmartContractMethodParameter[], value: string, - fromAddress: string, + fromAddress: string ): Promise { const transactionObject = await this.tronWeb.transactionBuilder.triggerSmartContract( contractAddress, @@ -243,7 +243,7 @@ export class TronPoolService extends ChainPoolService { callValue: +value, }, parameter, - fromAddress, + fromAddress ); if (!transactionObject?.result?.result) { throw new SdkError("Unknown error: " + JSON.stringify(transactionObject, null, 2)); diff --git a/src/services/models/index.ts b/src/services/models/index.ts index 42c2eabd..54f79bc0 100644 --- a/src/services/models/index.ts +++ b/src/services/models/index.ts @@ -58,6 +58,7 @@ export type RawTronTransaction = TronWebTransaction; export type RawSorobanTransaction = string; export type RawPoolSolanaTransaction = SolanaWeb3Transaction; export type RawBridgeSolanaTransaction = VersionedTransaction; +export type RawSuiTransaction = string; export interface SmartContractMethodParameter { type: string; diff --git a/src/services/models/srb/bridge-contract.ts b/src/services/models/srb/bridge-contract.ts index 17132b45..8db6ec54 100644 --- a/src/services/models/srb/bridge-contract.ts +++ b/src/services/models/srb/bridge-contract.ts @@ -149,7 +149,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -192,7 +192,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -233,7 +233,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -270,7 +270,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -333,7 +333,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -356,7 +356,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -379,7 +379,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -402,7 +402,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -425,7 +425,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -448,7 +448,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -471,7 +471,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -494,7 +494,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -517,7 +517,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -540,7 +540,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -563,7 +563,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -586,7 +586,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -609,7 +609,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -632,7 +632,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -695,7 +695,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -718,7 +718,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -781,7 +781,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -804,7 +804,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -827,7 +827,7 @@ export interface BridgeContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; } @@ -880,7 +880,7 @@ export class BridgeContract extends ContractClient { "AAAAAQAAAAAAAAAAAAAADVN0b3BBdXRob3JpdHkAAAAAAAABAAAAAAAAAAEwAAAAAAAAEw==", "AAAABAAAAAAAAAAAAAAABUVycm9yAAAAAAAAKAAAAAAAAAANVW5pbXBsZW1lbnRlZAAAAAAAAAAAAAAAAAAAC0luaXRpYWxpemVkAAAAAAEAAAAAAAAADVVuaW5pdGlhbGl6ZWQAAAAAAAACAAAAAAAAAAxVbmF1dGhvcml6ZWQAAAADAAAAAAAAAApJbnZhbGlkQXJnAAAAAAAEAAAAAAAAAA5JbnZhbGlkQ2hhaW5JZAAAAAAABQAAAAAAAAATSW52YWxpZE90aGVyQ2hhaW5JZAAAAAAGAAAAAAAAAA5HYXNVc2FnZU5vdFNldAAAAAAABwAAAAAAAAANQnJva2VuQWRkcmVzcwAAAAAAAAgAAAAAAAAACE5vdEZvdW5kAAAACQAAAAAAAAAYVG9rZW5JbnN1ZmZpY2llbnRCYWxhbmNlAAAACgAAAAAAAAAKQ2FzdEZhaWxlZAAAAAAACwAAAAAAAAAMVTI1Nk92ZXJmbG93AAAADAAAAAAAAAAKWmVyb0Ftb3VudAAAAAAAZwAAAAAAAAAMUG9vbE92ZXJmbG93AAAAaAAAAAAAAAALWmVyb0NoYW5nZXMAAAAAaQAAAAAAAAARUmVzZXJ2ZXNFeGhhdXN0ZWQAAAAAAABqAAAAAAAAABpJbnN1ZmZpY2llbnRSZWNlaXZlZEFtb3VudAAAAAAAawAAAAAAAAAUQmFsYW5jZVJhdGlvRXhjZWVkZWQAAABsAAAAAAAAAAlGb3JiaWRkZW4AAAAAAABtAAAAAAAAABlVbmF1dGhvcml6ZWRTdG9wQXV0aG9yaXR5AAAAAAAAywAAAAAAAAAOU3dhcFByb2hpYml0ZWQAAAAAAMwAAAAAAAAAEkFtb3VudFRvb0xvd0ZvckZlZQAAAAAAzQAAAAAAAAAWQnJpZGdlVG9UaGVaZXJvQWRkcmVzcwAAAAAAzgAAAAAAAAAORW1wdHlSZWNpcGllbnQAAAAAAM8AAAAAAAAAE1NvdXJjZU5vdFJlZ2lzdGVyZWQAAAAA0AAAAAAAAAAVV3JvbmdEZXN0aW5hdGlvbkNoYWluAAAAAAAA0QAAAAAAAAATVW5rbm93bkFub3RoZXJDaGFpbgAAAADSAAAAAAAAABFUb2tlbnNBbHJlYWR5U2VudAAAAAAAANMAAAAAAAAAEE1lc3NhZ2VQcm9jZXNzZWQAAADUAAAAAAAAAAxOb3RFbm91Z2hGZWUAAADWAAAAAAAAAAlOb01lc3NhZ2UAAAAAAADXAAAAAAAAAA1Ob1JlY2VpdmVQb29sAAAAAAAA2AAAAAAAAAAGTm9Qb29sAAAAAADZAAAAAAAAABNVbmtub3duQW5vdGhlclRva2VuAAAAANoAAAAAAAAAD1dyb25nQnl0ZUxlbmd0aAAAAAEsAAAAAAAAAApIYXNNZXNzYWdlAAAAAAEtAAAAAAAAABdJbnZhbGlkUHJpbWFyeVNpZ25hdHVyZQAAAAEuAAAAAAAAABlJbnZhbGlkU2Vjb25kYXJ5U2lnbmF0dXJlAAAAAAABLwAAAAAAAAARTm9HYXNEYXRhRm9yQ2hhaW4AAAAAAAGQ", ]), - options, + options ); } diff --git a/src/services/models/srb/gas-oracle-contract.ts b/src/services/models/srb/gas-oracle-contract.ts index 3bfe2944..b5c80d38 100644 --- a/src/services/models/srb/gas-oracle-contract.ts +++ b/src/services/models/srb/gas-oracle-contract.ts @@ -83,7 +83,7 @@ export interface GasOracleContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -114,7 +114,7 @@ export interface GasOracleContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -137,7 +137,7 @@ export interface GasOracleContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -160,7 +160,7 @@ export interface GasOracleContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -183,7 +183,7 @@ export interface GasOracleContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -206,7 +206,7 @@ export interface GasOracleContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -229,7 +229,7 @@ export interface GasOracleContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -252,7 +252,7 @@ export interface GasOracleContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -295,7 +295,7 @@ export interface GasOracleContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; } // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging @@ -321,7 +321,7 @@ export class GasOracleContract extends ContractClient { "AAAAAQAAAAAAAAAAAAAADVN0b3BBdXRob3JpdHkAAAAAAAABAAAAAAAAAAEwAAAAAAAAEw==", "AAAABAAAAAAAAAAAAAAABUVycm9yAAAAAAAAKAAAAAAAAAANVW5pbXBsZW1lbnRlZAAAAAAAAAAAAAAAAAAAC0luaXRpYWxpemVkAAAAAAEAAAAAAAAADVVuaW5pdGlhbGl6ZWQAAAAAAAACAAAAAAAAAAxVbmF1dGhvcml6ZWQAAAADAAAAAAAAAApJbnZhbGlkQXJnAAAAAAAEAAAAAAAAAA5JbnZhbGlkQ2hhaW5JZAAAAAAABQAAAAAAAAATSW52YWxpZE90aGVyQ2hhaW5JZAAAAAAGAAAAAAAAAA5HYXNVc2FnZU5vdFNldAAAAAAABwAAAAAAAAANQnJva2VuQWRkcmVzcwAAAAAAAAgAAAAAAAAACE5vdEZvdW5kAAAACQAAAAAAAAAYVG9rZW5JbnN1ZmZpY2llbnRCYWxhbmNlAAAACgAAAAAAAAAKQ2FzdEZhaWxlZAAAAAAACwAAAAAAAAAMVTI1Nk92ZXJmbG93AAAADAAAAAAAAAAKWmVyb0Ftb3VudAAAAAAAZwAAAAAAAAAMUG9vbE92ZXJmbG93AAAAaAAAAAAAAAALWmVyb0NoYW5nZXMAAAAAaQAAAAAAAAARUmVzZXJ2ZXNFeGhhdXN0ZWQAAAAAAABqAAAAAAAAABpJbnN1ZmZpY2llbnRSZWNlaXZlZEFtb3VudAAAAAAAawAAAAAAAAAUQmFsYW5jZVJhdGlvRXhjZWVkZWQAAABsAAAAAAAAAAlGb3JiaWRkZW4AAAAAAABtAAAAAAAAABlVbmF1dGhvcml6ZWRTdG9wQXV0aG9yaXR5AAAAAAAAywAAAAAAAAAOU3dhcFByb2hpYml0ZWQAAAAAAMwAAAAAAAAAEkFtb3VudFRvb0xvd0ZvckZlZQAAAAAAzQAAAAAAAAAWQnJpZGdlVG9UaGVaZXJvQWRkcmVzcwAAAAAAzgAAAAAAAAAORW1wdHlSZWNpcGllbnQAAAAAAM8AAAAAAAAAE1NvdXJjZU5vdFJlZ2lzdGVyZWQAAAAA0AAAAAAAAAAVV3JvbmdEZXN0aW5hdGlvbkNoYWluAAAAAAAA0QAAAAAAAAATVW5rbm93bkFub3RoZXJDaGFpbgAAAADSAAAAAAAAABFUb2tlbnNBbHJlYWR5U2VudAAAAAAAANMAAAAAAAAAEE1lc3NhZ2VQcm9jZXNzZWQAAADUAAAAAAAAAAxOb3RFbm91Z2hGZWUAAADWAAAAAAAAAAlOb01lc3NhZ2UAAAAAAADXAAAAAAAAAA1Ob1JlY2VpdmVQb29sAAAAAAAA2AAAAAAAAAAGTm9Qb29sAAAAAADZAAAAAAAAABNVbmtub3duQW5vdGhlclRva2VuAAAAANoAAAAAAAAAD1dyb25nQnl0ZUxlbmd0aAAAAAEsAAAAAAAAAApIYXNNZXNzYWdlAAAAAAEtAAAAAAAAABdJbnZhbGlkUHJpbWFyeVNpZ25hdHVyZQAAAAEuAAAAAAAAABlJbnZhbGlkU2Vjb25kYXJ5U2lnbmF0dXJlAAAAAAABLwAAAAAAAAARTm9HYXNEYXRhRm9yQ2hhaW4AAAAAAAGQ", ]), - options, + options ); } diff --git a/src/services/models/srb/messenger-contract.ts b/src/services/models/srb/messenger-contract.ts index 41c0ba9c..f7deff9e 100644 --- a/src/services/models/srb/messenger-contract.ts +++ b/src/services/models/srb/messenger-contract.ts @@ -117,7 +117,7 @@ export interface MessengerContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -140,7 +140,7 @@ export interface MessengerContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -175,7 +175,7 @@ export interface MessengerContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -198,7 +198,7 @@ export interface MessengerContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -221,7 +221,7 @@ export interface MessengerContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -244,7 +244,7 @@ export interface MessengerContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -267,7 +267,7 @@ export interface MessengerContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -290,7 +290,7 @@ export interface MessengerContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -313,7 +313,7 @@ export interface MessengerContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -336,7 +336,7 @@ export interface MessengerContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -359,7 +359,7 @@ export interface MessengerContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -402,7 +402,7 @@ export interface MessengerContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -425,7 +425,7 @@ export interface MessengerContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -448,7 +448,7 @@ export interface MessengerContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -471,7 +471,7 @@ export interface MessengerContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -494,7 +494,7 @@ export interface MessengerContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -557,7 +557,7 @@ export interface MessengerContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; } // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging @@ -597,7 +597,7 @@ export class MessengerContract extends ContractClient { "AAAAAQAAAAAAAAAAAAAADVN0b3BBdXRob3JpdHkAAAAAAAABAAAAAAAAAAEwAAAAAAAAEw==", "AAAABAAAAAAAAAAAAAAABUVycm9yAAAAAAAAKAAAAAAAAAANVW5pbXBsZW1lbnRlZAAAAAAAAAAAAAAAAAAAC0luaXRpYWxpemVkAAAAAAEAAAAAAAAADVVuaW5pdGlhbGl6ZWQAAAAAAAACAAAAAAAAAAxVbmF1dGhvcml6ZWQAAAADAAAAAAAAAApJbnZhbGlkQXJnAAAAAAAEAAAAAAAAAA5JbnZhbGlkQ2hhaW5JZAAAAAAABQAAAAAAAAATSW52YWxpZE90aGVyQ2hhaW5JZAAAAAAGAAAAAAAAAA5HYXNVc2FnZU5vdFNldAAAAAAABwAAAAAAAAANQnJva2VuQWRkcmVzcwAAAAAAAAgAAAAAAAAACE5vdEZvdW5kAAAACQAAAAAAAAAYVG9rZW5JbnN1ZmZpY2llbnRCYWxhbmNlAAAACgAAAAAAAAAKQ2FzdEZhaWxlZAAAAAAACwAAAAAAAAAMVTI1Nk92ZXJmbG93AAAADAAAAAAAAAAKWmVyb0Ftb3VudAAAAAAAZwAAAAAAAAAMUG9vbE92ZXJmbG93AAAAaAAAAAAAAAALWmVyb0NoYW5nZXMAAAAAaQAAAAAAAAARUmVzZXJ2ZXNFeGhhdXN0ZWQAAAAAAABqAAAAAAAAABpJbnN1ZmZpY2llbnRSZWNlaXZlZEFtb3VudAAAAAAAawAAAAAAAAAUQmFsYW5jZVJhdGlvRXhjZWVkZWQAAABsAAAAAAAAAAlGb3JiaWRkZW4AAAAAAABtAAAAAAAAABlVbmF1dGhvcml6ZWRTdG9wQXV0aG9yaXR5AAAAAAAAywAAAAAAAAAOU3dhcFByb2hpYml0ZWQAAAAAAMwAAAAAAAAAEkFtb3VudFRvb0xvd0ZvckZlZQAAAAAAzQAAAAAAAAAWQnJpZGdlVG9UaGVaZXJvQWRkcmVzcwAAAAAAzgAAAAAAAAAORW1wdHlSZWNpcGllbnQAAAAAAM8AAAAAAAAAE1NvdXJjZU5vdFJlZ2lzdGVyZWQAAAAA0AAAAAAAAAAVV3JvbmdEZXN0aW5hdGlvbkNoYWluAAAAAAAA0QAAAAAAAAATVW5rbm93bkFub3RoZXJDaGFpbgAAAADSAAAAAAAAABFUb2tlbnNBbHJlYWR5U2VudAAAAAAAANMAAAAAAAAAEE1lc3NhZ2VQcm9jZXNzZWQAAADUAAAAAAAAAAxOb3RFbm91Z2hGZWUAAADWAAAAAAAAAAlOb01lc3NhZ2UAAAAAAADXAAAAAAAAAA1Ob1JlY2VpdmVQb29sAAAAAAAA2AAAAAAAAAAGTm9Qb29sAAAAAADZAAAAAAAAABNVbmtub3duQW5vdGhlclRva2VuAAAAANoAAAAAAAAAD1dyb25nQnl0ZUxlbmd0aAAAAAEsAAAAAAAAAApIYXNNZXNzYWdlAAAAAAEtAAAAAAAAABdJbnZhbGlkUHJpbWFyeVNpZ25hdHVyZQAAAAEuAAAAAAAAABlJbnZhbGlkU2Vjb25kYXJ5U2lnbmF0dXJlAAAAAAABLwAAAAAAAAARTm9HYXNEYXRhRm9yQ2hhaW4AAAAAAAGQ", ]), - options, + options ); } public readonly fromJSON = { diff --git a/src/services/models/srb/pool-contract.ts b/src/services/models/srb/pool-contract.ts index 7e7ccc4c..315e3588 100644 --- a/src/services/models/srb/pool-contract.ts +++ b/src/services/models/srb/pool-contract.ts @@ -153,7 +153,7 @@ export interface PoolContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -176,7 +176,7 @@ export interface PoolContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -199,7 +199,7 @@ export interface PoolContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -222,7 +222,7 @@ export interface PoolContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -255,7 +255,7 @@ export interface PoolContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -278,7 +278,7 @@ export interface PoolContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -302,7 +302,7 @@ export interface PoolContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -345,7 +345,7 @@ export interface PoolContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -448,7 +448,7 @@ export interface PoolContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -471,7 +471,7 @@ export interface PoolContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -494,7 +494,7 @@ export interface PoolContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -517,7 +517,7 @@ export interface PoolContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -561,7 +561,7 @@ export interface PoolContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -664,7 +664,7 @@ export interface PoolContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; /** @@ -687,7 +687,7 @@ export interface PoolContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>>; } // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging @@ -736,7 +736,7 @@ export class PoolContract extends ContractClient { "AAAAAQAAAAAAAAAAAAAADVN0b3BBdXRob3JpdHkAAAAAAAABAAAAAAAAAAEwAAAAAAAAEw==", "AAAABAAAAAAAAAAAAAAABUVycm9yAAAAAAAAKAAAAAAAAAANVW5pbXBsZW1lbnRlZAAAAAAAAAAAAAAAAAAAC0luaXRpYWxpemVkAAAAAAEAAAAAAAAADVVuaW5pdGlhbGl6ZWQAAAAAAAACAAAAAAAAAAxVbmF1dGhvcml6ZWQAAAADAAAAAAAAAApJbnZhbGlkQXJnAAAAAAAEAAAAAAAAAA5JbnZhbGlkQ2hhaW5JZAAAAAAABQAAAAAAAAATSW52YWxpZE90aGVyQ2hhaW5JZAAAAAAGAAAAAAAAAA5HYXNVc2FnZU5vdFNldAAAAAAABwAAAAAAAAANQnJva2VuQWRkcmVzcwAAAAAAAAgAAAAAAAAACE5vdEZvdW5kAAAACQAAAAAAAAAYVG9rZW5JbnN1ZmZpY2llbnRCYWxhbmNlAAAACgAAAAAAAAAKQ2FzdEZhaWxlZAAAAAAACwAAAAAAAAAMVTI1Nk92ZXJmbG93AAAADAAAAAAAAAAKWmVyb0Ftb3VudAAAAAAAZwAAAAAAAAAMUG9vbE92ZXJmbG93AAAAaAAAAAAAAAALWmVyb0NoYW5nZXMAAAAAaQAAAAAAAAARUmVzZXJ2ZXNFeGhhdXN0ZWQAAAAAAABqAAAAAAAAABpJbnN1ZmZpY2llbnRSZWNlaXZlZEFtb3VudAAAAAAAawAAAAAAAAAUQmFsYW5jZVJhdGlvRXhjZWVkZWQAAABsAAAAAAAAAAlGb3JiaWRkZW4AAAAAAABtAAAAAAAAABlVbmF1dGhvcml6ZWRTdG9wQXV0aG9yaXR5AAAAAAAAywAAAAAAAAAOU3dhcFByb2hpYml0ZWQAAAAAAMwAAAAAAAAAEkFtb3VudFRvb0xvd0ZvckZlZQAAAAAAzQAAAAAAAAAWQnJpZGdlVG9UaGVaZXJvQWRkcmVzcwAAAAAAzgAAAAAAAAAORW1wdHlSZWNpcGllbnQAAAAAAM8AAAAAAAAAE1NvdXJjZU5vdFJlZ2lzdGVyZWQAAAAA0AAAAAAAAAAVV3JvbmdEZXN0aW5hdGlvbkNoYWluAAAAAAAA0QAAAAAAAAATVW5rbm93bkFub3RoZXJDaGFpbgAAAADSAAAAAAAAABFUb2tlbnNBbHJlYWR5U2VudAAAAAAAANMAAAAAAAAAEE1lc3NhZ2VQcm9jZXNzZWQAAADUAAAAAAAAAAxOb3RFbm91Z2hGZWUAAADWAAAAAAAAAAlOb01lc3NhZ2UAAAAAAADXAAAAAAAAAA1Ob1JlY2VpdmVQb29sAAAAAAAA2AAAAAAAAAAGTm9Qb29sAAAAAADZAAAAAAAAABNVbmtub3duQW5vdGhlclRva2VuAAAAANoAAAAAAAAAD1dyb25nQnl0ZUxlbmd0aAAAAAEsAAAAAAAAAApIYXNNZXNzYWdlAAAAAAEtAAAAAAAAABdJbnZhbGlkUHJpbWFyeVNpZ25hdHVyZQAAAAEuAAAAAAAAABlJbnZhbGlkU2Vjb25kYXJ5U2lnbmF0dXJlAAAAAAABLwAAAAAAAAARTm9HYXNEYXRhRm9yQ2hhaW4AAAAAAAGQ", ]), - options, + options ); } public readonly fromJSON = { diff --git a/src/services/models/srb/token-contract.ts b/src/services/models/srb/token-contract.ts index 044dfcbb..fd236293 100644 --- a/src/services/models/srb/token-contract.ts +++ b/src/services/models/srb/token-contract.ts @@ -39,7 +39,7 @@ export interface TokenContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>; /** @@ -67,7 +67,7 @@ export interface TokenContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>; /** @@ -123,7 +123,7 @@ export interface TokenContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>; /** @@ -152,7 +152,7 @@ export interface TokenContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>; /** @@ -190,7 +190,7 @@ export interface TokenContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>; /** @@ -235,7 +235,7 @@ export interface TokenContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>; /** @@ -271,7 +271,7 @@ export interface TokenContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>; /** @@ -330,7 +330,7 @@ export interface TokenContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>; /** @@ -389,7 +389,7 @@ export interface TokenContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>; /** @@ -449,7 +449,7 @@ export interface TokenContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>; /** @@ -510,7 +510,7 @@ export interface TokenContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>; /** @@ -555,7 +555,7 @@ export interface TokenContract { * Whether to automatically simulate the transaction when constructing the AssembledTransaction. Default: true */ simulate?: boolean; - }, + } ) => Promise>; } // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging @@ -580,7 +580,7 @@ export class TokenContract extends ContractClient { "AAAAAAAAAWRUcmFuc2ZlciBgYW1vdW50YCBmcm9tIGBmcm9tYCB0byBgdG9gLgoKIyBBcmd1bWVudHMKCiogYGZyb21gIC0gVGhlIGFkZHJlc3MgaG9sZGluZyB0aGUgYmFsYW5jZSBvZiB0b2tlbnMgd2hpY2ggd2lsbCBiZQp3aXRoZHJhd24gZnJvbS4KKiBgdG9gIC0gVGhlIGFkZHJlc3Mgd2hpY2ggd2lsbCByZWNlaXZlIHRoZSB0cmFuc2ZlcnJlZCB0b2tlbnMuCiogYGFtb3VudGAgLSBUaGUgYW1vdW50IG9mIHRva2VucyB0byBiZSB0cmFuc2ZlcnJlZC4KCiMgRXZlbnRzCgpFbWl0cyBhbiBldmVudCB3aXRoIHRvcGljcyBgWyJ0cmFuc2ZlciIsIGZyb206IEFkZHJlc3MsIHRvOiBBZGRyZXNzXSwKZGF0YSA9IFthbW91bnQ6IGkxMjhdYAAAAAh0cmFuc2ZlcgAAAAMAAAAAAAAABGZyb20AAAATAAAAAAAAAAJ0bwAAAAAAEwAAAAAAAAAGYW1vdW50AAAAAAALAAAAAA==", "AAAAAAAAAzNUcmFuc2ZlciBgYW1vdW50YCBmcm9tIGBmcm9tYCB0byBgdG9gLCBjb25zdW1pbmcgdGhlIGFsbG93YW5jZSB0aGF0CmBzcGVuZGVyYCBoYXMgb24gYGZyb21gJ3MgYmFsYW5jZS4gQXV0aG9yaXplZCBieSBzcGVuZGVyCihgc3BlbmRlci5yZXF1aXJlX2F1dGgoKWApLgoKVGhlIHNwZW5kZXIgd2lsbCBiZSBhbGxvd2VkIHRvIHRyYW5zZmVyIHRoZSBhbW91bnQgZnJvbSBmcm9tJ3MgYmFsYW5jZQppZiB0aGUgYW1vdW50IGlzIGxlc3MgdGhhbiBvciBlcXVhbCB0byB0aGUgYWxsb3dhbmNlIHRoYXQgdGhlIHNwZW5kZXIKaGFzIG9uIHRoZSBmcm9tJ3MgYmFsYW5jZS4gVGhlIHNwZW5kZXIncyBhbGxvd2FuY2Ugb24gZnJvbSdzIGJhbGFuY2UKd2lsbCBiZSByZWR1Y2VkIGJ5IHRoZSBhbW91bnQuCgojIEFyZ3VtZW50cwoKKiBgc3BlbmRlcmAgLSBUaGUgYWRkcmVzcyBhdXRob3JpemluZyB0aGUgdHJhbnNmZXIsIGFuZCBoYXZpbmcgaXRzCmFsbG93YW5jZSBjb25zdW1lZCBkdXJpbmcgdGhlIHRyYW5zZmVyLgoqIGBmcm9tYCAtIFRoZSBhZGRyZXNzIGhvbGRpbmcgdGhlIGJhbGFuY2Ugb2YgdG9rZW5zIHdoaWNoIHdpbGwgYmUKd2l0aGRyYXduIGZyb20uCiogYHRvYCAtIFRoZSBhZGRyZXNzIHdoaWNoIHdpbGwgcmVjZWl2ZSB0aGUgdHJhbnNmZXJyZWQgdG9rZW5zLgoqIGBhbW91bnRgIC0gVGhlIGFtb3VudCBvZiB0b2tlbnMgdG8gYmUgdHJhbnNmZXJyZWQuCgojIEV2ZW50cwoKRW1pdHMgYW4gZXZlbnQgd2l0aCB0b3BpY3MgYFsidHJhbnNmZXIiLCBmcm9tOiBBZGRyZXNzLCB0bzogQWRkcmVzc10sCmRhdGEgPSBbYW1vdW50OiBpMTI4XWAAAAAADXRyYW5zZmVyX2Zyb20AAAAAAAAEAAAAAAAAAAdzcGVuZGVyAAAAABMAAAAAAAAABGZyb20AAAATAAAAAAAAAAJ0bwAAAAAAEwAAAAAAAAAGYW1vdW50AAAAAAALAAAAAA==", ]), - options, + options ); } public readonly fromJSON = { diff --git a/src/services/models/sui/.eslintrc.json b/src/services/models/sui/.eslintrc.json new file mode 100644 index 00000000..2127959d --- /dev/null +++ b/src/services/models/sui/.eslintrc.json @@ -0,0 +1,7 @@ +{ + "rules": { + "@typescript-eslint/ban-types": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-unused-vars": "off" + } +} diff --git a/src/services/models/sui/_dependencies/source/0x1/ascii/structs.ts b/src/services/models/sui/_dependencies/source/0x1/ascii/structs.ts new file mode 100644 index 00000000..fffb2a5b --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x1/ascii/structs.ts @@ -0,0 +1,342 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { Vector } from "../../../../_framework/vector"; +import { PKG_V13 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Char =============================== */ + +export function isChar(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V13}::ascii::Char`; +} + +export interface CharFields { + byte: ToField<"u8">; +} + +export type CharReified = Reified; + +export class Char implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V13}::ascii::Char`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Char.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Char.$isPhantom; + + readonly byte: ToField<"u8">; + + private constructor(typeArgs: [], fields: CharFields) { + this.$fullTypeName = composeSuiType(Char.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.byte = fields.byte; + } + + static reified(): CharReified { + return { + typeName: Char.$typeName, + fullTypeName: composeSuiType(Char.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Char.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Char.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Char.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Char.fromBcs(data), + bcs: Char.bcs, + fromJSONField: (field: any) => Char.fromJSONField(field), + fromJSON: (json: Record) => Char.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Char.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Char.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Char.fetch(client, id), + new: (fields: CharFields) => { + return new Char([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Char.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Char.reified()); + } + static get p() { + return Char.phantom(); + } + + static get bcs() { + return bcs.struct("Char", { + byte: bcs.u8(), + }); + } + + static fromFields(fields: Record): Char { + return Char.reified().new({ byte: decodeFromFields("u8", fields.byte) }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Char { + if (!isChar(item.type)) { + throw new Error("not a Char type"); + } + + return Char.reified().new({ + byte: decodeFromFieldsWithTypes("u8", item.fields.byte), + }); + } + + static fromBcs(data: Uint8Array): Char { + return Char.fromFields(Char.bcs.parse(data)); + } + + toJSONField() { + return { + byte: this.byte, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Char { + return Char.reified().new({ byte: decodeFromJSONField("u8", field.byte) }); + } + + static fromJSON(json: Record): Char { + if (json.$typeName !== Char.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Char.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Char { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isChar(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Char object`); + } + return Char.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Char { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isChar(data.bcs.type)) { + throw new Error(`object at is not a Char object`); + } + + return Char.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Char.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Char object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isChar(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Char object`); + } + + return Char.fromSuiObjectData(res.data); + } +} + +/* ============================== String =============================== */ + +export function isString(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V13}::ascii::String`; +} + +export interface StringFields { + bytes: ToField>; +} + +export type StringReified = Reified; + +export class String implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V13}::ascii::String`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = String.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = String.$isPhantom; + + readonly bytes: ToField>; + + private constructor(typeArgs: [], fields: StringFields) { + this.$fullTypeName = composeSuiType(String.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.bytes = fields.bytes; + } + + static reified(): StringReified { + return { + typeName: String.$typeName, + fullTypeName: composeSuiType(String.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: String.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => String.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => String.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => String.fromBcs(data), + bcs: String.bcs, + fromJSONField: (field: any) => String.fromJSONField(field), + fromJSON: (json: Record) => String.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => String.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => String.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => String.fetch(client, id), + new: (fields: StringFields) => { + return new String([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return String.reified(); + } + + static phantom(): PhantomReified> { + return phantom(String.reified()); + } + static get p() { + return String.phantom(); + } + + static get bcs() { + return bcs.struct("String", { + bytes: bcs.vector(bcs.u8()), + }); + } + + static fromFields(fields: Record): String { + return String.reified().new({ + bytes: decodeFromFields(reified.vector("u8"), fields.bytes), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): String { + if (!isString(item.type)) { + throw new Error("not a String type"); + } + + return String.reified().new({ + bytes: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.bytes), + }); + } + + static fromBcs(data: Uint8Array): String { + return String.fromFields(String.bcs.parse(data)); + } + + toJSONField() { + return { + bytes: fieldToJSON>(`vector`, this.bytes), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): String { + return String.reified().new({ + bytes: decodeFromJSONField(reified.vector("u8"), field.bytes), + }); + } + + static fromJSON(json: Record): String { + if (json.$typeName !== String.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return String.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): String { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isString(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a String object`); + } + return String.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): String { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isString(data.bcs.type)) { + throw new Error(`object at is not a String object`); + } + + return String.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return String.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching String object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isString(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a String object`); + } + + return String.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0x1/bit-vector/structs.ts b/src/services/models/sui/_dependencies/source/0x1/bit-vector/structs.ts new file mode 100644 index 00000000..f0c6f6ab --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x1/bit-vector/structs.ts @@ -0,0 +1,191 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { Vector } from "../../../../_framework/vector"; +import { PKG_V13 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== BitVector =============================== */ + +export function isBitVector(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V13}::bit_vector::BitVector`; +} + +export interface BitVectorFields { + length: ToField<"u64">; + bitField: ToField>; +} + +export type BitVectorReified = Reified; + +export class BitVector implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V13}::bit_vector::BitVector`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = BitVector.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = BitVector.$isPhantom; + + readonly length: ToField<"u64">; + readonly bitField: ToField>; + + private constructor(typeArgs: [], fields: BitVectorFields) { + this.$fullTypeName = composeSuiType(BitVector.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.length = fields.length; + this.bitField = fields.bitField; + } + + static reified(): BitVectorReified { + return { + typeName: BitVector.$typeName, + fullTypeName: composeSuiType(BitVector.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: BitVector.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => BitVector.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => BitVector.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => BitVector.fromBcs(data), + bcs: BitVector.bcs, + fromJSONField: (field: any) => BitVector.fromJSONField(field), + fromJSON: (json: Record) => BitVector.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => BitVector.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => BitVector.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => BitVector.fetch(client, id), + new: (fields: BitVectorFields) => { + return new BitVector([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return BitVector.reified(); + } + + static phantom(): PhantomReified> { + return phantom(BitVector.reified()); + } + static get p() { + return BitVector.phantom(); + } + + static get bcs() { + return bcs.struct("BitVector", { + length: bcs.u64(), + bit_field: bcs.vector(bcs.bool()), + }); + } + + static fromFields(fields: Record): BitVector { + return BitVector.reified().new({ + length: decodeFromFields("u64", fields.length), + bitField: decodeFromFields(reified.vector("bool"), fields.bit_field), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): BitVector { + if (!isBitVector(item.type)) { + throw new Error("not a BitVector type"); + } + + return BitVector.reified().new({ + length: decodeFromFieldsWithTypes("u64", item.fields.length), + bitField: decodeFromFieldsWithTypes(reified.vector("bool"), item.fields.bit_field), + }); + } + + static fromBcs(data: Uint8Array): BitVector { + return BitVector.fromFields(BitVector.bcs.parse(data)); + } + + toJSONField() { + return { + length: this.length.toString(), + bitField: fieldToJSON>(`vector`, this.bitField), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): BitVector { + return BitVector.reified().new({ + length: decodeFromJSONField("u64", field.length), + bitField: decodeFromJSONField(reified.vector("bool"), field.bitField), + }); + } + + static fromJSON(json: Record): BitVector { + if (json.$typeName !== BitVector.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return BitVector.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): BitVector { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isBitVector(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a BitVector object`); + } + return BitVector.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): BitVector { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isBitVector(data.bcs.type)) { + throw new Error(`object at is not a BitVector object`); + } + + return BitVector.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return BitVector.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching BitVector object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isBitVector(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a BitVector object`); + } + + return BitVector.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0x1/fixed-point32/structs.ts b/src/services/models/sui/_dependencies/source/0x1/fixed-point32/structs.ts new file mode 100644 index 00000000..3523d7a1 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x1/fixed-point32/structs.ts @@ -0,0 +1,180 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { PKG_V13 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== FixedPoint32 =============================== */ + +export function isFixedPoint32(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V13}::fixed_point32::FixedPoint32`; +} + +export interface FixedPoint32Fields { + value: ToField<"u64">; +} + +export type FixedPoint32Reified = Reified; + +export class FixedPoint32 implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V13}::fixed_point32::FixedPoint32`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = FixedPoint32.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = FixedPoint32.$isPhantom; + + readonly value: ToField<"u64">; + + private constructor(typeArgs: [], fields: FixedPoint32Fields) { + this.$fullTypeName = composeSuiType(FixedPoint32.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.value = fields.value; + } + + static reified(): FixedPoint32Reified { + return { + typeName: FixedPoint32.$typeName, + fullTypeName: composeSuiType(FixedPoint32.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: FixedPoint32.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => FixedPoint32.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => FixedPoint32.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => FixedPoint32.fromBcs(data), + bcs: FixedPoint32.bcs, + fromJSONField: (field: any) => FixedPoint32.fromJSONField(field), + fromJSON: (json: Record) => FixedPoint32.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => FixedPoint32.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => FixedPoint32.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => FixedPoint32.fetch(client, id), + new: (fields: FixedPoint32Fields) => { + return new FixedPoint32([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return FixedPoint32.reified(); + } + + static phantom(): PhantomReified> { + return phantom(FixedPoint32.reified()); + } + static get p() { + return FixedPoint32.phantom(); + } + + static get bcs() { + return bcs.struct("FixedPoint32", { + value: bcs.u64(), + }); + } + + static fromFields(fields: Record): FixedPoint32 { + return FixedPoint32.reified().new({ + value: decodeFromFields("u64", fields.value), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): FixedPoint32 { + if (!isFixedPoint32(item.type)) { + throw new Error("not a FixedPoint32 type"); + } + + return FixedPoint32.reified().new({ + value: decodeFromFieldsWithTypes("u64", item.fields.value), + }); + } + + static fromBcs(data: Uint8Array): FixedPoint32 { + return FixedPoint32.fromFields(FixedPoint32.bcs.parse(data)); + } + + toJSONField() { + return { + value: this.value.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): FixedPoint32 { + return FixedPoint32.reified().new({ + value: decodeFromJSONField("u64", field.value), + }); + } + + static fromJSON(json: Record): FixedPoint32 { + if (json.$typeName !== FixedPoint32.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return FixedPoint32.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): FixedPoint32 { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isFixedPoint32(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a FixedPoint32 object`); + } + return FixedPoint32.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): FixedPoint32 { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isFixedPoint32(data.bcs.type)) { + throw new Error(`object at is not a FixedPoint32 object`); + } + + return FixedPoint32.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return FixedPoint32.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching FixedPoint32 object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isFixedPoint32(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a FixedPoint32 object`); + } + + return FixedPoint32.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0x1/index.ts b/src/services/models/sui/_dependencies/source/0x1/index.ts new file mode 100644 index 00000000..21d7d659 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x1/index.ts @@ -0,0 +1,4 @@ +// @ts-nocheck +export const PACKAGE_ID = "0x1"; +export const PUBLISHED_AT = "0x1"; +export const PKG_V13 = "0x1"; diff --git a/src/services/models/sui/_dependencies/source/0x1/init.ts b/src/services/models/sui/_dependencies/source/0x1/init.ts new file mode 100644 index 00000000..e3bcda58 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x1/init.ts @@ -0,0 +1,22 @@ +// @ts-nocheck +import * as ascii from "./ascii/structs"; +import * as bitVector from "./bit-vector/structs"; +import * as fixedPoint32 from "./fixed-point32/structs"; +import * as option from "./option/structs"; +import * as string from "./string/structs"; +import * as typeName from "./type-name/structs"; +import * as uq3232 from "./uq32-32/structs"; +import * as uq6464 from "./uq64-64/structs"; +import { StructClassLoader } from "../../../_framework/loader"; + +export function registerClasses(loader: StructClassLoader) { + loader.register(fixedPoint32.FixedPoint32); + loader.register(uq3232.UQ32_32); + loader.register(uq6464.UQ64_64); + loader.register(option.Option); + loader.register(ascii.Char); + loader.register(ascii.String); + loader.register(string.String); + loader.register(typeName.TypeName); + loader.register(bitVector.BitVector); +} diff --git a/src/services/models/sui/_dependencies/source/0x1/option/structs.ts b/src/services/models/sui/_dependencies/source/0x1/option/structs.ts new file mode 100644 index 00000000..2f3c489e --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x1/option/structs.ts @@ -0,0 +1,233 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeArgument, + ToTypeStr, + TypeArgument, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + fieldToJSON, + phantom, + toBcs, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../../../_framework/util"; +import { Vector } from "../../../../_framework/vector"; +import { PKG_V13 } from "../index"; +import { BcsType, bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Option =============================== */ + +export function isOption(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V13}::option::Option` + "<"); +} + +export interface OptionFields { + vec: ToField>; +} + +export type OptionReified = Reified, OptionFields>; + +export class Option implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V13}::option::Option`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [false] as const; + + __inner: Element = null as unknown as Element; // for type checking in reified.ts + + readonly $typeName = Option.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [ToTypeStr]; + readonly $isPhantom = Option.$isPhantom; + + readonly vec: ToField>; + + private constructor(typeArgs: [ToTypeStr], fields: OptionFields) { + this.$fullTypeName = composeSuiType(Option.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.vec = fields.vec; + } + + static reified>(Element: Element): OptionReified> { + return { + typeName: Option.$typeName, + fullTypeName: composeSuiType(Option.$typeName, ...[extractType(Element)]) as string, + typeArgs: [extractType(Element)] as [ToTypeStr>], + isPhantom: Option.$isPhantom, + reifiedTypeArgs: [Element], + fromFields: (fields: Record) => Option.fromFields(Element, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Option.fromFieldsWithTypes(Element, item), + fromBcs: (data: Uint8Array) => Option.fromBcs(Element, data), + bcs: Option.bcs(toBcs(Element)), + fromJSONField: (field: any) => Option.fromJSONField(Element, field), + fromJSON: (json: Record) => Option.fromJSON(Element, json), + fromSuiParsedData: (content: SuiParsedData) => Option.fromSuiParsedData(Element, content), + fromSuiObjectData: (content: SuiObjectData) => Option.fromSuiObjectData(Element, content), + fetch: async (client: SuiClient, id: string) => Option.fetch(client, Element, id), + new: (fields: OptionFields>) => { + return new Option([extractType(Element)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Option.reified; + } + + static phantom>( + Element: Element + ): PhantomReified>>> { + return phantom(Option.reified(Element)); + } + static get p() { + return Option.phantom; + } + + static get bcs() { + return >(Element: Element) => + bcs.struct(`Option<${Element.name}>`, { + vec: bcs.vector(Element), + }); + } + + static fromFields>( + typeArg: Element, + fields: Record + ): Option> { + return Option.reified(typeArg).new({ + vec: decodeFromFields(reified.vector(typeArg), fields.vec), + }); + } + + static fromFieldsWithTypes>( + typeArg: Element, + item: FieldsWithTypes + ): Option> { + if (!isOption(item.type)) { + throw new Error("not a Option type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Option.reified(typeArg).new({ + vec: decodeFromFieldsWithTypes(reified.vector(typeArg), item.fields.vec), + }); + } + + static fromBcs>( + typeArg: Element, + data: Uint8Array + ): Option> { + const typeArgs = [typeArg]; + + return Option.fromFields(typeArg, Option.bcs(toBcs(typeArgs[0])).parse(data)); + } + + toJSONField() { + return { + vec: fieldToJSON>(`vector<${this.$typeArgs[0]}>`, this.vec), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: Element, + field: any + ): Option> { + return Option.reified(typeArg).new({ + vec: decodeFromJSONField(reified.vector(typeArg), field.vec), + }); + } + + static fromJSON>( + typeArg: Element, + json: Record + ): Option> { + if (json.$typeName !== Option.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Option.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Option.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: Element, + content: SuiParsedData + ): Option> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isOption(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Option object`); + } + return Option.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: Element, + data: SuiObjectData + ): Option> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isOption(data.bcs.type)) { + throw new Error(`object at is not a Option object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Option.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Option.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: Element, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Option object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isOption(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Option object`); + } + + return Option.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0x1/string/structs.ts b/src/services/models/sui/_dependencies/source/0x1/string/structs.ts new file mode 100644 index 00000000..3f3eb39b --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x1/string/structs.ts @@ -0,0 +1,183 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { Vector } from "../../../../_framework/vector"; +import { PKG_V13 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== String =============================== */ + +export function isString(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V13}::string::String`; +} + +export interface StringFields { + bytes: ToField>; +} + +export type StringReified = Reified; + +export class String implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V13}::string::String`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = String.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = String.$isPhantom; + + readonly bytes: ToField>; + + private constructor(typeArgs: [], fields: StringFields) { + this.$fullTypeName = composeSuiType(String.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.bytes = fields.bytes; + } + + static reified(): StringReified { + return { + typeName: String.$typeName, + fullTypeName: composeSuiType(String.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: String.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => String.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => String.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => String.fromBcs(data), + bcs: String.bcs, + fromJSONField: (field: any) => String.fromJSONField(field), + fromJSON: (json: Record) => String.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => String.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => String.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => String.fetch(client, id), + new: (fields: StringFields) => { + return new String([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return String.reified(); + } + + static phantom(): PhantomReified> { + return phantom(String.reified()); + } + static get p() { + return String.phantom(); + } + + static get bcs() { + return bcs.struct("String", { + bytes: bcs.vector(bcs.u8()), + }); + } + + static fromFields(fields: Record): String { + return String.reified().new({ + bytes: decodeFromFields(reified.vector("u8"), fields.bytes), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): String { + if (!isString(item.type)) { + throw new Error("not a String type"); + } + + return String.reified().new({ + bytes: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.bytes), + }); + } + + static fromBcs(data: Uint8Array): String { + return String.fromFields(String.bcs.parse(data)); + } + + toJSONField() { + return { + bytes: fieldToJSON>(`vector`, this.bytes), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): String { + return String.reified().new({ + bytes: decodeFromJSONField(reified.vector("u8"), field.bytes), + }); + } + + static fromJSON(json: Record): String { + if (json.$typeName !== String.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return String.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): String { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isString(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a String object`); + } + return String.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): String { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isString(data.bcs.type)) { + throw new Error(`object at is not a String object`); + } + + return String.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return String.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching String object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isString(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a String object`); + } + + return String.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0x1/type-name/structs.ts b/src/services/models/sui/_dependencies/source/0x1/type-name/structs.ts new file mode 100644 index 00000000..574f1997 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x1/type-name/structs.ts @@ -0,0 +1,181 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { String } from "../ascii/structs"; +import { PKG_V13 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== TypeName =============================== */ + +export function isTypeName(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V13}::type_name::TypeName`; +} + +export interface TypeNameFields { + name: ToField; +} + +export type TypeNameReified = Reified; + +export class TypeName implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V13}::type_name::TypeName`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = TypeName.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = TypeName.$isPhantom; + + readonly name: ToField; + + private constructor(typeArgs: [], fields: TypeNameFields) { + this.$fullTypeName = composeSuiType(TypeName.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.name = fields.name; + } + + static reified(): TypeNameReified { + return { + typeName: TypeName.$typeName, + fullTypeName: composeSuiType(TypeName.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: TypeName.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => TypeName.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => TypeName.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => TypeName.fromBcs(data), + bcs: TypeName.bcs, + fromJSONField: (field: any) => TypeName.fromJSONField(field), + fromJSON: (json: Record) => TypeName.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => TypeName.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => TypeName.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => TypeName.fetch(client, id), + new: (fields: TypeNameFields) => { + return new TypeName([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return TypeName.reified(); + } + + static phantom(): PhantomReified> { + return phantom(TypeName.reified()); + } + static get p() { + return TypeName.phantom(); + } + + static get bcs() { + return bcs.struct("TypeName", { + name: String.bcs, + }); + } + + static fromFields(fields: Record): TypeName { + return TypeName.reified().new({ + name: decodeFromFields(String.reified(), fields.name), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): TypeName { + if (!isTypeName(item.type)) { + throw new Error("not a TypeName type"); + } + + return TypeName.reified().new({ + name: decodeFromFieldsWithTypes(String.reified(), item.fields.name), + }); + } + + static fromBcs(data: Uint8Array): TypeName { + return TypeName.fromFields(TypeName.bcs.parse(data)); + } + + toJSONField() { + return { + name: this.name, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): TypeName { + return TypeName.reified().new({ + name: decodeFromJSONField(String.reified(), field.name), + }); + } + + static fromJSON(json: Record): TypeName { + if (json.$typeName !== TypeName.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return TypeName.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): TypeName { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTypeName(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a TypeName object`); + } + return TypeName.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): TypeName { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTypeName(data.bcs.type)) { + throw new Error(`object at is not a TypeName object`); + } + + return TypeName.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return TypeName.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching TypeName object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTypeName(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a TypeName object`); + } + + return TypeName.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0x1/uq32-32/structs.ts b/src/services/models/sui/_dependencies/source/0x1/uq32-32/structs.ts new file mode 100644 index 00000000..67f8f83f --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x1/uq32-32/structs.ts @@ -0,0 +1,180 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { PKG_V13 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== UQ32_32 =============================== */ + +export function isUQ32_32(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V13}::uq32_32::UQ32_32`; +} + +export interface UQ32_32Fields { + pos0: ToField<"u64">; +} + +export type UQ32_32Reified = Reified; + +export class UQ32_32 implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V13}::uq32_32::UQ32_32`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = UQ32_32.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = UQ32_32.$isPhantom; + + readonly pos0: ToField<"u64">; + + private constructor(typeArgs: [], fields: UQ32_32Fields) { + this.$fullTypeName = composeSuiType(UQ32_32.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.pos0 = fields.pos0; + } + + static reified(): UQ32_32Reified { + return { + typeName: UQ32_32.$typeName, + fullTypeName: composeSuiType(UQ32_32.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: UQ32_32.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => UQ32_32.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => UQ32_32.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => UQ32_32.fromBcs(data), + bcs: UQ32_32.bcs, + fromJSONField: (field: any) => UQ32_32.fromJSONField(field), + fromJSON: (json: Record) => UQ32_32.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => UQ32_32.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => UQ32_32.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => UQ32_32.fetch(client, id), + new: (fields: UQ32_32Fields) => { + return new UQ32_32([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return UQ32_32.reified(); + } + + static phantom(): PhantomReified> { + return phantom(UQ32_32.reified()); + } + static get p() { + return UQ32_32.phantom(); + } + + static get bcs() { + return bcs.struct("UQ32_32", { + pos0: bcs.u64(), + }); + } + + static fromFields(fields: Record): UQ32_32 { + return UQ32_32.reified().new({ + pos0: decodeFromFields("u64", fields.pos0), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): UQ32_32 { + if (!isUQ32_32(item.type)) { + throw new Error("not a UQ32_32 type"); + } + + return UQ32_32.reified().new({ + pos0: decodeFromFieldsWithTypes("u64", item.fields.pos0), + }); + } + + static fromBcs(data: Uint8Array): UQ32_32 { + return UQ32_32.fromFields(UQ32_32.bcs.parse(data)); + } + + toJSONField() { + return { + pos0: this.pos0.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): UQ32_32 { + return UQ32_32.reified().new({ + pos0: decodeFromJSONField("u64", field.pos0), + }); + } + + static fromJSON(json: Record): UQ32_32 { + if (json.$typeName !== UQ32_32.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return UQ32_32.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): UQ32_32 { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isUQ32_32(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a UQ32_32 object`); + } + return UQ32_32.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): UQ32_32 { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isUQ32_32(data.bcs.type)) { + throw new Error(`object at is not a UQ32_32 object`); + } + + return UQ32_32.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return UQ32_32.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching UQ32_32 object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isUQ32_32(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a UQ32_32 object`); + } + + return UQ32_32.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0x1/uq64-64/structs.ts b/src/services/models/sui/_dependencies/source/0x1/uq64-64/structs.ts new file mode 100644 index 00000000..87358165 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x1/uq64-64/structs.ts @@ -0,0 +1,180 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { PKG_V13 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== UQ64_64 =============================== */ + +export function isUQ64_64(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V13}::uq64_64::UQ64_64`; +} + +export interface UQ64_64Fields { + pos0: ToField<"u128">; +} + +export type UQ64_64Reified = Reified; + +export class UQ64_64 implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V13}::uq64_64::UQ64_64`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = UQ64_64.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = UQ64_64.$isPhantom; + + readonly pos0: ToField<"u128">; + + private constructor(typeArgs: [], fields: UQ64_64Fields) { + this.$fullTypeName = composeSuiType(UQ64_64.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.pos0 = fields.pos0; + } + + static reified(): UQ64_64Reified { + return { + typeName: UQ64_64.$typeName, + fullTypeName: composeSuiType(UQ64_64.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: UQ64_64.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => UQ64_64.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => UQ64_64.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => UQ64_64.fromBcs(data), + bcs: UQ64_64.bcs, + fromJSONField: (field: any) => UQ64_64.fromJSONField(field), + fromJSON: (json: Record) => UQ64_64.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => UQ64_64.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => UQ64_64.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => UQ64_64.fetch(client, id), + new: (fields: UQ64_64Fields) => { + return new UQ64_64([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return UQ64_64.reified(); + } + + static phantom(): PhantomReified> { + return phantom(UQ64_64.reified()); + } + static get p() { + return UQ64_64.phantom(); + } + + static get bcs() { + return bcs.struct("UQ64_64", { + pos0: bcs.u128(), + }); + } + + static fromFields(fields: Record): UQ64_64 { + return UQ64_64.reified().new({ + pos0: decodeFromFields("u128", fields.pos0), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): UQ64_64 { + if (!isUQ64_64(item.type)) { + throw new Error("not a UQ64_64 type"); + } + + return UQ64_64.reified().new({ + pos0: decodeFromFieldsWithTypes("u128", item.fields.pos0), + }); + } + + static fromBcs(data: Uint8Array): UQ64_64 { + return UQ64_64.fromFields(UQ64_64.bcs.parse(data)); + } + + toJSONField() { + return { + pos0: this.pos0.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): UQ64_64 { + return UQ64_64.reified().new({ + pos0: decodeFromJSONField("u128", field.pos0), + }); + } + + static fromJSON(json: Record): UQ64_64 { + if (json.$typeName !== UQ64_64.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return UQ64_64.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): UQ64_64 { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isUQ64_64(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a UQ64_64 object`); + } + return UQ64_64.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): UQ64_64 { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isUQ64_64(data.bcs.type)) { + throw new Error(`object at is not a UQ64_64 object`); + } + + return UQ64_64.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return UQ64_64.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching UQ64_64 object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isUQ64_64(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a UQ64_64 object`); + } + + return UQ64_64.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/burn-message/structs.ts b/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/burn-message/structs.ts new file mode 100644 index 00000000..69396a1c --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/burn-message/structs.ts @@ -0,0 +1,221 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64, fromHEX, toHEX } from "@mysten/sui/utils"; + +/* ============================== BurnMessage =============================== */ + +export function isBurnMessage(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::burn_message::BurnMessage`; +} + +export interface BurnMessageFields { + version: ToField<"u32">; + burnToken: ToField<"address">; + mintRecipient: ToField<"address">; + amount: ToField<"u256">; + messageSender: ToField<"address">; +} + +export type BurnMessageReified = Reified; + +export class BurnMessage implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::burn_message::BurnMessage`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = BurnMessage.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = BurnMessage.$isPhantom; + + readonly version: ToField<"u32">; + readonly burnToken: ToField<"address">; + readonly mintRecipient: ToField<"address">; + readonly amount: ToField<"u256">; + readonly messageSender: ToField<"address">; + + private constructor(typeArgs: [], fields: BurnMessageFields) { + this.$fullTypeName = composeSuiType(BurnMessage.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.version = fields.version; + this.burnToken = fields.burnToken; + this.mintRecipient = fields.mintRecipient; + this.amount = fields.amount; + this.messageSender = fields.messageSender; + } + + static reified(): BurnMessageReified { + return { + typeName: BurnMessage.$typeName, + fullTypeName: composeSuiType(BurnMessage.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: BurnMessage.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => BurnMessage.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => BurnMessage.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => BurnMessage.fromBcs(data), + bcs: BurnMessage.bcs, + fromJSONField: (field: any) => BurnMessage.fromJSONField(field), + fromJSON: (json: Record) => BurnMessage.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => BurnMessage.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => BurnMessage.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => BurnMessage.fetch(client, id), + new: (fields: BurnMessageFields) => { + return new BurnMessage([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return BurnMessage.reified(); + } + + static phantom(): PhantomReified> { + return phantom(BurnMessage.reified()); + } + static get p() { + return BurnMessage.phantom(); + } + + static get bcs() { + return bcs.struct("BurnMessage", { + version: bcs.u32(), + burn_token: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + mint_recipient: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + amount: bcs.u256(), + message_sender: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + }); + } + + static fromFields(fields: Record): BurnMessage { + return BurnMessage.reified().new({ + version: decodeFromFields("u32", fields.version), + burnToken: decodeFromFields("address", fields.burn_token), + mintRecipient: decodeFromFields("address", fields.mint_recipient), + amount: decodeFromFields("u256", fields.amount), + messageSender: decodeFromFields("address", fields.message_sender), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): BurnMessage { + if (!isBurnMessage(item.type)) { + throw new Error("not a BurnMessage type"); + } + + return BurnMessage.reified().new({ + version: decodeFromFieldsWithTypes("u32", item.fields.version), + burnToken: decodeFromFieldsWithTypes("address", item.fields.burn_token), + mintRecipient: decodeFromFieldsWithTypes("address", item.fields.mint_recipient), + amount: decodeFromFieldsWithTypes("u256", item.fields.amount), + messageSender: decodeFromFieldsWithTypes("address", item.fields.message_sender), + }); + } + + static fromBcs(data: Uint8Array): BurnMessage { + return BurnMessage.fromFields(BurnMessage.bcs.parse(data)); + } + + toJSONField() { + return { + version: this.version, + burnToken: this.burnToken, + mintRecipient: this.mintRecipient, + amount: this.amount.toString(), + messageSender: this.messageSender, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): BurnMessage { + return BurnMessage.reified().new({ + version: decodeFromJSONField("u32", field.version), + burnToken: decodeFromJSONField("address", field.burnToken), + mintRecipient: decodeFromJSONField("address", field.mintRecipient), + amount: decodeFromJSONField("u256", field.amount), + messageSender: decodeFromJSONField("address", field.messageSender), + }); + } + + static fromJSON(json: Record): BurnMessage { + if (json.$typeName !== BurnMessage.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return BurnMessage.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): BurnMessage { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isBurnMessage(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a BurnMessage object`); + } + return BurnMessage.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): BurnMessage { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isBurnMessage(data.bcs.type)) { + throw new Error(`object at is not a BurnMessage object`); + } + + return BurnMessage.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return BurnMessage.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching BurnMessage object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isBurnMessage(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a BurnMessage object`); + } + + return BurnMessage.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/deposit-for-burn/structs.ts b/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/deposit-for-burn/structs.ts new file mode 100644 index 00000000..694e5ceb --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/deposit-for-burn/structs.ts @@ -0,0 +1,538 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeArgument, + ToTypeStr, + TypeArgument, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + fieldToJSON, + phantom, + toBcs, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../../../_framework/util"; +import { Vector } from "../../../../_framework/vector"; +import { Coin } from "../../../../sui/coin/structs"; +import { Option } from "../../0x1/option/structs"; +import { PKG_V1 } from "../index"; +import { BcsType, bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64, fromHEX, toHEX } from "@mysten/sui/utils"; + +/* ============================== DepositForBurnTicket =============================== */ + +export function isDepositForBurnTicket(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V1}::deposit_for_burn::DepositForBurnTicket` + "<"); +} + +export interface DepositForBurnTicketFields { + auth: ToField; + coins: ToField>; + destinationDomain: ToField<"u32">; + mintRecipient: ToField<"address">; +} + +export type DepositForBurnTicketReified = Reified< + DepositForBurnTicket, + DepositForBurnTicketFields +>; + +export class DepositForBurnTicket implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::deposit_for_burn::DepositForBurnTicket`; + } + static readonly $numTypeParams = 2; + static readonly $isPhantom = [true, false] as const; + + readonly $typeName = DepositForBurnTicket.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr, ToTypeStr]; + readonly $isPhantom = DepositForBurnTicket.$isPhantom; + + readonly auth: ToField; + readonly coins: ToField>; + readonly destinationDomain: ToField<"u32">; + readonly mintRecipient: ToField<"address">; + + private constructor(typeArgs: [PhantomToTypeStr, ToTypeStr], fields: DepositForBurnTicketFields) { + this.$fullTypeName = composeSuiType(DepositForBurnTicket.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.auth = fields.auth; + this.coins = fields.coins; + this.destinationDomain = fields.destinationDomain; + this.mintRecipient = fields.mintRecipient; + } + + static reified, Auth extends Reified>( + T: T, + Auth: Auth + ): DepositForBurnTicketReified, ToTypeArgument> { + return { + typeName: DepositForBurnTicket.$typeName, + fullTypeName: composeSuiType(DepositForBurnTicket.$typeName, ...[extractType(T), extractType(Auth)]) as string, + typeArgs: [extractType(T), extractType(Auth)] as [ + PhantomToTypeStr>, + ToTypeStr>, + ], + isPhantom: DepositForBurnTicket.$isPhantom, + reifiedTypeArgs: [T, Auth], + fromFields: (fields: Record) => DepositForBurnTicket.fromFields([T, Auth], fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => DepositForBurnTicket.fromFieldsWithTypes([T, Auth], item), + fromBcs: (data: Uint8Array) => DepositForBurnTicket.fromBcs([T, Auth], data), + bcs: DepositForBurnTicket.bcs(toBcs(Auth)), + fromJSONField: (field: any) => DepositForBurnTicket.fromJSONField([T, Auth], field), + fromJSON: (json: Record) => DepositForBurnTicket.fromJSON([T, Auth], json), + fromSuiParsedData: (content: SuiParsedData) => DepositForBurnTicket.fromSuiParsedData([T, Auth], content), + fromSuiObjectData: (content: SuiObjectData) => DepositForBurnTicket.fromSuiObjectData([T, Auth], content), + fetch: async (client: SuiClient, id: string) => DepositForBurnTicket.fetch(client, [T, Auth], id), + new: (fields: DepositForBurnTicketFields, ToTypeArgument>) => { + return new DepositForBurnTicket([extractType(T), extractType(Auth)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return DepositForBurnTicket.reified; + } + + static phantom, Auth extends Reified>( + T: T, + Auth: Auth + ): PhantomReified, ToTypeArgument>>> { + return phantom(DepositForBurnTicket.reified(T, Auth)); + } + static get p() { + return DepositForBurnTicket.phantom; + } + + static get bcs() { + return >(Auth: Auth) => + bcs.struct(`DepositForBurnTicket<${Auth.name}>`, { + auth: Auth, + coins: Coin.bcs, + destination_domain: bcs.u32(), + mint_recipient: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + }); + } + + static fromFields, Auth extends Reified>( + typeArgs: [T, Auth], + fields: Record + ): DepositForBurnTicket, ToTypeArgument> { + return DepositForBurnTicket.reified(typeArgs[0], typeArgs[1]).new({ + auth: decodeFromFields(typeArgs[1], fields.auth), + coins: decodeFromFields(Coin.reified(typeArgs[0]), fields.coins), + destinationDomain: decodeFromFields("u32", fields.destination_domain), + mintRecipient: decodeFromFields("address", fields.mint_recipient), + }); + } + + static fromFieldsWithTypes, Auth extends Reified>( + typeArgs: [T, Auth], + item: FieldsWithTypes + ): DepositForBurnTicket, ToTypeArgument> { + if (!isDepositForBurnTicket(item.type)) { + throw new Error("not a DepositForBurnTicket type"); + } + assertFieldsWithTypesArgsMatch(item, typeArgs); + + return DepositForBurnTicket.reified(typeArgs[0], typeArgs[1]).new({ + auth: decodeFromFieldsWithTypes(typeArgs[1], item.fields.auth), + coins: decodeFromFieldsWithTypes(Coin.reified(typeArgs[0]), item.fields.coins), + destinationDomain: decodeFromFieldsWithTypes("u32", item.fields.destination_domain), + mintRecipient: decodeFromFieldsWithTypes("address", item.fields.mint_recipient), + }); + } + + static fromBcs, Auth extends Reified>( + typeArgs: [T, Auth], + data: Uint8Array + ): DepositForBurnTicket, ToTypeArgument> { + return DepositForBurnTicket.fromFields(typeArgs, DepositForBurnTicket.bcs(toBcs(typeArgs[1])).parse(data)); + } + + toJSONField() { + return { + auth: fieldToJSON(this.$typeArgs[1], this.auth), + coins: this.coins.toJSONField(), + destinationDomain: this.destinationDomain, + mintRecipient: this.mintRecipient, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField, Auth extends Reified>( + typeArgs: [T, Auth], + field: any + ): DepositForBurnTicket, ToTypeArgument> { + return DepositForBurnTicket.reified(typeArgs[0], typeArgs[1]).new({ + auth: decodeFromJSONField(typeArgs[1], field.auth), + coins: decodeFromJSONField(Coin.reified(typeArgs[0]), field.coins), + destinationDomain: decodeFromJSONField("u32", field.destinationDomain), + mintRecipient: decodeFromJSONField("address", field.mintRecipient), + }); + } + + static fromJSON, Auth extends Reified>( + typeArgs: [T, Auth], + json: Record + ): DepositForBurnTicket, ToTypeArgument> { + if (json.$typeName !== DepositForBurnTicket.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch( + composeSuiType(DepositForBurnTicket.$typeName, ...typeArgs.map(extractType)), + json.$typeArgs, + typeArgs + ); + + return DepositForBurnTicket.fromJSONField(typeArgs, json); + } + + static fromSuiParsedData, Auth extends Reified>( + typeArgs: [T, Auth], + content: SuiParsedData + ): DepositForBurnTicket, ToTypeArgument> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isDepositForBurnTicket(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a DepositForBurnTicket object`); + } + return DepositForBurnTicket.fromFieldsWithTypes(typeArgs, content); + } + + static fromSuiObjectData, Auth extends Reified>( + typeArgs: [T, Auth], + data: SuiObjectData + ): DepositForBurnTicket, ToTypeArgument> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isDepositForBurnTicket(data.bcs.type)) { + throw new Error(`object at is not a DepositForBurnTicket object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 2) { + throw new Error(`type argument mismatch: expected 2 type arguments but got ${gotTypeArgs.length}`); + } + for (let i = 0; i < 2; i++) { + const gotTypeArg = compressSuiType(gotTypeArgs[i]); + const expectedTypeArg = compressSuiType(extractType(typeArgs[i])); + if (gotTypeArg !== expectedTypeArg) { + throw new Error( + `type argument mismatch at position ${i}: expected '${expectedTypeArg}' but got '${gotTypeArg}'` + ); + } + } + + return DepositForBurnTicket.fromBcs(typeArgs, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return DepositForBurnTicket.fromSuiParsedData(typeArgs, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch, Auth extends Reified>( + client: SuiClient, + typeArgs: [T, Auth], + id: string + ): Promise, ToTypeArgument>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching DepositForBurnTicket object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isDepositForBurnTicket(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a DepositForBurnTicket object`); + } + + return DepositForBurnTicket.fromSuiObjectData(typeArgs, res.data); + } +} + +/* ============================== ReplaceDepositForBurnTicket =============================== */ + +export function isReplaceDepositForBurnTicket(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V1}::deposit_for_burn::ReplaceDepositForBurnTicket` + "<"); +} + +export interface ReplaceDepositForBurnTicketFields { + auth: ToField; + originalRawMessage: ToField>; + originalAttestation: ToField>; + newDestinationCaller: ToField>; + newMintRecipient: ToField>; +} + +export type ReplaceDepositForBurnTicketReified = Reified< + ReplaceDepositForBurnTicket, + ReplaceDepositForBurnTicketFields +>; + +export class ReplaceDepositForBurnTicket implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::deposit_for_burn::ReplaceDepositForBurnTicket`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [false] as const; + + readonly $typeName = ReplaceDepositForBurnTicket.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [ToTypeStr]; + readonly $isPhantom = ReplaceDepositForBurnTicket.$isPhantom; + + readonly auth: ToField; + readonly originalRawMessage: ToField>; + readonly originalAttestation: ToField>; + readonly newDestinationCaller: ToField>; + readonly newMintRecipient: ToField>; + + private constructor(typeArgs: [ToTypeStr], fields: ReplaceDepositForBurnTicketFields) { + this.$fullTypeName = composeSuiType(ReplaceDepositForBurnTicket.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.auth = fields.auth; + this.originalRawMessage = fields.originalRawMessage; + this.originalAttestation = fields.originalAttestation; + this.newDestinationCaller = fields.newDestinationCaller; + this.newMintRecipient = fields.newMintRecipient; + } + + static reified>( + Auth: Auth + ): ReplaceDepositForBurnTicketReified> { + return { + typeName: ReplaceDepositForBurnTicket.$typeName, + fullTypeName: composeSuiType(ReplaceDepositForBurnTicket.$typeName, ...[extractType(Auth)]) as string, + typeArgs: [extractType(Auth)] as [ToTypeStr>], + isPhantom: ReplaceDepositForBurnTicket.$isPhantom, + reifiedTypeArgs: [Auth], + fromFields: (fields: Record) => ReplaceDepositForBurnTicket.fromFields(Auth, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => ReplaceDepositForBurnTicket.fromFieldsWithTypes(Auth, item), + fromBcs: (data: Uint8Array) => ReplaceDepositForBurnTicket.fromBcs(Auth, data), + bcs: ReplaceDepositForBurnTicket.bcs(toBcs(Auth)), + fromJSONField: (field: any) => ReplaceDepositForBurnTicket.fromJSONField(Auth, field), + fromJSON: (json: Record) => ReplaceDepositForBurnTicket.fromJSON(Auth, json), + fromSuiParsedData: (content: SuiParsedData) => ReplaceDepositForBurnTicket.fromSuiParsedData(Auth, content), + fromSuiObjectData: (content: SuiObjectData) => ReplaceDepositForBurnTicket.fromSuiObjectData(Auth, content), + fetch: async (client: SuiClient, id: string) => ReplaceDepositForBurnTicket.fetch(client, Auth, id), + new: (fields: ReplaceDepositForBurnTicketFields>) => { + return new ReplaceDepositForBurnTicket([extractType(Auth)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return ReplaceDepositForBurnTicket.reified; + } + + static phantom>( + Auth: Auth + ): PhantomReified>>> { + return phantom(ReplaceDepositForBurnTicket.reified(Auth)); + } + static get p() { + return ReplaceDepositForBurnTicket.phantom; + } + + static get bcs() { + return >(Auth: Auth) => + bcs.struct(`ReplaceDepositForBurnTicket<${Auth.name}>`, { + auth: Auth, + original_raw_message: bcs.vector(bcs.u8()), + original_attestation: bcs.vector(bcs.u8()), + new_destination_caller: Option.bcs( + bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }) + ), + new_mint_recipient: Option.bcs( + bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }) + ), + }); + } + + static fromFields>( + typeArg: Auth, + fields: Record + ): ReplaceDepositForBurnTicket> { + return ReplaceDepositForBurnTicket.reified(typeArg).new({ + auth: decodeFromFields(typeArg, fields.auth), + originalRawMessage: decodeFromFields(reified.vector("u8"), fields.original_raw_message), + originalAttestation: decodeFromFields(reified.vector("u8"), fields.original_attestation), + newDestinationCaller: decodeFromFields(Option.reified("address"), fields.new_destination_caller), + newMintRecipient: decodeFromFields(Option.reified("address"), fields.new_mint_recipient), + }); + } + + static fromFieldsWithTypes>( + typeArg: Auth, + item: FieldsWithTypes + ): ReplaceDepositForBurnTicket> { + if (!isReplaceDepositForBurnTicket(item.type)) { + throw new Error("not a ReplaceDepositForBurnTicket type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return ReplaceDepositForBurnTicket.reified(typeArg).new({ + auth: decodeFromFieldsWithTypes(typeArg, item.fields.auth), + originalRawMessage: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.original_raw_message), + originalAttestation: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.original_attestation), + newDestinationCaller: decodeFromFieldsWithTypes(Option.reified("address"), item.fields.new_destination_caller), + newMintRecipient: decodeFromFieldsWithTypes(Option.reified("address"), item.fields.new_mint_recipient), + }); + } + + static fromBcs>( + typeArg: Auth, + data: Uint8Array + ): ReplaceDepositForBurnTicket> { + const typeArgs = [typeArg]; + + return ReplaceDepositForBurnTicket.fromFields( + typeArg, + ReplaceDepositForBurnTicket.bcs(toBcs(typeArgs[0])).parse(data) + ); + } + + toJSONField() { + return { + auth: fieldToJSON(this.$typeArgs[0], this.auth), + originalRawMessage: fieldToJSON>(`vector`, this.originalRawMessage), + originalAttestation: fieldToJSON>(`vector`, this.originalAttestation), + newDestinationCaller: fieldToJSON>(`${Option.$typeName}
`, this.newDestinationCaller), + newMintRecipient: fieldToJSON>(`${Option.$typeName}
`, this.newMintRecipient), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: Auth, + field: any + ): ReplaceDepositForBurnTicket> { + return ReplaceDepositForBurnTicket.reified(typeArg).new({ + auth: decodeFromJSONField(typeArg, field.auth), + originalRawMessage: decodeFromJSONField(reified.vector("u8"), field.originalRawMessage), + originalAttestation: decodeFromJSONField(reified.vector("u8"), field.originalAttestation), + newDestinationCaller: decodeFromJSONField(Option.reified("address"), field.newDestinationCaller), + newMintRecipient: decodeFromJSONField(Option.reified("address"), field.newMintRecipient), + }); + } + + static fromJSON>( + typeArg: Auth, + json: Record + ): ReplaceDepositForBurnTicket> { + if (json.$typeName !== ReplaceDepositForBurnTicket.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch( + composeSuiType(ReplaceDepositForBurnTicket.$typeName, extractType(typeArg)), + json.$typeArgs, + [typeArg] + ); + + return ReplaceDepositForBurnTicket.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: Auth, + content: SuiParsedData + ): ReplaceDepositForBurnTicket> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isReplaceDepositForBurnTicket(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a ReplaceDepositForBurnTicket object`); + } + return ReplaceDepositForBurnTicket.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: Auth, + data: SuiObjectData + ): ReplaceDepositForBurnTicket> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isReplaceDepositForBurnTicket(data.bcs.type)) { + throw new Error(`object at is not a ReplaceDepositForBurnTicket object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return ReplaceDepositForBurnTicket.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return ReplaceDepositForBurnTicket.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: Auth, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching ReplaceDepositForBurnTicket object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isReplaceDepositForBurnTicket(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a ReplaceDepositForBurnTicket object`); + } + + return ReplaceDepositForBurnTicket.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/handle-receive-message/structs.ts b/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/handle-receive-message/structs.ts new file mode 100644 index 00000000..0b61585e --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/handle-receive-message/structs.ts @@ -0,0 +1,203 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { StampReceiptTicket } from "../../0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/receive-message/structs"; +import { BurnMessage } from "../burn-message/structs"; +import { PKG_V1 } from "../index"; +import { MessageTransmitterAuthenticator } from "../message-transmitter-authenticator/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== StampReceiptTicketWithBurnMessage =============================== */ + +export function isStampReceiptTicketWithBurnMessage(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::handle_receive_message::StampReceiptTicketWithBurnMessage`; +} + +export interface StampReceiptTicketWithBurnMessageFields { + stampReceiptTicket: ToField>; + burnMessage: ToField; +} + +export type StampReceiptTicketWithBurnMessageReified = Reified< + StampReceiptTicketWithBurnMessage, + StampReceiptTicketWithBurnMessageFields +>; + +export class StampReceiptTicketWithBurnMessage implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::handle_receive_message::StampReceiptTicketWithBurnMessage`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = StampReceiptTicketWithBurnMessage.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = StampReceiptTicketWithBurnMessage.$isPhantom; + + readonly stampReceiptTicket: ToField>; + readonly burnMessage: ToField; + + private constructor(typeArgs: [], fields: StampReceiptTicketWithBurnMessageFields) { + this.$fullTypeName = composeSuiType(StampReceiptTicketWithBurnMessage.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.stampReceiptTicket = fields.stampReceiptTicket; + this.burnMessage = fields.burnMessage; + } + + static reified(): StampReceiptTicketWithBurnMessageReified { + return { + typeName: StampReceiptTicketWithBurnMessage.$typeName, + fullTypeName: composeSuiType(StampReceiptTicketWithBurnMessage.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: StampReceiptTicketWithBurnMessage.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => StampReceiptTicketWithBurnMessage.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => StampReceiptTicketWithBurnMessage.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => StampReceiptTicketWithBurnMessage.fromBcs(data), + bcs: StampReceiptTicketWithBurnMessage.bcs, + fromJSONField: (field: any) => StampReceiptTicketWithBurnMessage.fromJSONField(field), + fromJSON: (json: Record) => StampReceiptTicketWithBurnMessage.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => StampReceiptTicketWithBurnMessage.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => StampReceiptTicketWithBurnMessage.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => StampReceiptTicketWithBurnMessage.fetch(client, id), + new: (fields: StampReceiptTicketWithBurnMessageFields) => { + return new StampReceiptTicketWithBurnMessage([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return StampReceiptTicketWithBurnMessage.reified(); + } + + static phantom(): PhantomReified> { + return phantom(StampReceiptTicketWithBurnMessage.reified()); + } + static get p() { + return StampReceiptTicketWithBurnMessage.phantom(); + } + + static get bcs() { + return bcs.struct("StampReceiptTicketWithBurnMessage", { + stamp_receipt_ticket: StampReceiptTicket.bcs(MessageTransmitterAuthenticator.bcs), + burn_message: BurnMessage.bcs, + }); + } + + static fromFields(fields: Record): StampReceiptTicketWithBurnMessage { + return StampReceiptTicketWithBurnMessage.reified().new({ + stampReceiptTicket: decodeFromFields( + StampReceiptTicket.reified(MessageTransmitterAuthenticator.reified()), + fields.stamp_receipt_ticket + ), + burnMessage: decodeFromFields(BurnMessage.reified(), fields.burn_message), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): StampReceiptTicketWithBurnMessage { + if (!isStampReceiptTicketWithBurnMessage(item.type)) { + throw new Error("not a StampReceiptTicketWithBurnMessage type"); + } + + return StampReceiptTicketWithBurnMessage.reified().new({ + stampReceiptTicket: decodeFromFieldsWithTypes( + StampReceiptTicket.reified(MessageTransmitterAuthenticator.reified()), + item.fields.stamp_receipt_ticket + ), + burnMessage: decodeFromFieldsWithTypes(BurnMessage.reified(), item.fields.burn_message), + }); + } + + static fromBcs(data: Uint8Array): StampReceiptTicketWithBurnMessage { + return StampReceiptTicketWithBurnMessage.fromFields(StampReceiptTicketWithBurnMessage.bcs.parse(data)); + } + + toJSONField() { + return { + stampReceiptTicket: this.stampReceiptTicket.toJSONField(), + burnMessage: this.burnMessage.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): StampReceiptTicketWithBurnMessage { + return StampReceiptTicketWithBurnMessage.reified().new({ + stampReceiptTicket: decodeFromJSONField( + StampReceiptTicket.reified(MessageTransmitterAuthenticator.reified()), + field.stampReceiptTicket + ), + burnMessage: decodeFromJSONField(BurnMessage.reified(), field.burnMessage), + }); + } + + static fromJSON(json: Record): StampReceiptTicketWithBurnMessage { + if (json.$typeName !== StampReceiptTicketWithBurnMessage.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return StampReceiptTicketWithBurnMessage.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): StampReceiptTicketWithBurnMessage { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isStampReceiptTicketWithBurnMessage(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a StampReceiptTicketWithBurnMessage object`); + } + return StampReceiptTicketWithBurnMessage.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): StampReceiptTicketWithBurnMessage { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isStampReceiptTicketWithBurnMessage(data.bcs.type)) { + throw new Error(`object at is not a StampReceiptTicketWithBurnMessage object`); + } + + return StampReceiptTicketWithBurnMessage.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return StampReceiptTicketWithBurnMessage.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching StampReceiptTicketWithBurnMessage object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isStampReceiptTicketWithBurnMessage(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a StampReceiptTicketWithBurnMessage object`); + } + + return StampReceiptTicketWithBurnMessage.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/index.ts b/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/index.ts new file mode 100644 index 00000000..d3f275b0 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/index.ts @@ -0,0 +1,4 @@ +// @ts-nocheck +export const PACKAGE_ID = "0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb"; +export const PUBLISHED_AT = "0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb"; +export const PKG_V1 = "0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb"; diff --git a/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/init.ts b/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/init.ts new file mode 100644 index 00000000..8e71fd23 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/init.ts @@ -0,0 +1,16 @@ +// @ts-nocheck +import * as burnMessage from "./burn-message/structs"; +import * as depositForBurn from "./deposit-for-burn/structs"; +import * as handleReceiveMessage from "./handle-receive-message/structs"; +import * as messageTransmitterAuthenticator from "./message-transmitter-authenticator/structs"; +import * as state from "./state/structs"; +import { StructClassLoader } from "../../../_framework/loader"; + +export function registerClasses(loader: StructClassLoader) { + loader.register(state.State); + loader.register(burnMessage.BurnMessage); + loader.register(depositForBurn.DepositForBurnTicket); + loader.register(depositForBurn.ReplaceDepositForBurnTicket); + loader.register(messageTransmitterAuthenticator.MessageTransmitterAuthenticator); + loader.register(handleReceiveMessage.StampReceiptTicketWithBurnMessage); +} diff --git a/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/message-transmitter-authenticator/structs.ts b/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/message-transmitter-authenticator/structs.ts new file mode 100644 index 00000000..dd83f059 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/message-transmitter-authenticator/structs.ts @@ -0,0 +1,183 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== MessageTransmitterAuthenticator =============================== */ + +export function isMessageTransmitterAuthenticator(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::message_transmitter_authenticator::MessageTransmitterAuthenticator`; +} + +export interface MessageTransmitterAuthenticatorFields { + dummyField: ToField<"bool">; +} + +export type MessageTransmitterAuthenticatorReified = Reified< + MessageTransmitterAuthenticator, + MessageTransmitterAuthenticatorFields +>; + +export class MessageTransmitterAuthenticator implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::message_transmitter_authenticator::MessageTransmitterAuthenticator`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = MessageTransmitterAuthenticator.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = MessageTransmitterAuthenticator.$isPhantom; + + readonly dummyField: ToField<"bool">; + + private constructor(typeArgs: [], fields: MessageTransmitterAuthenticatorFields) { + this.$fullTypeName = composeSuiType(MessageTransmitterAuthenticator.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.dummyField = fields.dummyField; + } + + static reified(): MessageTransmitterAuthenticatorReified { + return { + typeName: MessageTransmitterAuthenticator.$typeName, + fullTypeName: composeSuiType(MessageTransmitterAuthenticator.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: MessageTransmitterAuthenticator.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => MessageTransmitterAuthenticator.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => MessageTransmitterAuthenticator.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => MessageTransmitterAuthenticator.fromBcs(data), + bcs: MessageTransmitterAuthenticator.bcs, + fromJSONField: (field: any) => MessageTransmitterAuthenticator.fromJSONField(field), + fromJSON: (json: Record) => MessageTransmitterAuthenticator.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => MessageTransmitterAuthenticator.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => MessageTransmitterAuthenticator.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => MessageTransmitterAuthenticator.fetch(client, id), + new: (fields: MessageTransmitterAuthenticatorFields) => { + return new MessageTransmitterAuthenticator([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return MessageTransmitterAuthenticator.reified(); + } + + static phantom(): PhantomReified> { + return phantom(MessageTransmitterAuthenticator.reified()); + } + static get p() { + return MessageTransmitterAuthenticator.phantom(); + } + + static get bcs() { + return bcs.struct("MessageTransmitterAuthenticator", { + dummy_field: bcs.bool(), + }); + } + + static fromFields(fields: Record): MessageTransmitterAuthenticator { + return MessageTransmitterAuthenticator.reified().new({ + dummyField: decodeFromFields("bool", fields.dummy_field), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): MessageTransmitterAuthenticator { + if (!isMessageTransmitterAuthenticator(item.type)) { + throw new Error("not a MessageTransmitterAuthenticator type"); + } + + return MessageTransmitterAuthenticator.reified().new({ + dummyField: decodeFromFieldsWithTypes("bool", item.fields.dummy_field), + }); + } + + static fromBcs(data: Uint8Array): MessageTransmitterAuthenticator { + return MessageTransmitterAuthenticator.fromFields(MessageTransmitterAuthenticator.bcs.parse(data)); + } + + toJSONField() { + return { + dummyField: this.dummyField, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): MessageTransmitterAuthenticator { + return MessageTransmitterAuthenticator.reified().new({ + dummyField: decodeFromJSONField("bool", field.dummyField), + }); + } + + static fromJSON(json: Record): MessageTransmitterAuthenticator { + if (json.$typeName !== MessageTransmitterAuthenticator.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return MessageTransmitterAuthenticator.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): MessageTransmitterAuthenticator { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isMessageTransmitterAuthenticator(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a MessageTransmitterAuthenticator object`); + } + return MessageTransmitterAuthenticator.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): MessageTransmitterAuthenticator { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isMessageTransmitterAuthenticator(data.bcs.type)) { + throw new Error(`object at is not a MessageTransmitterAuthenticator object`); + } + + return MessageTransmitterAuthenticator.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return MessageTransmitterAuthenticator.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching MessageTransmitterAuthenticator object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isMessageTransmitterAuthenticator(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a MessageTransmitterAuthenticator object`); + } + + return MessageTransmitterAuthenticator.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/state/structs.ts b/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/state/structs.ts new file mode 100644 index 00000000..737bec06 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/state/structs.ts @@ -0,0 +1,268 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { Bag } from "../../../../sui/bag/structs"; +import { UID } from "../../../../sui/object/structs"; +import { Table } from "../../../../sui/table/structs"; +import { VecSet } from "../../../../sui/vec-set/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== State =============================== */ + +export function isState(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::state::State`; +} + +export interface StateFields { + id: ToField; + messageBodyVersion: ToField<"u32">; + remoteTokenMessengers: ToField>; + burnLimitsPerMessage: ToField>; + remoteTokensToLocalTokens: ToField>; + mintCaps: ToField; + paused: ToField<"bool">; + compatibleVersions: ToField>; +} + +export type StateReified = Reified; + +export class State implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::state::State`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = State.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = State.$isPhantom; + + readonly id: ToField; + readonly messageBodyVersion: ToField<"u32">; + readonly remoteTokenMessengers: ToField>; + readonly burnLimitsPerMessage: ToField>; + readonly remoteTokensToLocalTokens: ToField>; + readonly mintCaps: ToField; + readonly paused: ToField<"bool">; + readonly compatibleVersions: ToField>; + + private constructor(typeArgs: [], fields: StateFields) { + this.$fullTypeName = composeSuiType(State.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.messageBodyVersion = fields.messageBodyVersion; + this.remoteTokenMessengers = fields.remoteTokenMessengers; + this.burnLimitsPerMessage = fields.burnLimitsPerMessage; + this.remoteTokensToLocalTokens = fields.remoteTokensToLocalTokens; + this.mintCaps = fields.mintCaps; + this.paused = fields.paused; + this.compatibleVersions = fields.compatibleVersions; + } + + static reified(): StateReified { + return { + typeName: State.$typeName, + fullTypeName: composeSuiType(State.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: State.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => State.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => State.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => State.fromBcs(data), + bcs: State.bcs, + fromJSONField: (field: any) => State.fromJSONField(field), + fromJSON: (json: Record) => State.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => State.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => State.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => State.fetch(client, id), + new: (fields: StateFields) => { + return new State([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return State.reified(); + } + + static phantom(): PhantomReified> { + return phantom(State.reified()); + } + static get p() { + return State.phantom(); + } + + static get bcs() { + return bcs.struct("State", { + id: UID.bcs, + message_body_version: bcs.u32(), + remote_token_messengers: Table.bcs, + burn_limits_per_message: Table.bcs, + remote_tokens_to_local_tokens: Table.bcs, + mint_caps: Bag.bcs, + paused: bcs.bool(), + compatible_versions: VecSet.bcs(bcs.u64()), + }); + } + + static fromFields(fields: Record): State { + return State.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + messageBodyVersion: decodeFromFields("u32", fields.message_body_version), + remoteTokenMessengers: decodeFromFields( + Table.reified(reified.phantom("u32"), reified.phantom("address")), + fields.remote_token_messengers + ), + burnLimitsPerMessage: decodeFromFields( + Table.reified(reified.phantom("address"), reified.phantom("u64")), + fields.burn_limits_per_message + ), + remoteTokensToLocalTokens: decodeFromFields( + Table.reified(reified.phantom("address"), reified.phantom("address")), + fields.remote_tokens_to_local_tokens + ), + mintCaps: decodeFromFields(Bag.reified(), fields.mint_caps), + paused: decodeFromFields("bool", fields.paused), + compatibleVersions: decodeFromFields(VecSet.reified("u64"), fields.compatible_versions), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): State { + if (!isState(item.type)) { + throw new Error("not a State type"); + } + + return State.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + messageBodyVersion: decodeFromFieldsWithTypes("u32", item.fields.message_body_version), + remoteTokenMessengers: decodeFromFieldsWithTypes( + Table.reified(reified.phantom("u32"), reified.phantom("address")), + item.fields.remote_token_messengers + ), + burnLimitsPerMessage: decodeFromFieldsWithTypes( + Table.reified(reified.phantom("address"), reified.phantom("u64")), + item.fields.burn_limits_per_message + ), + remoteTokensToLocalTokens: decodeFromFieldsWithTypes( + Table.reified(reified.phantom("address"), reified.phantom("address")), + item.fields.remote_tokens_to_local_tokens + ), + mintCaps: decodeFromFieldsWithTypes(Bag.reified(), item.fields.mint_caps), + paused: decodeFromFieldsWithTypes("bool", item.fields.paused), + compatibleVersions: decodeFromFieldsWithTypes(VecSet.reified("u64"), item.fields.compatible_versions), + }); + } + + static fromBcs(data: Uint8Array): State { + return State.fromFields(State.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + messageBodyVersion: this.messageBodyVersion, + remoteTokenMessengers: this.remoteTokenMessengers.toJSONField(), + burnLimitsPerMessage: this.burnLimitsPerMessage.toJSONField(), + remoteTokensToLocalTokens: this.remoteTokensToLocalTokens.toJSONField(), + mintCaps: this.mintCaps.toJSONField(), + paused: this.paused, + compatibleVersions: this.compatibleVersions.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): State { + return State.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + messageBodyVersion: decodeFromJSONField("u32", field.messageBodyVersion), + remoteTokenMessengers: decodeFromJSONField( + Table.reified(reified.phantom("u32"), reified.phantom("address")), + field.remoteTokenMessengers + ), + burnLimitsPerMessage: decodeFromJSONField( + Table.reified(reified.phantom("address"), reified.phantom("u64")), + field.burnLimitsPerMessage + ), + remoteTokensToLocalTokens: decodeFromJSONField( + Table.reified(reified.phantom("address"), reified.phantom("address")), + field.remoteTokensToLocalTokens + ), + mintCaps: decodeFromJSONField(Bag.reified(), field.mintCaps), + paused: decodeFromJSONField("bool", field.paused), + compatibleVersions: decodeFromJSONField(VecSet.reified("u64"), field.compatibleVersions), + }); + } + + static fromJSON(json: Record): State { + if (json.$typeName !== State.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return State.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): State { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isState(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a State object`); + } + return State.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): State { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isState(data.bcs.type)) { + throw new Error(`object at is not a State object`); + } + + return State.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return State.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching State object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isState(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a State object`); + } + + return State.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917/index.ts b/src/services/models/sui/_dependencies/source/0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917/index.ts new file mode 100644 index 00000000..66d91b85 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917/index.ts @@ -0,0 +1,4 @@ +// @ts-nocheck +export const PACKAGE_ID = "0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917"; +export const PUBLISHED_AT = "0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917"; +export const PKG_V1 = "0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917"; diff --git a/src/services/models/sui/_dependencies/source/0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917/init.ts b/src/services/models/sui/_dependencies/source/0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917/init.ts new file mode 100644 index 00000000..ba46d664 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917/init.ts @@ -0,0 +1,12 @@ +// @ts-nocheck +import * as mintAllowance from "./mint-allowance/structs"; +import * as treasury from "./treasury/structs"; +import { StructClassLoader } from "../../../_framework/loader"; + +export function registerClasses(loader: StructClassLoader) { + loader.register(mintAllowance.MintAllowance); + loader.register(treasury.Burn); + loader.register(treasury.MintCap); + loader.register(treasury.Treasury); + loader.register(treasury.TreasuryCapKey); +} diff --git a/src/services/models/sui/_dependencies/source/0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917/mint-allowance/structs.ts b/src/services/models/sui/_dependencies/source/0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917/mint-allowance/structs.ts new file mode 100644 index 00000000..40117e38 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917/mint-allowance/structs.ts @@ -0,0 +1,227 @@ +// @ts-nocheck +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../../../_framework/util"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== MintAllowance =============================== */ + +export function isMintAllowance(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V1}::mint_allowance::MintAllowance` + "<"); +} + +export interface MintAllowanceFields { + value: ToField<"u64">; +} + +export type MintAllowanceReified = Reified, MintAllowanceFields>; + +export class MintAllowance implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::mint_allowance::MintAllowance`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = MintAllowance.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = MintAllowance.$isPhantom; + + readonly value: ToField<"u64">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: MintAllowanceFields) { + this.$fullTypeName = composeSuiType(MintAllowance.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.value = fields.value; + } + + static reified>(T: T): MintAllowanceReified> { + return { + typeName: MintAllowance.$typeName, + fullTypeName: composeSuiType(MintAllowance.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: MintAllowance.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => MintAllowance.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => MintAllowance.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => MintAllowance.fromBcs(T, data), + bcs: MintAllowance.bcs, + fromJSONField: (field: any) => MintAllowance.fromJSONField(T, field), + fromJSON: (json: Record) => MintAllowance.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => MintAllowance.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => MintAllowance.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => MintAllowance.fetch(client, T, id), + new: (fields: MintAllowanceFields>) => { + return new MintAllowance([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return MintAllowance.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(MintAllowance.reified(T)); + } + static get p() { + return MintAllowance.phantom; + } + + static get bcs() { + return bcs.struct("MintAllowance", { + value: bcs.u64(), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): MintAllowance> { + return MintAllowance.reified(typeArg).new({ + value: decodeFromFields("u64", fields.value), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): MintAllowance> { + if (!isMintAllowance(item.type)) { + throw new Error("not a MintAllowance type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return MintAllowance.reified(typeArg).new({ + value: decodeFromFieldsWithTypes("u64", item.fields.value), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): MintAllowance> { + return MintAllowance.fromFields(typeArg, MintAllowance.bcs.parse(data)); + } + + toJSONField() { + return { + value: this.value.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): MintAllowance> { + return MintAllowance.reified(typeArg).new({ + value: decodeFromJSONField("u64", field.value), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): MintAllowance> { + if (json.$typeName !== MintAllowance.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(MintAllowance.$typeName, extractType(typeArg)), json.$typeArgs, [ + typeArg, + ]); + + return MintAllowance.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): MintAllowance> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isMintAllowance(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a MintAllowance object`); + } + return MintAllowance.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): MintAllowance> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isMintAllowance(data.bcs.type)) { + throw new Error(`object at is not a MintAllowance object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return MintAllowance.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return MintAllowance.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching MintAllowance object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isMintAllowance(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a MintAllowance object`); + } + + return MintAllowance.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917/treasury/structs.ts b/src/services/models/sui/_dependencies/source/0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917/treasury/structs.ts new file mode 100644 index 00000000..36287374 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917/treasury/structs.ts @@ -0,0 +1,848 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, + ToTypeStr as ToPhantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../../../_framework/util"; +import { ID, UID } from "../../../../sui/object/structs"; +import { Table } from "../../../../sui/table/structs"; +import { VecSet } from "../../../../sui/vec-set/structs"; +import { PKG_V1 } from "../index"; +import { MintAllowance } from "../mint-allowance/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Burn =============================== */ + +export function isBurn(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V1}::treasury::Burn` + "<"); +} + +export interface BurnFields { + mintCap: ToField; + amount: ToField<"u64">; +} + +export type BurnReified = Reified, BurnFields>; + +export class Burn implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::treasury::Burn`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = Burn.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = Burn.$isPhantom; + + readonly mintCap: ToField; + readonly amount: ToField<"u64">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: BurnFields) { + this.$fullTypeName = composeSuiType(Burn.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.mintCap = fields.mintCap; + this.amount = fields.amount; + } + + static reified>(T: T): BurnReified> { + return { + typeName: Burn.$typeName, + fullTypeName: composeSuiType(Burn.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: Burn.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => Burn.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Burn.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => Burn.fromBcs(T, data), + bcs: Burn.bcs, + fromJSONField: (field: any) => Burn.fromJSONField(T, field), + fromJSON: (json: Record) => Burn.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => Burn.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => Burn.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => Burn.fetch(client, T, id), + new: (fields: BurnFields>) => { + return new Burn([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Burn.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(Burn.reified(T)); + } + static get p() { + return Burn.phantom; + } + + static get bcs() { + return bcs.struct("Burn", { + mint_cap: ID.bcs, + amount: bcs.u64(), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): Burn> { + return Burn.reified(typeArg).new({ + mintCap: decodeFromFields(ID.reified(), fields.mint_cap), + amount: decodeFromFields("u64", fields.amount), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): Burn> { + if (!isBurn(item.type)) { + throw new Error("not a Burn type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Burn.reified(typeArg).new({ + mintCap: decodeFromFieldsWithTypes(ID.reified(), item.fields.mint_cap), + amount: decodeFromFieldsWithTypes("u64", item.fields.amount), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): Burn> { + return Burn.fromFields(typeArg, Burn.bcs.parse(data)); + } + + toJSONField() { + return { + mintCap: this.mintCap, + amount: this.amount.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): Burn> { + return Burn.reified(typeArg).new({ + mintCap: decodeFromJSONField(ID.reified(), field.mintCap), + amount: decodeFromJSONField("u64", field.amount), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): Burn> { + if (json.$typeName !== Burn.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Burn.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Burn.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): Burn> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isBurn(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Burn object`); + } + return Burn.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): Burn> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isBurn(data.bcs.type)) { + throw new Error(`object at is not a Burn object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Burn.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Burn.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Burn object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isBurn(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Burn object`); + } + + return Burn.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== MintCap =============================== */ + +export function isMintCap(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V1}::treasury::MintCap` + "<"); +} + +export interface MintCapFields { + id: ToField; +} + +export type MintCapReified = Reified, MintCapFields>; + +export class MintCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::treasury::MintCap`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = MintCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = MintCap.$isPhantom; + + readonly id: ToField; + + private constructor(typeArgs: [PhantomToTypeStr], fields: MintCapFields) { + this.$fullTypeName = composeSuiType(MintCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified>(T: T): MintCapReified> { + return { + typeName: MintCap.$typeName, + fullTypeName: composeSuiType(MintCap.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: MintCap.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => MintCap.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => MintCap.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => MintCap.fromBcs(T, data), + bcs: MintCap.bcs, + fromJSONField: (field: any) => MintCap.fromJSONField(T, field), + fromJSON: (json: Record) => MintCap.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => MintCap.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => MintCap.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => MintCap.fetch(client, T, id), + new: (fields: MintCapFields>) => { + return new MintCap([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return MintCap.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(MintCap.reified(T)); + } + static get p() { + return MintCap.phantom; + } + + static get bcs() { + return bcs.struct("MintCap", { + id: UID.bcs, + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): MintCap> { + return MintCap.reified(typeArg).new({ + id: decodeFromFields(UID.reified(), fields.id), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): MintCap> { + if (!isMintCap(item.type)) { + throw new Error("not a MintCap type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return MintCap.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): MintCap> { + return MintCap.fromFields(typeArg, MintCap.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): MintCap> { + return MintCap.reified(typeArg).new({ + id: decodeFromJSONField(UID.reified(), field.id), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): MintCap> { + if (json.$typeName !== MintCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(MintCap.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return MintCap.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): MintCap> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isMintCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a MintCap object`); + } + return MintCap.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): MintCap> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isMintCap(data.bcs.type)) { + throw new Error(`object at is not a MintCap object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return MintCap.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return MintCap.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching MintCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isMintCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a MintCap object`); + } + + return MintCap.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== Treasury =============================== */ + +export function isTreasury(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V1}::treasury::Treasury` + "<"); +} + +export interface TreasuryFields { + id: ToField; + controllers: ToField>>; + mintAllowances: ToField, ToPhantom>>>; + compatibleVersions: ToField>; +} + +export type TreasuryReified = Reified, TreasuryFields>; + +export class Treasury implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::treasury::Treasury`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = Treasury.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = Treasury.$isPhantom; + + readonly id: ToField; + readonly controllers: ToField>>; + readonly mintAllowances: ToField, ToPhantom>>>; + readonly compatibleVersions: ToField>; + + private constructor(typeArgs: [PhantomToTypeStr], fields: TreasuryFields) { + this.$fullTypeName = composeSuiType(Treasury.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.controllers = fields.controllers; + this.mintAllowances = fields.mintAllowances; + this.compatibleVersions = fields.compatibleVersions; + } + + static reified>(T: T): TreasuryReified> { + return { + typeName: Treasury.$typeName, + fullTypeName: composeSuiType(Treasury.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: Treasury.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => Treasury.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Treasury.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => Treasury.fromBcs(T, data), + bcs: Treasury.bcs, + fromJSONField: (field: any) => Treasury.fromJSONField(T, field), + fromJSON: (json: Record) => Treasury.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => Treasury.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => Treasury.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => Treasury.fetch(client, T, id), + new: (fields: TreasuryFields>) => { + return new Treasury([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Treasury.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(Treasury.reified(T)); + } + static get p() { + return Treasury.phantom; + } + + static get bcs() { + return bcs.struct("Treasury", { + id: UID.bcs, + controllers: Table.bcs, + mint_allowances: Table.bcs, + compatible_versions: VecSet.bcs(bcs.u64()), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): Treasury> { + return Treasury.reified(typeArg).new({ + id: decodeFromFields(UID.reified(), fields.id), + controllers: decodeFromFields( + Table.reified(reified.phantom("address"), reified.phantom(ID.reified())), + fields.controllers + ), + mintAllowances: decodeFromFields( + Table.reified(reified.phantom(ID.reified()), reified.phantom(MintAllowance.reified(typeArg))), + fields.mint_allowances + ), + compatibleVersions: decodeFromFields(VecSet.reified("u64"), fields.compatible_versions), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): Treasury> { + if (!isTreasury(item.type)) { + throw new Error("not a Treasury type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Treasury.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + controllers: decodeFromFieldsWithTypes( + Table.reified(reified.phantom("address"), reified.phantom(ID.reified())), + item.fields.controllers + ), + mintAllowances: decodeFromFieldsWithTypes( + Table.reified(reified.phantom(ID.reified()), reified.phantom(MintAllowance.reified(typeArg))), + item.fields.mint_allowances + ), + compatibleVersions: decodeFromFieldsWithTypes(VecSet.reified("u64"), item.fields.compatible_versions), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): Treasury> { + return Treasury.fromFields(typeArg, Treasury.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + controllers: this.controllers.toJSONField(), + mintAllowances: this.mintAllowances.toJSONField(), + compatibleVersions: this.compatibleVersions.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): Treasury> { + return Treasury.reified(typeArg).new({ + id: decodeFromJSONField(UID.reified(), field.id), + controllers: decodeFromJSONField( + Table.reified(reified.phantom("address"), reified.phantom(ID.reified())), + field.controllers + ), + mintAllowances: decodeFromJSONField( + Table.reified(reified.phantom(ID.reified()), reified.phantom(MintAllowance.reified(typeArg))), + field.mintAllowances + ), + compatibleVersions: decodeFromJSONField(VecSet.reified("u64"), field.compatibleVersions), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): Treasury> { + if (json.$typeName !== Treasury.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Treasury.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Treasury.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): Treasury> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTreasury(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Treasury object`); + } + return Treasury.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): Treasury> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTreasury(data.bcs.type)) { + throw new Error(`object at is not a Treasury object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Treasury.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Treasury.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Treasury object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTreasury(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Treasury object`); + } + + return Treasury.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== TreasuryCapKey =============================== */ + +export function isTreasuryCapKey(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::treasury::TreasuryCapKey`; +} + +export interface TreasuryCapKeyFields { + dummyField: ToField<"bool">; +} + +export type TreasuryCapKeyReified = Reified; + +export class TreasuryCapKey implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::treasury::TreasuryCapKey`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = TreasuryCapKey.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = TreasuryCapKey.$isPhantom; + + readonly dummyField: ToField<"bool">; + + private constructor(typeArgs: [], fields: TreasuryCapKeyFields) { + this.$fullTypeName = composeSuiType(TreasuryCapKey.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.dummyField = fields.dummyField; + } + + static reified(): TreasuryCapKeyReified { + return { + typeName: TreasuryCapKey.$typeName, + fullTypeName: composeSuiType(TreasuryCapKey.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: TreasuryCapKey.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => TreasuryCapKey.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => TreasuryCapKey.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => TreasuryCapKey.fromBcs(data), + bcs: TreasuryCapKey.bcs, + fromJSONField: (field: any) => TreasuryCapKey.fromJSONField(field), + fromJSON: (json: Record) => TreasuryCapKey.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => TreasuryCapKey.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => TreasuryCapKey.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => TreasuryCapKey.fetch(client, id), + new: (fields: TreasuryCapKeyFields) => { + return new TreasuryCapKey([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return TreasuryCapKey.reified(); + } + + static phantom(): PhantomReified> { + return phantom(TreasuryCapKey.reified()); + } + static get p() { + return TreasuryCapKey.phantom(); + } + + static get bcs() { + return bcs.struct("TreasuryCapKey", { + dummy_field: bcs.bool(), + }); + } + + static fromFields(fields: Record): TreasuryCapKey { + return TreasuryCapKey.reified().new({ + dummyField: decodeFromFields("bool", fields.dummy_field), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): TreasuryCapKey { + if (!isTreasuryCapKey(item.type)) { + throw new Error("not a TreasuryCapKey type"); + } + + return TreasuryCapKey.reified().new({ + dummyField: decodeFromFieldsWithTypes("bool", item.fields.dummy_field), + }); + } + + static fromBcs(data: Uint8Array): TreasuryCapKey { + return TreasuryCapKey.fromFields(TreasuryCapKey.bcs.parse(data)); + } + + toJSONField() { + return { + dummyField: this.dummyField, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): TreasuryCapKey { + return TreasuryCapKey.reified().new({ + dummyField: decodeFromJSONField("bool", field.dummyField), + }); + } + + static fromJSON(json: Record): TreasuryCapKey { + if (json.$typeName !== TreasuryCapKey.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return TreasuryCapKey.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): TreasuryCapKey { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTreasuryCapKey(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a TreasuryCapKey object`); + } + return TreasuryCapKey.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): TreasuryCapKey { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTreasuryCapKey(data.bcs.type)) { + throw new Error(`object at is not a TreasuryCapKey object`); + } + + return TreasuryCapKey.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return TreasuryCapKey.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching TreasuryCapKey object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTreasuryCapKey(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a TreasuryCapKey object`); + } + + return TreasuryCapKey.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/index.ts b/src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/index.ts new file mode 100644 index 00000000..d97cfbc9 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/index.ts @@ -0,0 +1,4 @@ +// @ts-nocheck +export const PACKAGE_ID = "0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5"; +export const PUBLISHED_AT = "0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5"; +export const PKG_V1 = "0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5"; diff --git a/src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/init.ts b/src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/init.ts new file mode 100644 index 00000000..e88241c4 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/init.ts @@ -0,0 +1,13 @@ +// @ts-nocheck +import * as message from "./message/structs"; +import * as receiveMessage from "./receive-message/structs"; +import * as state from "./state/structs"; +import { StructClassLoader } from "../../../_framework/loader"; + +export function registerClasses(loader: StructClassLoader) { + loader.register(state.State); + loader.register(message.Message); + loader.register(receiveMessage.Receipt); + loader.register(receiveMessage.StampReceiptTicket); + loader.register(receiveMessage.StampedReceipt); +} diff --git a/src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/message/structs.ts b/src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/message/structs.ts new file mode 100644 index 00000000..32fef660 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/message/structs.ts @@ -0,0 +1,248 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { Vector } from "../../../../_framework/vector"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64, fromHEX, toHEX } from "@mysten/sui/utils"; + +/* ============================== Message =============================== */ + +export function isMessage(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::message::Message`; +} + +export interface MessageFields { + version: ToField<"u32">; + sourceDomain: ToField<"u32">; + destinationDomain: ToField<"u32">; + nonce: ToField<"u64">; + sender: ToField<"address">; + recipient: ToField<"address">; + destinationCaller: ToField<"address">; + messageBody: ToField>; +} + +export type MessageReified = Reified; + +export class Message implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::message::Message`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Message.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Message.$isPhantom; + + readonly version: ToField<"u32">; + readonly sourceDomain: ToField<"u32">; + readonly destinationDomain: ToField<"u32">; + readonly nonce: ToField<"u64">; + readonly sender: ToField<"address">; + readonly recipient: ToField<"address">; + readonly destinationCaller: ToField<"address">; + readonly messageBody: ToField>; + + private constructor(typeArgs: [], fields: MessageFields) { + this.$fullTypeName = composeSuiType(Message.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.version = fields.version; + this.sourceDomain = fields.sourceDomain; + this.destinationDomain = fields.destinationDomain; + this.nonce = fields.nonce; + this.sender = fields.sender; + this.recipient = fields.recipient; + this.destinationCaller = fields.destinationCaller; + this.messageBody = fields.messageBody; + } + + static reified(): MessageReified { + return { + typeName: Message.$typeName, + fullTypeName: composeSuiType(Message.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Message.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Message.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Message.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Message.fromBcs(data), + bcs: Message.bcs, + fromJSONField: (field: any) => Message.fromJSONField(field), + fromJSON: (json: Record) => Message.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Message.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Message.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Message.fetch(client, id), + new: (fields: MessageFields) => { + return new Message([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Message.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Message.reified()); + } + static get p() { + return Message.phantom(); + } + + static get bcs() { + return bcs.struct("Message", { + version: bcs.u32(), + source_domain: bcs.u32(), + destination_domain: bcs.u32(), + nonce: bcs.u64(), + sender: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + recipient: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + destination_caller: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + message_body: bcs.vector(bcs.u8()), + }); + } + + static fromFields(fields: Record): Message { + return Message.reified().new({ + version: decodeFromFields("u32", fields.version), + sourceDomain: decodeFromFields("u32", fields.source_domain), + destinationDomain: decodeFromFields("u32", fields.destination_domain), + nonce: decodeFromFields("u64", fields.nonce), + sender: decodeFromFields("address", fields.sender), + recipient: decodeFromFields("address", fields.recipient), + destinationCaller: decodeFromFields("address", fields.destination_caller), + messageBody: decodeFromFields(reified.vector("u8"), fields.message_body), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Message { + if (!isMessage(item.type)) { + throw new Error("not a Message type"); + } + + return Message.reified().new({ + version: decodeFromFieldsWithTypes("u32", item.fields.version), + sourceDomain: decodeFromFieldsWithTypes("u32", item.fields.source_domain), + destinationDomain: decodeFromFieldsWithTypes("u32", item.fields.destination_domain), + nonce: decodeFromFieldsWithTypes("u64", item.fields.nonce), + sender: decodeFromFieldsWithTypes("address", item.fields.sender), + recipient: decodeFromFieldsWithTypes("address", item.fields.recipient), + destinationCaller: decodeFromFieldsWithTypes("address", item.fields.destination_caller), + messageBody: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.message_body), + }); + } + + static fromBcs(data: Uint8Array): Message { + return Message.fromFields(Message.bcs.parse(data)); + } + + toJSONField() { + return { + version: this.version, + sourceDomain: this.sourceDomain, + destinationDomain: this.destinationDomain, + nonce: this.nonce.toString(), + sender: this.sender, + recipient: this.recipient, + destinationCaller: this.destinationCaller, + messageBody: fieldToJSON>(`vector`, this.messageBody), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Message { + return Message.reified().new({ + version: decodeFromJSONField("u32", field.version), + sourceDomain: decodeFromJSONField("u32", field.sourceDomain), + destinationDomain: decodeFromJSONField("u32", field.destinationDomain), + nonce: decodeFromJSONField("u64", field.nonce), + sender: decodeFromJSONField("address", field.sender), + recipient: decodeFromJSONField("address", field.recipient), + destinationCaller: decodeFromJSONField("address", field.destinationCaller), + messageBody: decodeFromJSONField(reified.vector("u8"), field.messageBody), + }); + } + + static fromJSON(json: Record): Message { + if (json.$typeName !== Message.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Message.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Message { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isMessage(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Message object`); + } + return Message.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Message { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isMessage(data.bcs.type)) { + throw new Error(`object at is not a Message object`); + } + + return Message.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Message.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Message object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isMessage(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Message object`); + } + + return Message.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/receive-message/structs.ts b/src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/receive-message/structs.ts new file mode 100644 index 00000000..76e8a11e --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/receive-message/structs.ts @@ -0,0 +1,628 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeArgument, + ToTypeStr, + TypeArgument, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + fieldToJSON, + phantom, + toBcs, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../../../_framework/util"; +import { Vector } from "../../../../_framework/vector"; +import { VecSet } from "../../../../sui/vec-set/structs"; +import { PKG_V1 } from "../index"; +import { BcsType, bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64, fromHEX, toHEX } from "@mysten/sui/utils"; + +/* ============================== Receipt =============================== */ + +export function isReceipt(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::receive_message::Receipt`; +} + +export interface ReceiptFields { + caller: ToField<"address">; + recipient: ToField<"address">; + sourceDomain: ToField<"u32">; + sender: ToField<"address">; + nonce: ToField<"u64">; + messageBody: ToField>; + currentVersion: ToField>; +} + +export type ReceiptReified = Reified; + +export class Receipt implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::receive_message::Receipt`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Receipt.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Receipt.$isPhantom; + + readonly caller: ToField<"address">; + readonly recipient: ToField<"address">; + readonly sourceDomain: ToField<"u32">; + readonly sender: ToField<"address">; + readonly nonce: ToField<"u64">; + readonly messageBody: ToField>; + readonly currentVersion: ToField>; + + private constructor(typeArgs: [], fields: ReceiptFields) { + this.$fullTypeName = composeSuiType(Receipt.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.caller = fields.caller; + this.recipient = fields.recipient; + this.sourceDomain = fields.sourceDomain; + this.sender = fields.sender; + this.nonce = fields.nonce; + this.messageBody = fields.messageBody; + this.currentVersion = fields.currentVersion; + } + + static reified(): ReceiptReified { + return { + typeName: Receipt.$typeName, + fullTypeName: composeSuiType(Receipt.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Receipt.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Receipt.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Receipt.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Receipt.fromBcs(data), + bcs: Receipt.bcs, + fromJSONField: (field: any) => Receipt.fromJSONField(field), + fromJSON: (json: Record) => Receipt.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Receipt.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Receipt.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Receipt.fetch(client, id), + new: (fields: ReceiptFields) => { + return new Receipt([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Receipt.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Receipt.reified()); + } + static get p() { + return Receipt.phantom(); + } + + static get bcs() { + return bcs.struct("Receipt", { + caller: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + recipient: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + source_domain: bcs.u32(), + sender: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + nonce: bcs.u64(), + message_body: bcs.vector(bcs.u8()), + current_version: VecSet.bcs(bcs.u64()), + }); + } + + static fromFields(fields: Record): Receipt { + return Receipt.reified().new({ + caller: decodeFromFields("address", fields.caller), + recipient: decodeFromFields("address", fields.recipient), + sourceDomain: decodeFromFields("u32", fields.source_domain), + sender: decodeFromFields("address", fields.sender), + nonce: decodeFromFields("u64", fields.nonce), + messageBody: decodeFromFields(reified.vector("u8"), fields.message_body), + currentVersion: decodeFromFields(VecSet.reified("u64"), fields.current_version), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Receipt { + if (!isReceipt(item.type)) { + throw new Error("not a Receipt type"); + } + + return Receipt.reified().new({ + caller: decodeFromFieldsWithTypes("address", item.fields.caller), + recipient: decodeFromFieldsWithTypes("address", item.fields.recipient), + sourceDomain: decodeFromFieldsWithTypes("u32", item.fields.source_domain), + sender: decodeFromFieldsWithTypes("address", item.fields.sender), + nonce: decodeFromFieldsWithTypes("u64", item.fields.nonce), + messageBody: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.message_body), + currentVersion: decodeFromFieldsWithTypes(VecSet.reified("u64"), item.fields.current_version), + }); + } + + static fromBcs(data: Uint8Array): Receipt { + return Receipt.fromFields(Receipt.bcs.parse(data)); + } + + toJSONField() { + return { + caller: this.caller, + recipient: this.recipient, + sourceDomain: this.sourceDomain, + sender: this.sender, + nonce: this.nonce.toString(), + messageBody: fieldToJSON>(`vector`, this.messageBody), + currentVersion: this.currentVersion.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Receipt { + return Receipt.reified().new({ + caller: decodeFromJSONField("address", field.caller), + recipient: decodeFromJSONField("address", field.recipient), + sourceDomain: decodeFromJSONField("u32", field.sourceDomain), + sender: decodeFromJSONField("address", field.sender), + nonce: decodeFromJSONField("u64", field.nonce), + messageBody: decodeFromJSONField(reified.vector("u8"), field.messageBody), + currentVersion: decodeFromJSONField(VecSet.reified("u64"), field.currentVersion), + }); + } + + static fromJSON(json: Record): Receipt { + if (json.$typeName !== Receipt.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Receipt.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Receipt { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isReceipt(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Receipt object`); + } + return Receipt.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Receipt { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isReceipt(data.bcs.type)) { + throw new Error(`object at is not a Receipt object`); + } + + return Receipt.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Receipt.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Receipt object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isReceipt(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Receipt object`); + } + + return Receipt.fromSuiObjectData(res.data); + } +} + +/* ============================== StampReceiptTicket =============================== */ + +export function isStampReceiptTicket(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V1}::receive_message::StampReceiptTicket` + "<"); +} + +export interface StampReceiptTicketFields { + auth: ToField; + receipt: ToField; +} + +export type StampReceiptTicketReified = Reified< + StampReceiptTicket, + StampReceiptTicketFields +>; + +export class StampReceiptTicket implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::receive_message::StampReceiptTicket`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [false] as const; + + readonly $typeName = StampReceiptTicket.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [ToTypeStr]; + readonly $isPhantom = StampReceiptTicket.$isPhantom; + + readonly auth: ToField; + readonly receipt: ToField; + + private constructor(typeArgs: [ToTypeStr], fields: StampReceiptTicketFields) { + this.$fullTypeName = composeSuiType(StampReceiptTicket.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.auth = fields.auth; + this.receipt = fields.receipt; + } + + static reified>(Auth: Auth): StampReceiptTicketReified> { + return { + typeName: StampReceiptTicket.$typeName, + fullTypeName: composeSuiType(StampReceiptTicket.$typeName, ...[extractType(Auth)]) as string, + typeArgs: [extractType(Auth)] as [ToTypeStr>], + isPhantom: StampReceiptTicket.$isPhantom, + reifiedTypeArgs: [Auth], + fromFields: (fields: Record) => StampReceiptTicket.fromFields(Auth, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => StampReceiptTicket.fromFieldsWithTypes(Auth, item), + fromBcs: (data: Uint8Array) => StampReceiptTicket.fromBcs(Auth, data), + bcs: StampReceiptTicket.bcs(toBcs(Auth)), + fromJSONField: (field: any) => StampReceiptTicket.fromJSONField(Auth, field), + fromJSON: (json: Record) => StampReceiptTicket.fromJSON(Auth, json), + fromSuiParsedData: (content: SuiParsedData) => StampReceiptTicket.fromSuiParsedData(Auth, content), + fromSuiObjectData: (content: SuiObjectData) => StampReceiptTicket.fromSuiObjectData(Auth, content), + fetch: async (client: SuiClient, id: string) => StampReceiptTicket.fetch(client, Auth, id), + new: (fields: StampReceiptTicketFields>) => { + return new StampReceiptTicket([extractType(Auth)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return StampReceiptTicket.reified; + } + + static phantom>( + Auth: Auth + ): PhantomReified>>> { + return phantom(StampReceiptTicket.reified(Auth)); + } + static get p() { + return StampReceiptTicket.phantom; + } + + static get bcs() { + return >(Auth: Auth) => + bcs.struct(`StampReceiptTicket<${Auth.name}>`, { + auth: Auth, + receipt: Receipt.bcs, + }); + } + + static fromFields>( + typeArg: Auth, + fields: Record + ): StampReceiptTicket> { + return StampReceiptTicket.reified(typeArg).new({ + auth: decodeFromFields(typeArg, fields.auth), + receipt: decodeFromFields(Receipt.reified(), fields.receipt), + }); + } + + static fromFieldsWithTypes>( + typeArg: Auth, + item: FieldsWithTypes + ): StampReceiptTicket> { + if (!isStampReceiptTicket(item.type)) { + throw new Error("not a StampReceiptTicket type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return StampReceiptTicket.reified(typeArg).new({ + auth: decodeFromFieldsWithTypes(typeArg, item.fields.auth), + receipt: decodeFromFieldsWithTypes(Receipt.reified(), item.fields.receipt), + }); + } + + static fromBcs>( + typeArg: Auth, + data: Uint8Array + ): StampReceiptTicket> { + const typeArgs = [typeArg]; + + return StampReceiptTicket.fromFields(typeArg, StampReceiptTicket.bcs(toBcs(typeArgs[0])).parse(data)); + } + + toJSONField() { + return { + auth: fieldToJSON(this.$typeArgs[0], this.auth), + receipt: this.receipt.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: Auth, + field: any + ): StampReceiptTicket> { + return StampReceiptTicket.reified(typeArg).new({ + auth: decodeFromJSONField(typeArg, field.auth), + receipt: decodeFromJSONField(Receipt.reified(), field.receipt), + }); + } + + static fromJSON>( + typeArg: Auth, + json: Record + ): StampReceiptTicket> { + if (json.$typeName !== StampReceiptTicket.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(StampReceiptTicket.$typeName, extractType(typeArg)), json.$typeArgs, [ + typeArg, + ]); + + return StampReceiptTicket.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: Auth, + content: SuiParsedData + ): StampReceiptTicket> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isStampReceiptTicket(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a StampReceiptTicket object`); + } + return StampReceiptTicket.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: Auth, + data: SuiObjectData + ): StampReceiptTicket> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isStampReceiptTicket(data.bcs.type)) { + throw new Error(`object at is not a StampReceiptTicket object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return StampReceiptTicket.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return StampReceiptTicket.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: Auth, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching StampReceiptTicket object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isStampReceiptTicket(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a StampReceiptTicket object`); + } + + return StampReceiptTicket.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== StampedReceipt =============================== */ + +export function isStampedReceipt(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::receive_message::StampedReceipt`; +} + +export interface StampedReceiptFields { + receipt: ToField; +} + +export type StampedReceiptReified = Reified; + +export class StampedReceipt implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::receive_message::StampedReceipt`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = StampedReceipt.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = StampedReceipt.$isPhantom; + + readonly receipt: ToField; + + private constructor(typeArgs: [], fields: StampedReceiptFields) { + this.$fullTypeName = composeSuiType(StampedReceipt.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.receipt = fields.receipt; + } + + static reified(): StampedReceiptReified { + return { + typeName: StampedReceipt.$typeName, + fullTypeName: composeSuiType(StampedReceipt.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: StampedReceipt.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => StampedReceipt.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => StampedReceipt.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => StampedReceipt.fromBcs(data), + bcs: StampedReceipt.bcs, + fromJSONField: (field: any) => StampedReceipt.fromJSONField(field), + fromJSON: (json: Record) => StampedReceipt.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => StampedReceipt.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => StampedReceipt.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => StampedReceipt.fetch(client, id), + new: (fields: StampedReceiptFields) => { + return new StampedReceipt([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return StampedReceipt.reified(); + } + + static phantom(): PhantomReified> { + return phantom(StampedReceipt.reified()); + } + static get p() { + return StampedReceipt.phantom(); + } + + static get bcs() { + return bcs.struct("StampedReceipt", { + receipt: Receipt.bcs, + }); + } + + static fromFields(fields: Record): StampedReceipt { + return StampedReceipt.reified().new({ + receipt: decodeFromFields(Receipt.reified(), fields.receipt), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): StampedReceipt { + if (!isStampedReceipt(item.type)) { + throw new Error("not a StampedReceipt type"); + } + + return StampedReceipt.reified().new({ + receipt: decodeFromFieldsWithTypes(Receipt.reified(), item.fields.receipt), + }); + } + + static fromBcs(data: Uint8Array): StampedReceipt { + return StampedReceipt.fromFields(StampedReceipt.bcs.parse(data)); + } + + toJSONField() { + return { + receipt: this.receipt.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): StampedReceipt { + return StampedReceipt.reified().new({ + receipt: decodeFromJSONField(Receipt.reified(), field.receipt), + }); + } + + static fromJSON(json: Record): StampedReceipt { + if (json.$typeName !== StampedReceipt.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return StampedReceipt.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): StampedReceipt { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isStampedReceipt(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a StampedReceipt object`); + } + return StampedReceipt.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): StampedReceipt { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isStampedReceipt(data.bcs.type)) { + throw new Error(`object at is not a StampedReceipt object`); + } + + return StampedReceipt.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return StampedReceipt.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching StampedReceipt object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isStampedReceipt(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a StampedReceipt object`); + } + + return StampedReceipt.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/state/structs.ts b/src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/state/structs.ts new file mode 100644 index 00000000..03a29727 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/state/structs.ts @@ -0,0 +1,270 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { UID } from "../../../../sui/object/structs"; +import { Table } from "../../../../sui/table/structs"; +import { VecSet } from "../../../../sui/vec-set/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64, fromHEX, toHEX } from "@mysten/sui/utils"; + +/* ============================== State =============================== */ + +export function isState(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::state::State`; +} + +export interface StateFields { + id: ToField; + localDomain: ToField<"u32">; + messageVersion: ToField<"u32">; + maxMessageBodySize: ToField<"u64">; + enabledAttesters: ToField>; + nextAvailableNonce: ToField<"u64">; + usedNonces: ToField>; + signatureThreshold: ToField<"u64">; + paused: ToField<"bool">; + compatibleVersions: ToField>; +} + +export type StateReified = Reified; + +export class State implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::state::State`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = State.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = State.$isPhantom; + + readonly id: ToField; + readonly localDomain: ToField<"u32">; + readonly messageVersion: ToField<"u32">; + readonly maxMessageBodySize: ToField<"u64">; + readonly enabledAttesters: ToField>; + readonly nextAvailableNonce: ToField<"u64">; + readonly usedNonces: ToField>; + readonly signatureThreshold: ToField<"u64">; + readonly paused: ToField<"bool">; + readonly compatibleVersions: ToField>; + + private constructor(typeArgs: [], fields: StateFields) { + this.$fullTypeName = composeSuiType(State.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.localDomain = fields.localDomain; + this.messageVersion = fields.messageVersion; + this.maxMessageBodySize = fields.maxMessageBodySize; + this.enabledAttesters = fields.enabledAttesters; + this.nextAvailableNonce = fields.nextAvailableNonce; + this.usedNonces = fields.usedNonces; + this.signatureThreshold = fields.signatureThreshold; + this.paused = fields.paused; + this.compatibleVersions = fields.compatibleVersions; + } + + static reified(): StateReified { + return { + typeName: State.$typeName, + fullTypeName: composeSuiType(State.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: State.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => State.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => State.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => State.fromBcs(data), + bcs: State.bcs, + fromJSONField: (field: any) => State.fromJSONField(field), + fromJSON: (json: Record) => State.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => State.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => State.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => State.fetch(client, id), + new: (fields: StateFields) => { + return new State([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return State.reified(); + } + + static phantom(): PhantomReified> { + return phantom(State.reified()); + } + static get p() { + return State.phantom(); + } + + static get bcs() { + return bcs.struct("State", { + id: UID.bcs, + local_domain: bcs.u32(), + message_version: bcs.u32(), + max_message_body_size: bcs.u64(), + enabled_attesters: VecSet.bcs( + bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }) + ), + next_available_nonce: bcs.u64(), + used_nonces: Table.bcs, + signature_threshold: bcs.u64(), + paused: bcs.bool(), + compatible_versions: VecSet.bcs(bcs.u64()), + }); + } + + static fromFields(fields: Record): State { + return State.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + localDomain: decodeFromFields("u32", fields.local_domain), + messageVersion: decodeFromFields("u32", fields.message_version), + maxMessageBodySize: decodeFromFields("u64", fields.max_message_body_size), + enabledAttesters: decodeFromFields(VecSet.reified("address"), fields.enabled_attesters), + nextAvailableNonce: decodeFromFields("u64", fields.next_available_nonce), + usedNonces: decodeFromFields( + Table.reified(reified.phantom("address"), reified.phantom("bool")), + fields.used_nonces + ), + signatureThreshold: decodeFromFields("u64", fields.signature_threshold), + paused: decodeFromFields("bool", fields.paused), + compatibleVersions: decodeFromFields(VecSet.reified("u64"), fields.compatible_versions), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): State { + if (!isState(item.type)) { + throw new Error("not a State type"); + } + + return State.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + localDomain: decodeFromFieldsWithTypes("u32", item.fields.local_domain), + messageVersion: decodeFromFieldsWithTypes("u32", item.fields.message_version), + maxMessageBodySize: decodeFromFieldsWithTypes("u64", item.fields.max_message_body_size), + enabledAttesters: decodeFromFieldsWithTypes(VecSet.reified("address"), item.fields.enabled_attesters), + nextAvailableNonce: decodeFromFieldsWithTypes("u64", item.fields.next_available_nonce), + usedNonces: decodeFromFieldsWithTypes( + Table.reified(reified.phantom("address"), reified.phantom("bool")), + item.fields.used_nonces + ), + signatureThreshold: decodeFromFieldsWithTypes("u64", item.fields.signature_threshold), + paused: decodeFromFieldsWithTypes("bool", item.fields.paused), + compatibleVersions: decodeFromFieldsWithTypes(VecSet.reified("u64"), item.fields.compatible_versions), + }); + } + + static fromBcs(data: Uint8Array): State { + return State.fromFields(State.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + localDomain: this.localDomain, + messageVersion: this.messageVersion, + maxMessageBodySize: this.maxMessageBodySize.toString(), + enabledAttesters: this.enabledAttesters.toJSONField(), + nextAvailableNonce: this.nextAvailableNonce.toString(), + usedNonces: this.usedNonces.toJSONField(), + signatureThreshold: this.signatureThreshold.toString(), + paused: this.paused, + compatibleVersions: this.compatibleVersions.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): State { + return State.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + localDomain: decodeFromJSONField("u32", field.localDomain), + messageVersion: decodeFromJSONField("u32", field.messageVersion), + maxMessageBodySize: decodeFromJSONField("u64", field.maxMessageBodySize), + enabledAttesters: decodeFromJSONField(VecSet.reified("address"), field.enabledAttesters), + nextAvailableNonce: decodeFromJSONField("u64", field.nextAvailableNonce), + usedNonces: decodeFromJSONField( + Table.reified(reified.phantom("address"), reified.phantom("bool")), + field.usedNonces + ), + signatureThreshold: decodeFromJSONField("u64", field.signatureThreshold), + paused: decodeFromJSONField("bool", field.paused), + compatibleVersions: decodeFromJSONField(VecSet.reified("u64"), field.compatibleVersions), + }); + } + + static fromJSON(json: Record): State { + if (json.$typeName !== State.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return State.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): State { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isState(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a State object`); + } + return State.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): State { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isState(data.bcs.type)) { + throw new Error(`object at is not a State object`); + } + + return State.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return State.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching State object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isState(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a State object`); + } + + return State.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/bytes20/structs.ts b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/bytes20/structs.ts new file mode 100644 index 00000000..c8f3796f --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/bytes20/structs.ts @@ -0,0 +1,183 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { Vector } from "../../../../_framework/vector"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Bytes20 =============================== */ + +export function isBytes20(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::bytes20::Bytes20`; +} + +export interface Bytes20Fields { + data: ToField>; +} + +export type Bytes20Reified = Reified; + +export class Bytes20 implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::bytes20::Bytes20`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Bytes20.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Bytes20.$isPhantom; + + readonly data: ToField>; + + private constructor(typeArgs: [], fields: Bytes20Fields) { + this.$fullTypeName = composeSuiType(Bytes20.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.data = fields.data; + } + + static reified(): Bytes20Reified { + return { + typeName: Bytes20.$typeName, + fullTypeName: composeSuiType(Bytes20.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Bytes20.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Bytes20.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Bytes20.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Bytes20.fromBcs(data), + bcs: Bytes20.bcs, + fromJSONField: (field: any) => Bytes20.fromJSONField(field), + fromJSON: (json: Record) => Bytes20.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Bytes20.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Bytes20.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Bytes20.fetch(client, id), + new: (fields: Bytes20Fields) => { + return new Bytes20([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Bytes20.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Bytes20.reified()); + } + static get p() { + return Bytes20.phantom(); + } + + static get bcs() { + return bcs.struct("Bytes20", { + data: bcs.vector(bcs.u8()), + }); + } + + static fromFields(fields: Record): Bytes20 { + return Bytes20.reified().new({ + data: decodeFromFields(reified.vector("u8"), fields.data), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Bytes20 { + if (!isBytes20(item.type)) { + throw new Error("not a Bytes20 type"); + } + + return Bytes20.reified().new({ + data: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.data), + }); + } + + static fromBcs(data: Uint8Array): Bytes20 { + return Bytes20.fromFields(Bytes20.bcs.parse(data)); + } + + toJSONField() { + return { + data: fieldToJSON>(`vector`, this.data), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Bytes20 { + return Bytes20.reified().new({ + data: decodeFromJSONField(reified.vector("u8"), field.data), + }); + } + + static fromJSON(json: Record): Bytes20 { + if (json.$typeName !== Bytes20.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Bytes20.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Bytes20 { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isBytes20(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Bytes20 object`); + } + return Bytes20.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Bytes20 { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isBytes20(data.bcs.type)) { + throw new Error(`object at is not a Bytes20 object`); + } + + return Bytes20.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Bytes20.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Bytes20 object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isBytes20(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Bytes20 object`); + } + + return Bytes20.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/bytes32/structs.ts b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/bytes32/structs.ts new file mode 100644 index 00000000..d01176a4 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/bytes32/structs.ts @@ -0,0 +1,183 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { Vector } from "../../../../_framework/vector"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Bytes32 =============================== */ + +export function isBytes32(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::bytes32::Bytes32`; +} + +export interface Bytes32Fields { + data: ToField>; +} + +export type Bytes32Reified = Reified; + +export class Bytes32 implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::bytes32::Bytes32`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Bytes32.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Bytes32.$isPhantom; + + readonly data: ToField>; + + private constructor(typeArgs: [], fields: Bytes32Fields) { + this.$fullTypeName = composeSuiType(Bytes32.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.data = fields.data; + } + + static reified(): Bytes32Reified { + return { + typeName: Bytes32.$typeName, + fullTypeName: composeSuiType(Bytes32.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Bytes32.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Bytes32.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Bytes32.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Bytes32.fromBcs(data), + bcs: Bytes32.bcs, + fromJSONField: (field: any) => Bytes32.fromJSONField(field), + fromJSON: (json: Record) => Bytes32.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Bytes32.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Bytes32.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Bytes32.fetch(client, id), + new: (fields: Bytes32Fields) => { + return new Bytes32([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Bytes32.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Bytes32.reified()); + } + static get p() { + return Bytes32.phantom(); + } + + static get bcs() { + return bcs.struct("Bytes32", { + data: bcs.vector(bcs.u8()), + }); + } + + static fromFields(fields: Record): Bytes32 { + return Bytes32.reified().new({ + data: decodeFromFields(reified.vector("u8"), fields.data), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Bytes32 { + if (!isBytes32(item.type)) { + throw new Error("not a Bytes32 type"); + } + + return Bytes32.reified().new({ + data: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.data), + }); + } + + static fromBcs(data: Uint8Array): Bytes32 { + return Bytes32.fromFields(Bytes32.bcs.parse(data)); + } + + toJSONField() { + return { + data: fieldToJSON>(`vector`, this.data), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Bytes32 { + return Bytes32.reified().new({ + data: decodeFromJSONField(reified.vector("u8"), field.data), + }); + } + + static fromJSON(json: Record): Bytes32 { + if (json.$typeName !== Bytes32.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Bytes32.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Bytes32 { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isBytes32(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Bytes32 object`); + } + return Bytes32.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Bytes32 { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isBytes32(data.bcs.type)) { + throw new Error(`object at is not a Bytes32 object`); + } + + return Bytes32.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Bytes32.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Bytes32 object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isBytes32(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Bytes32 object`); + } + + return Bytes32.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/consumed-vaas/structs.ts b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/consumed-vaas/structs.ts new file mode 100644 index 00000000..5ba2bdb7 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/consumed-vaas/structs.ts @@ -0,0 +1,184 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, + ToTypeStr as ToPhantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { Bytes32 } from "../bytes32/structs"; +import { PKG_V1 } from "../index"; +import { Set } from "../set/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== ConsumedVAAs =============================== */ + +export function isConsumedVAAs(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::consumed_vaas::ConsumedVAAs`; +} + +export interface ConsumedVAAsFields { + hashes: ToField>>; +} + +export type ConsumedVAAsReified = Reified; + +export class ConsumedVAAs implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::consumed_vaas::ConsumedVAAs`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = ConsumedVAAs.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = ConsumedVAAs.$isPhantom; + + readonly hashes: ToField>>; + + private constructor(typeArgs: [], fields: ConsumedVAAsFields) { + this.$fullTypeName = composeSuiType(ConsumedVAAs.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.hashes = fields.hashes; + } + + static reified(): ConsumedVAAsReified { + return { + typeName: ConsumedVAAs.$typeName, + fullTypeName: composeSuiType(ConsumedVAAs.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: ConsumedVAAs.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => ConsumedVAAs.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => ConsumedVAAs.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => ConsumedVAAs.fromBcs(data), + bcs: ConsumedVAAs.bcs, + fromJSONField: (field: any) => ConsumedVAAs.fromJSONField(field), + fromJSON: (json: Record) => ConsumedVAAs.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => ConsumedVAAs.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => ConsumedVAAs.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => ConsumedVAAs.fetch(client, id), + new: (fields: ConsumedVAAsFields) => { + return new ConsumedVAAs([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return ConsumedVAAs.reified(); + } + + static phantom(): PhantomReified> { + return phantom(ConsumedVAAs.reified()); + } + static get p() { + return ConsumedVAAs.phantom(); + } + + static get bcs() { + return bcs.struct("ConsumedVAAs", { + hashes: Set.bcs, + }); + } + + static fromFields(fields: Record): ConsumedVAAs { + return ConsumedVAAs.reified().new({ + hashes: decodeFromFields(Set.reified(reified.phantom(Bytes32.reified())), fields.hashes), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): ConsumedVAAs { + if (!isConsumedVAAs(item.type)) { + throw new Error("not a ConsumedVAAs type"); + } + + return ConsumedVAAs.reified().new({ + hashes: decodeFromFieldsWithTypes(Set.reified(reified.phantom(Bytes32.reified())), item.fields.hashes), + }); + } + + static fromBcs(data: Uint8Array): ConsumedVAAs { + return ConsumedVAAs.fromFields(ConsumedVAAs.bcs.parse(data)); + } + + toJSONField() { + return { + hashes: this.hashes.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): ConsumedVAAs { + return ConsumedVAAs.reified().new({ + hashes: decodeFromJSONField(Set.reified(reified.phantom(Bytes32.reified())), field.hashes), + }); + } + + static fromJSON(json: Record): ConsumedVAAs { + if (json.$typeName !== ConsumedVAAs.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return ConsumedVAAs.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): ConsumedVAAs { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isConsumedVAAs(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a ConsumedVAAs object`); + } + return ConsumedVAAs.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): ConsumedVAAs { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isConsumedVAAs(data.bcs.type)) { + throw new Error(`object at is not a ConsumedVAAs object`); + } + + return ConsumedVAAs.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return ConsumedVAAs.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching ConsumedVAAs object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isConsumedVAAs(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a ConsumedVAAs object`); + } + + return ConsumedVAAs.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/cursor/structs.ts b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/cursor/structs.ts new file mode 100644 index 00000000..561874da --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/cursor/structs.ts @@ -0,0 +1,223 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeArgument, + ToTypeStr, + TypeArgument, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + fieldToJSON, + phantom, + toBcs, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../../../_framework/util"; +import { Vector } from "../../../../_framework/vector"; +import { PKG_V1 } from "../index"; +import { BcsType, bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Cursor =============================== */ + +export function isCursor(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V1}::cursor::Cursor` + "<"); +} + +export interface CursorFields { + data: ToField>; +} + +export type CursorReified = Reified, CursorFields>; + +export class Cursor implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::cursor::Cursor`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [false] as const; + + readonly $typeName = Cursor.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [ToTypeStr]; + readonly $isPhantom = Cursor.$isPhantom; + + readonly data: ToField>; + + private constructor(typeArgs: [ToTypeStr], fields: CursorFields) { + this.$fullTypeName = composeSuiType(Cursor.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.data = fields.data; + } + + static reified>(T: T): CursorReified> { + return { + typeName: Cursor.$typeName, + fullTypeName: composeSuiType(Cursor.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [ToTypeStr>], + isPhantom: Cursor.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => Cursor.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Cursor.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => Cursor.fromBcs(T, data), + bcs: Cursor.bcs(toBcs(T)), + fromJSONField: (field: any) => Cursor.fromJSONField(T, field), + fromJSON: (json: Record) => Cursor.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => Cursor.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => Cursor.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => Cursor.fetch(client, T, id), + new: (fields: CursorFields>) => { + return new Cursor([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Cursor.reified; + } + + static phantom>(T: T): PhantomReified>>> { + return phantom(Cursor.reified(T)); + } + static get p() { + return Cursor.phantom; + } + + static get bcs() { + return >(T: T) => + bcs.struct(`Cursor<${T.name}>`, { + data: bcs.vector(T), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): Cursor> { + return Cursor.reified(typeArg).new({ + data: decodeFromFields(reified.vector(typeArg), fields.data), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): Cursor> { + if (!isCursor(item.type)) { + throw new Error("not a Cursor type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Cursor.reified(typeArg).new({ + data: decodeFromFieldsWithTypes(reified.vector(typeArg), item.fields.data), + }); + } + + static fromBcs>(typeArg: T, data: Uint8Array): Cursor> { + const typeArgs = [typeArg]; + + return Cursor.fromFields(typeArg, Cursor.bcs(toBcs(typeArgs[0])).parse(data)); + } + + toJSONField() { + return { + data: fieldToJSON>(`vector<${this.$typeArgs[0]}>`, this.data), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>(typeArg: T, field: any): Cursor> { + return Cursor.reified(typeArg).new({ + data: decodeFromJSONField(reified.vector(typeArg), field.data), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): Cursor> { + if (json.$typeName !== Cursor.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Cursor.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Cursor.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): Cursor> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isCursor(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Cursor object`); + } + return Cursor.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): Cursor> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isCursor(data.bcs.type)) { + throw new Error(`object at is not a Cursor object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Cursor.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Cursor.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Cursor object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isCursor(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Cursor object`); + } + + return Cursor.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/emitter/structs.ts b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/emitter/structs.ts new file mode 100644 index 00000000..39bc73ee --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/emitter/structs.ts @@ -0,0 +1,352 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { ID, UID } from "../../../../sui/object/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== EmitterCap =============================== */ + +export function isEmitterCap(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::emitter::EmitterCap`; +} + +export interface EmitterCapFields { + id: ToField; + sequence: ToField<"u64">; +} + +export type EmitterCapReified = Reified; + +export class EmitterCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::emitter::EmitterCap`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = EmitterCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = EmitterCap.$isPhantom; + + readonly id: ToField; + readonly sequence: ToField<"u64">; + + private constructor(typeArgs: [], fields: EmitterCapFields) { + this.$fullTypeName = composeSuiType(EmitterCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.sequence = fields.sequence; + } + + static reified(): EmitterCapReified { + return { + typeName: EmitterCap.$typeName, + fullTypeName: composeSuiType(EmitterCap.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: EmitterCap.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => EmitterCap.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => EmitterCap.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => EmitterCap.fromBcs(data), + bcs: EmitterCap.bcs, + fromJSONField: (field: any) => EmitterCap.fromJSONField(field), + fromJSON: (json: Record) => EmitterCap.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => EmitterCap.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => EmitterCap.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => EmitterCap.fetch(client, id), + new: (fields: EmitterCapFields) => { + return new EmitterCap([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return EmitterCap.reified(); + } + + static phantom(): PhantomReified> { + return phantom(EmitterCap.reified()); + } + static get p() { + return EmitterCap.phantom(); + } + + static get bcs() { + return bcs.struct("EmitterCap", { + id: UID.bcs, + sequence: bcs.u64(), + }); + } + + static fromFields(fields: Record): EmitterCap { + return EmitterCap.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + sequence: decodeFromFields("u64", fields.sequence), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): EmitterCap { + if (!isEmitterCap(item.type)) { + throw new Error("not a EmitterCap type"); + } + + return EmitterCap.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + sequence: decodeFromFieldsWithTypes("u64", item.fields.sequence), + }); + } + + static fromBcs(data: Uint8Array): EmitterCap { + return EmitterCap.fromFields(EmitterCap.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + sequence: this.sequence.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): EmitterCap { + return EmitterCap.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + sequence: decodeFromJSONField("u64", field.sequence), + }); + } + + static fromJSON(json: Record): EmitterCap { + if (json.$typeName !== EmitterCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return EmitterCap.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): EmitterCap { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isEmitterCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a EmitterCap object`); + } + return EmitterCap.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): EmitterCap { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isEmitterCap(data.bcs.type)) { + throw new Error(`object at is not a EmitterCap object`); + } + + return EmitterCap.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return EmitterCap.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching EmitterCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isEmitterCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a EmitterCap object`); + } + + return EmitterCap.fromSuiObjectData(res.data); + } +} + +/* ============================== EmitterCreated =============================== */ + +export function isEmitterCreated(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::emitter::EmitterCreated`; +} + +export interface EmitterCreatedFields { + emitterCap: ToField; +} + +export type EmitterCreatedReified = Reified; + +export class EmitterCreated implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::emitter::EmitterCreated`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = EmitterCreated.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = EmitterCreated.$isPhantom; + + readonly emitterCap: ToField; + + private constructor(typeArgs: [], fields: EmitterCreatedFields) { + this.$fullTypeName = composeSuiType(EmitterCreated.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.emitterCap = fields.emitterCap; + } + + static reified(): EmitterCreatedReified { + return { + typeName: EmitterCreated.$typeName, + fullTypeName: composeSuiType(EmitterCreated.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: EmitterCreated.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => EmitterCreated.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => EmitterCreated.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => EmitterCreated.fromBcs(data), + bcs: EmitterCreated.bcs, + fromJSONField: (field: any) => EmitterCreated.fromJSONField(field), + fromJSON: (json: Record) => EmitterCreated.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => EmitterCreated.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => EmitterCreated.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => EmitterCreated.fetch(client, id), + new: (fields: EmitterCreatedFields) => { + return new EmitterCreated([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return EmitterCreated.reified(); + } + + static phantom(): PhantomReified> { + return phantom(EmitterCreated.reified()); + } + static get p() { + return EmitterCreated.phantom(); + } + + static get bcs() { + return bcs.struct("EmitterCreated", { + emitter_cap: ID.bcs, + }); + } + + static fromFields(fields: Record): EmitterCreated { + return EmitterCreated.reified().new({ + emitterCap: decodeFromFields(ID.reified(), fields.emitter_cap), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): EmitterCreated { + if (!isEmitterCreated(item.type)) { + throw new Error("not a EmitterCreated type"); + } + + return EmitterCreated.reified().new({ + emitterCap: decodeFromFieldsWithTypes(ID.reified(), item.fields.emitter_cap), + }); + } + + static fromBcs(data: Uint8Array): EmitterCreated { + return EmitterCreated.fromFields(EmitterCreated.bcs.parse(data)); + } + + toJSONField() { + return { + emitterCap: this.emitterCap, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): EmitterCreated { + return EmitterCreated.reified().new({ + emitterCap: decodeFromJSONField(ID.reified(), field.emitterCap), + }); + } + + static fromJSON(json: Record): EmitterCreated { + if (json.$typeName !== EmitterCreated.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return EmitterCreated.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): EmitterCreated { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isEmitterCreated(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a EmitterCreated object`); + } + return EmitterCreated.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): EmitterCreated { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isEmitterCreated(data.bcs.type)) { + throw new Error(`object at is not a EmitterCreated object`); + } + + return EmitterCreated.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return EmitterCreated.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching EmitterCreated object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isEmitterCreated(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a EmitterCreated object`); + } + + return EmitterCreated.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/external-address/structs.ts b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/external-address/structs.ts new file mode 100644 index 00000000..6b9fd98e --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/external-address/structs.ts @@ -0,0 +1,181 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { Bytes32 } from "../bytes32/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== ExternalAddress =============================== */ + +export function isExternalAddress(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::external_address::ExternalAddress`; +} + +export interface ExternalAddressFields { + value: ToField; +} + +export type ExternalAddressReified = Reified; + +export class ExternalAddress implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::external_address::ExternalAddress`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = ExternalAddress.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = ExternalAddress.$isPhantom; + + readonly value: ToField; + + private constructor(typeArgs: [], fields: ExternalAddressFields) { + this.$fullTypeName = composeSuiType(ExternalAddress.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.value = fields.value; + } + + static reified(): ExternalAddressReified { + return { + typeName: ExternalAddress.$typeName, + fullTypeName: composeSuiType(ExternalAddress.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: ExternalAddress.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => ExternalAddress.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => ExternalAddress.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => ExternalAddress.fromBcs(data), + bcs: ExternalAddress.bcs, + fromJSONField: (field: any) => ExternalAddress.fromJSONField(field), + fromJSON: (json: Record) => ExternalAddress.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => ExternalAddress.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => ExternalAddress.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => ExternalAddress.fetch(client, id), + new: (fields: ExternalAddressFields) => { + return new ExternalAddress([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return ExternalAddress.reified(); + } + + static phantom(): PhantomReified> { + return phantom(ExternalAddress.reified()); + } + static get p() { + return ExternalAddress.phantom(); + } + + static get bcs() { + return bcs.struct("ExternalAddress", { + value: Bytes32.bcs, + }); + } + + static fromFields(fields: Record): ExternalAddress { + return ExternalAddress.reified().new({ + value: decodeFromFields(Bytes32.reified(), fields.value), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): ExternalAddress { + if (!isExternalAddress(item.type)) { + throw new Error("not a ExternalAddress type"); + } + + return ExternalAddress.reified().new({ + value: decodeFromFieldsWithTypes(Bytes32.reified(), item.fields.value), + }); + } + + static fromBcs(data: Uint8Array): ExternalAddress { + return ExternalAddress.fromFields(ExternalAddress.bcs.parse(data)); + } + + toJSONField() { + return { + value: this.value.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): ExternalAddress { + return ExternalAddress.reified().new({ + value: decodeFromJSONField(Bytes32.reified(), field.value), + }); + } + + static fromJSON(json: Record): ExternalAddress { + if (json.$typeName !== ExternalAddress.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return ExternalAddress.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): ExternalAddress { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isExternalAddress(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a ExternalAddress object`); + } + return ExternalAddress.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): ExternalAddress { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isExternalAddress(data.bcs.type)) { + throw new Error(`object at is not a ExternalAddress object`); + } + + return ExternalAddress.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return ExternalAddress.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching ExternalAddress object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isExternalAddress(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a ExternalAddress object`); + } + + return ExternalAddress.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/fee-collector/structs.ts b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/fee-collector/structs.ts new file mode 100644 index 00000000..82808c8d --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/fee-collector/structs.ts @@ -0,0 +1,192 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, + ToTypeStr as ToPhantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { Balance } from "../../../../sui/balance/structs"; +import { SUI } from "../../../../sui/sui/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== FeeCollector =============================== */ + +export function isFeeCollector(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::fee_collector::FeeCollector`; +} + +export interface FeeCollectorFields { + feeAmount: ToField<"u64">; + balance: ToField>>; +} + +export type FeeCollectorReified = Reified; + +export class FeeCollector implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::fee_collector::FeeCollector`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = FeeCollector.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = FeeCollector.$isPhantom; + + readonly feeAmount: ToField<"u64">; + readonly balance: ToField>>; + + private constructor(typeArgs: [], fields: FeeCollectorFields) { + this.$fullTypeName = composeSuiType(FeeCollector.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.feeAmount = fields.feeAmount; + this.balance = fields.balance; + } + + static reified(): FeeCollectorReified { + return { + typeName: FeeCollector.$typeName, + fullTypeName: composeSuiType(FeeCollector.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: FeeCollector.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => FeeCollector.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => FeeCollector.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => FeeCollector.fromBcs(data), + bcs: FeeCollector.bcs, + fromJSONField: (field: any) => FeeCollector.fromJSONField(field), + fromJSON: (json: Record) => FeeCollector.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => FeeCollector.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => FeeCollector.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => FeeCollector.fetch(client, id), + new: (fields: FeeCollectorFields) => { + return new FeeCollector([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return FeeCollector.reified(); + } + + static phantom(): PhantomReified> { + return phantom(FeeCollector.reified()); + } + static get p() { + return FeeCollector.phantom(); + } + + static get bcs() { + return bcs.struct("FeeCollector", { + fee_amount: bcs.u64(), + balance: Balance.bcs, + }); + } + + static fromFields(fields: Record): FeeCollector { + return FeeCollector.reified().new({ + feeAmount: decodeFromFields("u64", fields.fee_amount), + balance: decodeFromFields(Balance.reified(reified.phantom(SUI.reified())), fields.balance), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): FeeCollector { + if (!isFeeCollector(item.type)) { + throw new Error("not a FeeCollector type"); + } + + return FeeCollector.reified().new({ + feeAmount: decodeFromFieldsWithTypes("u64", item.fields.fee_amount), + balance: decodeFromFieldsWithTypes(Balance.reified(reified.phantom(SUI.reified())), item.fields.balance), + }); + } + + static fromBcs(data: Uint8Array): FeeCollector { + return FeeCollector.fromFields(FeeCollector.bcs.parse(data)); + } + + toJSONField() { + return { + feeAmount: this.feeAmount.toString(), + balance: this.balance.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): FeeCollector { + return FeeCollector.reified().new({ + feeAmount: decodeFromJSONField("u64", field.feeAmount), + balance: decodeFromJSONField(Balance.reified(reified.phantom(SUI.reified())), field.balance), + }); + } + + static fromJSON(json: Record): FeeCollector { + if (json.$typeName !== FeeCollector.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return FeeCollector.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): FeeCollector { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isFeeCollector(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a FeeCollector object`); + } + return FeeCollector.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): FeeCollector { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isFeeCollector(data.bcs.type)) { + throw new Error(`object at is not a FeeCollector object`); + } + + return FeeCollector.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return FeeCollector.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching FeeCollector object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isFeeCollector(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a FeeCollector object`); + } + + return FeeCollector.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/guardian-set/structs.ts b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/guardian-set/structs.ts new file mode 100644 index 00000000..c0c37976 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/guardian-set/structs.ts @@ -0,0 +1,200 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { Vector } from "../../../../_framework/vector"; +import { Guardian } from "../guardian/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== GuardianSet =============================== */ + +export function isGuardianSet(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::guardian_set::GuardianSet`; +} + +export interface GuardianSetFields { + index: ToField<"u32">; + guardians: ToField>; + expirationTimestampMs: ToField<"u64">; +} + +export type GuardianSetReified = Reified; + +export class GuardianSet implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::guardian_set::GuardianSet`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = GuardianSet.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = GuardianSet.$isPhantom; + + readonly index: ToField<"u32">; + readonly guardians: ToField>; + readonly expirationTimestampMs: ToField<"u64">; + + private constructor(typeArgs: [], fields: GuardianSetFields) { + this.$fullTypeName = composeSuiType(GuardianSet.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.index = fields.index; + this.guardians = fields.guardians; + this.expirationTimestampMs = fields.expirationTimestampMs; + } + + static reified(): GuardianSetReified { + return { + typeName: GuardianSet.$typeName, + fullTypeName: composeSuiType(GuardianSet.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: GuardianSet.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => GuardianSet.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => GuardianSet.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => GuardianSet.fromBcs(data), + bcs: GuardianSet.bcs, + fromJSONField: (field: any) => GuardianSet.fromJSONField(field), + fromJSON: (json: Record) => GuardianSet.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => GuardianSet.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => GuardianSet.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => GuardianSet.fetch(client, id), + new: (fields: GuardianSetFields) => { + return new GuardianSet([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return GuardianSet.reified(); + } + + static phantom(): PhantomReified> { + return phantom(GuardianSet.reified()); + } + static get p() { + return GuardianSet.phantom(); + } + + static get bcs() { + return bcs.struct("GuardianSet", { + index: bcs.u32(), + guardians: bcs.vector(Guardian.bcs), + expiration_timestamp_ms: bcs.u64(), + }); + } + + static fromFields(fields: Record): GuardianSet { + return GuardianSet.reified().new({ + index: decodeFromFields("u32", fields.index), + guardians: decodeFromFields(reified.vector(Guardian.reified()), fields.guardians), + expirationTimestampMs: decodeFromFields("u64", fields.expiration_timestamp_ms), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): GuardianSet { + if (!isGuardianSet(item.type)) { + throw new Error("not a GuardianSet type"); + } + + return GuardianSet.reified().new({ + index: decodeFromFieldsWithTypes("u32", item.fields.index), + guardians: decodeFromFieldsWithTypes(reified.vector(Guardian.reified()), item.fields.guardians), + expirationTimestampMs: decodeFromFieldsWithTypes("u64", item.fields.expiration_timestamp_ms), + }); + } + + static fromBcs(data: Uint8Array): GuardianSet { + return GuardianSet.fromFields(GuardianSet.bcs.parse(data)); + } + + toJSONField() { + return { + index: this.index, + guardians: fieldToJSON>(`vector<${Guardian.$typeName}>`, this.guardians), + expirationTimestampMs: this.expirationTimestampMs.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): GuardianSet { + return GuardianSet.reified().new({ + index: decodeFromJSONField("u32", field.index), + guardians: decodeFromJSONField(reified.vector(Guardian.reified()), field.guardians), + expirationTimestampMs: decodeFromJSONField("u64", field.expirationTimestampMs), + }); + } + + static fromJSON(json: Record): GuardianSet { + if (json.$typeName !== GuardianSet.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return GuardianSet.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): GuardianSet { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isGuardianSet(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a GuardianSet object`); + } + return GuardianSet.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): GuardianSet { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isGuardianSet(data.bcs.type)) { + throw new Error(`object at is not a GuardianSet object`); + } + + return GuardianSet.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return GuardianSet.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching GuardianSet object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isGuardianSet(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a GuardianSet object`); + } + + return GuardianSet.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/guardian/structs.ts b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/guardian/structs.ts new file mode 100644 index 00000000..38c9c45f --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/guardian/structs.ts @@ -0,0 +1,181 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { Bytes20 } from "../bytes20/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Guardian =============================== */ + +export function isGuardian(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::guardian::Guardian`; +} + +export interface GuardianFields { + pubkey: ToField; +} + +export type GuardianReified = Reified; + +export class Guardian implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::guardian::Guardian`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Guardian.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Guardian.$isPhantom; + + readonly pubkey: ToField; + + private constructor(typeArgs: [], fields: GuardianFields) { + this.$fullTypeName = composeSuiType(Guardian.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.pubkey = fields.pubkey; + } + + static reified(): GuardianReified { + return { + typeName: Guardian.$typeName, + fullTypeName: composeSuiType(Guardian.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Guardian.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Guardian.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Guardian.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Guardian.fromBcs(data), + bcs: Guardian.bcs, + fromJSONField: (field: any) => Guardian.fromJSONField(field), + fromJSON: (json: Record) => Guardian.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Guardian.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Guardian.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Guardian.fetch(client, id), + new: (fields: GuardianFields) => { + return new Guardian([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Guardian.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Guardian.reified()); + } + static get p() { + return Guardian.phantom(); + } + + static get bcs() { + return bcs.struct("Guardian", { + pubkey: Bytes20.bcs, + }); + } + + static fromFields(fields: Record): Guardian { + return Guardian.reified().new({ + pubkey: decodeFromFields(Bytes20.reified(), fields.pubkey), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Guardian { + if (!isGuardian(item.type)) { + throw new Error("not a Guardian type"); + } + + return Guardian.reified().new({ + pubkey: decodeFromFieldsWithTypes(Bytes20.reified(), item.fields.pubkey), + }); + } + + static fromBcs(data: Uint8Array): Guardian { + return Guardian.fromFields(Guardian.bcs.parse(data)); + } + + toJSONField() { + return { + pubkey: this.pubkey.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Guardian { + return Guardian.reified().new({ + pubkey: decodeFromJSONField(Bytes20.reified(), field.pubkey), + }); + } + + static fromJSON(json: Record): Guardian { + if (json.$typeName !== Guardian.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Guardian.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Guardian { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isGuardian(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Guardian object`); + } + return Guardian.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Guardian { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isGuardian(data.bcs.type)) { + throw new Error(`object at is not a Guardian object`); + } + + return Guardian.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Guardian.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Guardian object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isGuardian(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Guardian object`); + } + + return Guardian.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/index.ts b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/index.ts new file mode 100644 index 00000000..848b3db2 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/index.ts @@ -0,0 +1,4 @@ +// @ts-nocheck +export const PACKAGE_ID = "0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94"; +export const PUBLISHED_AT = "0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94"; +export const PKG_V1 = "0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94"; diff --git a/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/init.ts b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/init.ts new file mode 100644 index 00000000..4f37cd15 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/init.ts @@ -0,0 +1,34 @@ +// @ts-nocheck +import * as bytes20 from "./bytes20/structs"; +import * as bytes32 from "./bytes32/structs"; +import * as consumedVaas from "./consumed-vaas/structs"; +import * as cursor from "./cursor/structs"; +import * as emitter from "./emitter/structs"; +import * as externalAddress from "./external-address/structs"; +import * as feeCollector from "./fee-collector/structs"; +import * as guardianSet from "./guardian-set/structs"; +import * as guardian from "./guardian/structs"; +import * as publishMessage from "./publish-message/structs"; +import * as set from "./set/structs"; +import * as state from "./state/structs"; +import * as vaa from "./vaa/structs"; +import { StructClassLoader } from "../../../_framework/loader"; + +export function registerClasses(loader: StructClassLoader) { + loader.register(cursor.Cursor); + loader.register(bytes20.Bytes20); + loader.register(guardian.Guardian); + loader.register(guardianSet.GuardianSet); + loader.register(feeCollector.FeeCollector); + loader.register(bytes32.Bytes32); + loader.register(externalAddress.ExternalAddress); + loader.register(set.Empty); + loader.register(set.Set); + loader.register(consumedVaas.ConsumedVAAs); + loader.register(state.State); + loader.register(vaa.VAA); + loader.register(emitter.EmitterCap); + loader.register(emitter.EmitterCreated); + loader.register(publishMessage.MessageTicket); + loader.register(publishMessage.WormholeMessage); +} diff --git a/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/publish-message/structs.ts b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/publish-message/structs.ts new file mode 100644 index 00000000..eac99928 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/publish-message/structs.ts @@ -0,0 +1,411 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { Vector } from "../../../../_framework/vector"; +import { ID } from "../../../../sui/object/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== MessageTicket =============================== */ + +export function isMessageTicket(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::publish_message::MessageTicket`; +} + +export interface MessageTicketFields { + sender: ToField; + sequence: ToField<"u64">; + nonce: ToField<"u32">; + payload: ToField>; +} + +export type MessageTicketReified = Reified; + +export class MessageTicket implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::publish_message::MessageTicket`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = MessageTicket.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = MessageTicket.$isPhantom; + + readonly sender: ToField; + readonly sequence: ToField<"u64">; + readonly nonce: ToField<"u32">; + readonly payload: ToField>; + + private constructor(typeArgs: [], fields: MessageTicketFields) { + this.$fullTypeName = composeSuiType(MessageTicket.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.sender = fields.sender; + this.sequence = fields.sequence; + this.nonce = fields.nonce; + this.payload = fields.payload; + } + + static reified(): MessageTicketReified { + return { + typeName: MessageTicket.$typeName, + fullTypeName: composeSuiType(MessageTicket.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: MessageTicket.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => MessageTicket.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => MessageTicket.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => MessageTicket.fromBcs(data), + bcs: MessageTicket.bcs, + fromJSONField: (field: any) => MessageTicket.fromJSONField(field), + fromJSON: (json: Record) => MessageTicket.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => MessageTicket.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => MessageTicket.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => MessageTicket.fetch(client, id), + new: (fields: MessageTicketFields) => { + return new MessageTicket([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return MessageTicket.reified(); + } + + static phantom(): PhantomReified> { + return phantom(MessageTicket.reified()); + } + static get p() { + return MessageTicket.phantom(); + } + + static get bcs() { + return bcs.struct("MessageTicket", { + sender: ID.bcs, + sequence: bcs.u64(), + nonce: bcs.u32(), + payload: bcs.vector(bcs.u8()), + }); + } + + static fromFields(fields: Record): MessageTicket { + return MessageTicket.reified().new({ + sender: decodeFromFields(ID.reified(), fields.sender), + sequence: decodeFromFields("u64", fields.sequence), + nonce: decodeFromFields("u32", fields.nonce), + payload: decodeFromFields(reified.vector("u8"), fields.payload), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): MessageTicket { + if (!isMessageTicket(item.type)) { + throw new Error("not a MessageTicket type"); + } + + return MessageTicket.reified().new({ + sender: decodeFromFieldsWithTypes(ID.reified(), item.fields.sender), + sequence: decodeFromFieldsWithTypes("u64", item.fields.sequence), + nonce: decodeFromFieldsWithTypes("u32", item.fields.nonce), + payload: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.payload), + }); + } + + static fromBcs(data: Uint8Array): MessageTicket { + return MessageTicket.fromFields(MessageTicket.bcs.parse(data)); + } + + toJSONField() { + return { + sender: this.sender, + sequence: this.sequence.toString(), + nonce: this.nonce, + payload: fieldToJSON>(`vector`, this.payload), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): MessageTicket { + return MessageTicket.reified().new({ + sender: decodeFromJSONField(ID.reified(), field.sender), + sequence: decodeFromJSONField("u64", field.sequence), + nonce: decodeFromJSONField("u32", field.nonce), + payload: decodeFromJSONField(reified.vector("u8"), field.payload), + }); + } + + static fromJSON(json: Record): MessageTicket { + if (json.$typeName !== MessageTicket.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return MessageTicket.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): MessageTicket { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isMessageTicket(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a MessageTicket object`); + } + return MessageTicket.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): MessageTicket { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isMessageTicket(data.bcs.type)) { + throw new Error(`object at is not a MessageTicket object`); + } + + return MessageTicket.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return MessageTicket.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching MessageTicket object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isMessageTicket(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a MessageTicket object`); + } + + return MessageTicket.fromSuiObjectData(res.data); + } +} + +/* ============================== WormholeMessage =============================== */ + +export function isWormholeMessage(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::publish_message::WormholeMessage`; +} + +export interface WormholeMessageFields { + sender: ToField; + sequence: ToField<"u64">; + nonce: ToField<"u32">; + payload: ToField>; + consistencyLevel: ToField<"u8">; + timestamp: ToField<"u64">; +} + +export type WormholeMessageReified = Reified; + +export class WormholeMessage implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::publish_message::WormholeMessage`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = WormholeMessage.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = WormholeMessage.$isPhantom; + + readonly sender: ToField; + readonly sequence: ToField<"u64">; + readonly nonce: ToField<"u32">; + readonly payload: ToField>; + readonly consistencyLevel: ToField<"u8">; + readonly timestamp: ToField<"u64">; + + private constructor(typeArgs: [], fields: WormholeMessageFields) { + this.$fullTypeName = composeSuiType(WormholeMessage.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.sender = fields.sender; + this.sequence = fields.sequence; + this.nonce = fields.nonce; + this.payload = fields.payload; + this.consistencyLevel = fields.consistencyLevel; + this.timestamp = fields.timestamp; + } + + static reified(): WormholeMessageReified { + return { + typeName: WormholeMessage.$typeName, + fullTypeName: composeSuiType(WormholeMessage.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: WormholeMessage.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => WormholeMessage.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => WormholeMessage.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => WormholeMessage.fromBcs(data), + bcs: WormholeMessage.bcs, + fromJSONField: (field: any) => WormholeMessage.fromJSONField(field), + fromJSON: (json: Record) => WormholeMessage.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => WormholeMessage.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => WormholeMessage.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => WormholeMessage.fetch(client, id), + new: (fields: WormholeMessageFields) => { + return new WormholeMessage([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return WormholeMessage.reified(); + } + + static phantom(): PhantomReified> { + return phantom(WormholeMessage.reified()); + } + static get p() { + return WormholeMessage.phantom(); + } + + static get bcs() { + return bcs.struct("WormholeMessage", { + sender: ID.bcs, + sequence: bcs.u64(), + nonce: bcs.u32(), + payload: bcs.vector(bcs.u8()), + consistency_level: bcs.u8(), + timestamp: bcs.u64(), + }); + } + + static fromFields(fields: Record): WormholeMessage { + return WormholeMessage.reified().new({ + sender: decodeFromFields(ID.reified(), fields.sender), + sequence: decodeFromFields("u64", fields.sequence), + nonce: decodeFromFields("u32", fields.nonce), + payload: decodeFromFields(reified.vector("u8"), fields.payload), + consistencyLevel: decodeFromFields("u8", fields.consistency_level), + timestamp: decodeFromFields("u64", fields.timestamp), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): WormholeMessage { + if (!isWormholeMessage(item.type)) { + throw new Error("not a WormholeMessage type"); + } + + return WormholeMessage.reified().new({ + sender: decodeFromFieldsWithTypes(ID.reified(), item.fields.sender), + sequence: decodeFromFieldsWithTypes("u64", item.fields.sequence), + nonce: decodeFromFieldsWithTypes("u32", item.fields.nonce), + payload: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.payload), + consistencyLevel: decodeFromFieldsWithTypes("u8", item.fields.consistency_level), + timestamp: decodeFromFieldsWithTypes("u64", item.fields.timestamp), + }); + } + + static fromBcs(data: Uint8Array): WormholeMessage { + return WormholeMessage.fromFields(WormholeMessage.bcs.parse(data)); + } + + toJSONField() { + return { + sender: this.sender, + sequence: this.sequence.toString(), + nonce: this.nonce, + payload: fieldToJSON>(`vector`, this.payload), + consistencyLevel: this.consistencyLevel, + timestamp: this.timestamp.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): WormholeMessage { + return WormholeMessage.reified().new({ + sender: decodeFromJSONField(ID.reified(), field.sender), + sequence: decodeFromJSONField("u64", field.sequence), + nonce: decodeFromJSONField("u32", field.nonce), + payload: decodeFromJSONField(reified.vector("u8"), field.payload), + consistencyLevel: decodeFromJSONField("u8", field.consistencyLevel), + timestamp: decodeFromJSONField("u64", field.timestamp), + }); + } + + static fromJSON(json: Record): WormholeMessage { + if (json.$typeName !== WormholeMessage.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return WormholeMessage.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): WormholeMessage { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isWormholeMessage(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a WormholeMessage object`); + } + return WormholeMessage.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): WormholeMessage { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isWormholeMessage(data.bcs.type)) { + throw new Error(`object at is not a WormholeMessage object`); + } + + return WormholeMessage.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return WormholeMessage.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching WormholeMessage object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isWormholeMessage(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a WormholeMessage object`); + } + + return WormholeMessage.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/set/structs.ts b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/set/structs.ts new file mode 100644 index 00000000..c56884bf --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/set/structs.ts @@ -0,0 +1,391 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, + ToTypeStr as ToPhantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../../../_framework/util"; +import { Table } from "../../../../sui/table/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Empty =============================== */ + +export function isEmpty(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::set::Empty`; +} + +export interface EmptyFields { + dummyField: ToField<"bool">; +} + +export type EmptyReified = Reified; + +export class Empty implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::set::Empty`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Empty.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Empty.$isPhantom; + + readonly dummyField: ToField<"bool">; + + private constructor(typeArgs: [], fields: EmptyFields) { + this.$fullTypeName = composeSuiType(Empty.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.dummyField = fields.dummyField; + } + + static reified(): EmptyReified { + return { + typeName: Empty.$typeName, + fullTypeName: composeSuiType(Empty.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Empty.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Empty.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Empty.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Empty.fromBcs(data), + bcs: Empty.bcs, + fromJSONField: (field: any) => Empty.fromJSONField(field), + fromJSON: (json: Record) => Empty.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Empty.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Empty.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Empty.fetch(client, id), + new: (fields: EmptyFields) => { + return new Empty([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Empty.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Empty.reified()); + } + static get p() { + return Empty.phantom(); + } + + static get bcs() { + return bcs.struct("Empty", { + dummy_field: bcs.bool(), + }); + } + + static fromFields(fields: Record): Empty { + return Empty.reified().new({ + dummyField: decodeFromFields("bool", fields.dummy_field), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Empty { + if (!isEmpty(item.type)) { + throw new Error("not a Empty type"); + } + + return Empty.reified().new({ + dummyField: decodeFromFieldsWithTypes("bool", item.fields.dummy_field), + }); + } + + static fromBcs(data: Uint8Array): Empty { + return Empty.fromFields(Empty.bcs.parse(data)); + } + + toJSONField() { + return { + dummyField: this.dummyField, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Empty { + return Empty.reified().new({ + dummyField: decodeFromJSONField("bool", field.dummyField), + }); + } + + static fromJSON(json: Record): Empty { + if (json.$typeName !== Empty.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Empty.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Empty { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isEmpty(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Empty object`); + } + return Empty.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Empty { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isEmpty(data.bcs.type)) { + throw new Error(`object at is not a Empty object`); + } + + return Empty.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Empty.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Empty object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isEmpty(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Empty object`); + } + + return Empty.fromSuiObjectData(res.data); + } +} + +/* ============================== Set =============================== */ + +export function isSet(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V1}::set::Set` + "<"); +} + +export interface SetFields { + items: ToField>>; +} + +export type SetReified = Reified, SetFields>; + +export class Set implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::set::Set`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = Set.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = Set.$isPhantom; + + readonly items: ToField>>; + + private constructor(typeArgs: [PhantomToTypeStr], fields: SetFields) { + this.$fullTypeName = composeSuiType(Set.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.items = fields.items; + } + + static reified>(T: T): SetReified> { + return { + typeName: Set.$typeName, + fullTypeName: composeSuiType(Set.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: Set.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => Set.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Set.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => Set.fromBcs(T, data), + bcs: Set.bcs, + fromJSONField: (field: any) => Set.fromJSONField(T, field), + fromJSON: (json: Record) => Set.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => Set.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => Set.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => Set.fetch(client, T, id), + new: (fields: SetFields>) => { + return new Set([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Set.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(Set.reified(T)); + } + static get p() { + return Set.phantom; + } + + static get bcs() { + return bcs.struct("Set", { + items: Table.bcs, + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): Set> { + return Set.reified(typeArg).new({ + items: decodeFromFields(Table.reified(typeArg, reified.phantom(Empty.reified())), fields.items), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): Set> { + if (!isSet(item.type)) { + throw new Error("not a Set type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Set.reified(typeArg).new({ + items: decodeFromFieldsWithTypes(Table.reified(typeArg, reified.phantom(Empty.reified())), item.fields.items), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): Set> { + return Set.fromFields(typeArg, Set.bcs.parse(data)); + } + + toJSONField() { + return { + items: this.items.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): Set> { + return Set.reified(typeArg).new({ + items: decodeFromJSONField(Table.reified(typeArg, reified.phantom(Empty.reified())), field.items), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): Set> { + if (json.$typeName !== Set.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Set.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Set.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): Set> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isSet(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Set object`); + } + return Set.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): Set> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isSet(data.bcs.type)) { + throw new Error(`object at is not a Set object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Set.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Set.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Set object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isSet(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Set object`); + } + + return Set.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/state/structs.ts b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/state/structs.ts new file mode 100644 index 00000000..fd8caf3f --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/state/structs.ts @@ -0,0 +1,262 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, + ToTypeStr as ToPhantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { UID } from "../../../../sui/object/structs"; +import { UpgradeCap } from "../../../../sui/package/structs"; +import { Table } from "../../../../sui/table/structs"; +import { ConsumedVAAs } from "../consumed-vaas/structs"; +import { ExternalAddress } from "../external-address/structs"; +import { FeeCollector } from "../fee-collector/structs"; +import { GuardianSet } from "../guardian-set/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== State =============================== */ + +export function isState(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::state::State`; +} + +export interface StateFields { + id: ToField; + governanceChain: ToField<"u16">; + governanceContract: ToField; + guardianSetIndex: ToField<"u32">; + guardianSets: ToField>>; + guardianSetSecondsToLive: ToField<"u32">; + consumedVaas: ToField; + feeCollector: ToField; + upgradeCap: ToField; +} + +export type StateReified = Reified; + +export class State implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::state::State`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = State.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = State.$isPhantom; + + readonly id: ToField; + readonly governanceChain: ToField<"u16">; + readonly governanceContract: ToField; + readonly guardianSetIndex: ToField<"u32">; + readonly guardianSets: ToField>>; + readonly guardianSetSecondsToLive: ToField<"u32">; + readonly consumedVaas: ToField; + readonly feeCollector: ToField; + readonly upgradeCap: ToField; + + private constructor(typeArgs: [], fields: StateFields) { + this.$fullTypeName = composeSuiType(State.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.governanceChain = fields.governanceChain; + this.governanceContract = fields.governanceContract; + this.guardianSetIndex = fields.guardianSetIndex; + this.guardianSets = fields.guardianSets; + this.guardianSetSecondsToLive = fields.guardianSetSecondsToLive; + this.consumedVaas = fields.consumedVaas; + this.feeCollector = fields.feeCollector; + this.upgradeCap = fields.upgradeCap; + } + + static reified(): StateReified { + return { + typeName: State.$typeName, + fullTypeName: composeSuiType(State.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: State.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => State.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => State.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => State.fromBcs(data), + bcs: State.bcs, + fromJSONField: (field: any) => State.fromJSONField(field), + fromJSON: (json: Record) => State.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => State.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => State.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => State.fetch(client, id), + new: (fields: StateFields) => { + return new State([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return State.reified(); + } + + static phantom(): PhantomReified> { + return phantom(State.reified()); + } + static get p() { + return State.phantom(); + } + + static get bcs() { + return bcs.struct("State", { + id: UID.bcs, + governance_chain: bcs.u16(), + governance_contract: ExternalAddress.bcs, + guardian_set_index: bcs.u32(), + guardian_sets: Table.bcs, + guardian_set_seconds_to_live: bcs.u32(), + consumed_vaas: ConsumedVAAs.bcs, + fee_collector: FeeCollector.bcs, + upgrade_cap: UpgradeCap.bcs, + }); + } + + static fromFields(fields: Record): State { + return State.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + governanceChain: decodeFromFields("u16", fields.governance_chain), + governanceContract: decodeFromFields(ExternalAddress.reified(), fields.governance_contract), + guardianSetIndex: decodeFromFields("u32", fields.guardian_set_index), + guardianSets: decodeFromFields( + Table.reified(reified.phantom("u32"), reified.phantom(GuardianSet.reified())), + fields.guardian_sets + ), + guardianSetSecondsToLive: decodeFromFields("u32", fields.guardian_set_seconds_to_live), + consumedVaas: decodeFromFields(ConsumedVAAs.reified(), fields.consumed_vaas), + feeCollector: decodeFromFields(FeeCollector.reified(), fields.fee_collector), + upgradeCap: decodeFromFields(UpgradeCap.reified(), fields.upgrade_cap), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): State { + if (!isState(item.type)) { + throw new Error("not a State type"); + } + + return State.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + governanceChain: decodeFromFieldsWithTypes("u16", item.fields.governance_chain), + governanceContract: decodeFromFieldsWithTypes(ExternalAddress.reified(), item.fields.governance_contract), + guardianSetIndex: decodeFromFieldsWithTypes("u32", item.fields.guardian_set_index), + guardianSets: decodeFromFieldsWithTypes( + Table.reified(reified.phantom("u32"), reified.phantom(GuardianSet.reified())), + item.fields.guardian_sets + ), + guardianSetSecondsToLive: decodeFromFieldsWithTypes("u32", item.fields.guardian_set_seconds_to_live), + consumedVaas: decodeFromFieldsWithTypes(ConsumedVAAs.reified(), item.fields.consumed_vaas), + feeCollector: decodeFromFieldsWithTypes(FeeCollector.reified(), item.fields.fee_collector), + upgradeCap: decodeFromFieldsWithTypes(UpgradeCap.reified(), item.fields.upgrade_cap), + }); + } + + static fromBcs(data: Uint8Array): State { + return State.fromFields(State.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + governanceChain: this.governanceChain, + governanceContract: this.governanceContract.toJSONField(), + guardianSetIndex: this.guardianSetIndex, + guardianSets: this.guardianSets.toJSONField(), + guardianSetSecondsToLive: this.guardianSetSecondsToLive, + consumedVaas: this.consumedVaas.toJSONField(), + feeCollector: this.feeCollector.toJSONField(), + upgradeCap: this.upgradeCap.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): State { + return State.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + governanceChain: decodeFromJSONField("u16", field.governanceChain), + governanceContract: decodeFromJSONField(ExternalAddress.reified(), field.governanceContract), + guardianSetIndex: decodeFromJSONField("u32", field.guardianSetIndex), + guardianSets: decodeFromJSONField( + Table.reified(reified.phantom("u32"), reified.phantom(GuardianSet.reified())), + field.guardianSets + ), + guardianSetSecondsToLive: decodeFromJSONField("u32", field.guardianSetSecondsToLive), + consumedVaas: decodeFromJSONField(ConsumedVAAs.reified(), field.consumedVaas), + feeCollector: decodeFromJSONField(FeeCollector.reified(), field.feeCollector), + upgradeCap: decodeFromJSONField(UpgradeCap.reified(), field.upgradeCap), + }); + } + + static fromJSON(json: Record): State { + if (json.$typeName !== State.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return State.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): State { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isState(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a State object`); + } + return State.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): State { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isState(data.bcs.type)) { + throw new Error(`object at is not a State object`); + } + + return State.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return State.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching State object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isState(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a State object`); + } + + return State.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/vaa/structs.ts b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/vaa/structs.ts new file mode 100644 index 00000000..774b2d51 --- /dev/null +++ b/src/services/models/sui/_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/vaa/structs.ts @@ -0,0 +1,249 @@ +// @ts-nocheck +import * as reified from "../../../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, +} from "../../../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../../../_framework/util"; +import { Vector } from "../../../../_framework/vector"; +import { Bytes32 } from "../bytes32/structs"; +import { ExternalAddress } from "../external-address/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== VAA =============================== */ + +export function isVAA(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::vaa::VAA`; +} + +export interface VAAFields { + guardianSetIndex: ToField<"u32">; + timestamp: ToField<"u32">; + nonce: ToField<"u32">; + emitterChain: ToField<"u16">; + emitterAddress: ToField; + sequence: ToField<"u64">; + consistencyLevel: ToField<"u8">; + payload: ToField>; + digest: ToField; +} + +export type VAAReified = Reified; + +export class VAA implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::vaa::VAA`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = VAA.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = VAA.$isPhantom; + + readonly guardianSetIndex: ToField<"u32">; + readonly timestamp: ToField<"u32">; + readonly nonce: ToField<"u32">; + readonly emitterChain: ToField<"u16">; + readonly emitterAddress: ToField; + readonly sequence: ToField<"u64">; + readonly consistencyLevel: ToField<"u8">; + readonly payload: ToField>; + readonly digest: ToField; + + private constructor(typeArgs: [], fields: VAAFields) { + this.$fullTypeName = composeSuiType(VAA.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.guardianSetIndex = fields.guardianSetIndex; + this.timestamp = fields.timestamp; + this.nonce = fields.nonce; + this.emitterChain = fields.emitterChain; + this.emitterAddress = fields.emitterAddress; + this.sequence = fields.sequence; + this.consistencyLevel = fields.consistencyLevel; + this.payload = fields.payload; + this.digest = fields.digest; + } + + static reified(): VAAReified { + return { + typeName: VAA.$typeName, + fullTypeName: composeSuiType(VAA.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: VAA.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => VAA.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => VAA.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => VAA.fromBcs(data), + bcs: VAA.bcs, + fromJSONField: (field: any) => VAA.fromJSONField(field), + fromJSON: (json: Record) => VAA.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => VAA.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => VAA.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => VAA.fetch(client, id), + new: (fields: VAAFields) => { + return new VAA([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return VAA.reified(); + } + + static phantom(): PhantomReified> { + return phantom(VAA.reified()); + } + static get p() { + return VAA.phantom(); + } + + static get bcs() { + return bcs.struct("VAA", { + guardian_set_index: bcs.u32(), + timestamp: bcs.u32(), + nonce: bcs.u32(), + emitter_chain: bcs.u16(), + emitter_address: ExternalAddress.bcs, + sequence: bcs.u64(), + consistency_level: bcs.u8(), + payload: bcs.vector(bcs.u8()), + digest: Bytes32.bcs, + }); + } + + static fromFields(fields: Record): VAA { + return VAA.reified().new({ + guardianSetIndex: decodeFromFields("u32", fields.guardian_set_index), + timestamp: decodeFromFields("u32", fields.timestamp), + nonce: decodeFromFields("u32", fields.nonce), + emitterChain: decodeFromFields("u16", fields.emitter_chain), + emitterAddress: decodeFromFields(ExternalAddress.reified(), fields.emitter_address), + sequence: decodeFromFields("u64", fields.sequence), + consistencyLevel: decodeFromFields("u8", fields.consistency_level), + payload: decodeFromFields(reified.vector("u8"), fields.payload), + digest: decodeFromFields(Bytes32.reified(), fields.digest), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): VAA { + if (!isVAA(item.type)) { + throw new Error("not a VAA type"); + } + + return VAA.reified().new({ + guardianSetIndex: decodeFromFieldsWithTypes("u32", item.fields.guardian_set_index), + timestamp: decodeFromFieldsWithTypes("u32", item.fields.timestamp), + nonce: decodeFromFieldsWithTypes("u32", item.fields.nonce), + emitterChain: decodeFromFieldsWithTypes("u16", item.fields.emitter_chain), + emitterAddress: decodeFromFieldsWithTypes(ExternalAddress.reified(), item.fields.emitter_address), + sequence: decodeFromFieldsWithTypes("u64", item.fields.sequence), + consistencyLevel: decodeFromFieldsWithTypes("u8", item.fields.consistency_level), + payload: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.payload), + digest: decodeFromFieldsWithTypes(Bytes32.reified(), item.fields.digest), + }); + } + + static fromBcs(data: Uint8Array): VAA { + return VAA.fromFields(VAA.bcs.parse(data)); + } + + toJSONField() { + return { + guardianSetIndex: this.guardianSetIndex, + timestamp: this.timestamp, + nonce: this.nonce, + emitterChain: this.emitterChain, + emitterAddress: this.emitterAddress.toJSONField(), + sequence: this.sequence.toString(), + consistencyLevel: this.consistencyLevel, + payload: fieldToJSON>(`vector`, this.payload), + digest: this.digest.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): VAA { + return VAA.reified().new({ + guardianSetIndex: decodeFromJSONField("u32", field.guardianSetIndex), + timestamp: decodeFromJSONField("u32", field.timestamp), + nonce: decodeFromJSONField("u32", field.nonce), + emitterChain: decodeFromJSONField("u16", field.emitterChain), + emitterAddress: decodeFromJSONField(ExternalAddress.reified(), field.emitterAddress), + sequence: decodeFromJSONField("u64", field.sequence), + consistencyLevel: decodeFromJSONField("u8", field.consistencyLevel), + payload: decodeFromJSONField(reified.vector("u8"), field.payload), + digest: decodeFromJSONField(Bytes32.reified(), field.digest), + }); + } + + static fromJSON(json: Record): VAA { + if (json.$typeName !== VAA.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return VAA.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): VAA { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isVAA(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a VAA object`); + } + return VAA.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): VAA { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isVAA(data.bcs.type)) { + throw new Error(`object at is not a VAA object`); + } + + return VAA.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return VAA.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching VAA object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isVAA(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a VAA object`); + } + + return VAA.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/_framework/init-loader.ts b/src/services/models/sui/_framework/init-loader.ts new file mode 100644 index 00000000..954f9441 --- /dev/null +++ b/src/services/models/sui/_framework/init-loader.ts @@ -0,0 +1,33 @@ +// @ts-nocheck +import * as package_source_1 from "../_dependencies/source/0x1/init"; +import * as package_source_31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb from "../_dependencies/source/0x31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb/init"; +import * as package_source_346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917 from "../_dependencies/source/0x346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917/init"; +import * as package_source_4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5 from "../_dependencies/source/0x4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5/init"; +import * as package_source_f47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94 from "../_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/init"; +import * as package_source_a2b1c8af2a4f4624362c4a7d0f91fb6b0921e780ffb2c07701901c734d75d2e3 from "../bridge/init"; +import * as package_source_cfb3ada02ea9b40f2beb396f5f781689a2f6862d224e6c9854e175d14278f9f5 from "../cctp-bridge/init"; +import * as package_source_34ae5595909bdfcd61191f6e5aabf0024250194f738b82df186fdd4fb18aa7ec from "../gas-oracle/init"; +import * as package_source_73d4d15293c2482646cdfc28c58da0f9eef64c577e9c0d2bbf614c1623346b49 from "../messenger/init"; +import * as package_source_2 from "../sui/init"; +import * as package_source_4dacc15807ba7ccfcdfcc2d0498401bbf504d112a5959323660d757a02b850d4 from "../utils/init"; +import * as package_source_0 from "../wormhole-messenger/init"; +import { StructClassLoader } from "./loader"; + +function registerClassesSource(loader: StructClassLoader) { + package_source_0.registerClasses(loader); + package_source_1.registerClasses(loader); + package_source_2.registerClasses(loader); + package_source_31cc14d80c175ae39777c0238f20594c6d4869cfab199f40b69f3319956b8beb.registerClasses(loader); + package_source_346e3233f61eb0055713417bfaddda7dc3bf26816faad1f7606994a368b92917.registerClasses(loader); + package_source_34ae5595909bdfcd61191f6e5aabf0024250194f738b82df186fdd4fb18aa7ec.registerClasses(loader); + package_source_4931e06dce648b3931f890035bd196920770e913e43e45990b383f6486fdd0a5.registerClasses(loader); + package_source_4dacc15807ba7ccfcdfcc2d0498401bbf504d112a5959323660d757a02b850d4.registerClasses(loader); + package_source_73d4d15293c2482646cdfc28c58da0f9eef64c577e9c0d2bbf614c1623346b49.registerClasses(loader); + package_source_a2b1c8af2a4f4624362c4a7d0f91fb6b0921e780ffb2c07701901c734d75d2e3.registerClasses(loader); + package_source_cfb3ada02ea9b40f2beb396f5f781689a2f6862d224e6c9854e175d14278f9f5.registerClasses(loader); + package_source_f47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94.registerClasses(loader); +} + +export function registerClasses(loader: StructClassLoader) { + registerClassesSource(loader); +} diff --git a/src/services/models/sui/_framework/loader.ts b/src/services/models/sui/_framework/loader.ts new file mode 100644 index 00000000..85cb921b --- /dev/null +++ b/src/services/models/sui/_framework/loader.ts @@ -0,0 +1,85 @@ +// @ts-nocheck + +import { compressSuiType, parseTypeName } from "./util"; +import { + PhantomReified, + PhantomTypeArgument, + Primitive, + Reified, + StructClass, + StructClassReified, + TypeArgument, + VectorClass, + VectorClassReified, + phantom, + vector, +} from "./reified"; +import { registerClasses } from "./init-loader"; + +export type PrimitiveValue = string | number | boolean | bigint; + +interface _StructClass { + $typeName: string; + $numTypeParams: number; + $isPhantom: readonly boolean[]; + reified( + ...Ts: Array | PhantomReified> + ): StructClassReified; +} + +export class StructClassLoader { + private map: Map = new Map(); + + register(...classes: _StructClass[]) { + for (const cls of classes) { + this.map.set(cls.$typeName, cls); + } + } + + reified(type: T): T; + reified(type: `vector<${string}>`): VectorClassReified; + reified(type: string): StructClassReified; + reified(type: string): StructClassReified | VectorClassReified | string { + const { typeName, typeArgs } = parseTypeName(compressSuiType(type)); + switch (typeName) { + case "bool": + case "u8": + case "u16": + case "u32": + case "u64": + case "u128": + case "u256": + case "address": + return typeName; + case "vector": { + if (typeArgs.length !== 1) { + throw new Error(`Vector expects 1 type argument, but got ${typeArgs.length}`); + } + return vector(this.reified(typeArgs[0])); + } + } + + if (!this.map.has(typeName)) { + throw new Error(`Unknown type ${typeName}`); + } + + const cls = this.map.get(typeName)!; + if (cls.$numTypeParams !== typeArgs.length) { + throw new Error(`Type ${typeName} expects ${cls.$numTypeParams} type arguments, but got ${typeArgs.length}`); + } + + const reifiedTypeArgs: Array | PhantomReified> = []; + for (let i = 0; i < typeArgs.length; i++) { + if (cls.$isPhantom[i]) { + reifiedTypeArgs.push(phantom(typeArgs[i])); + } else { + reifiedTypeArgs.push(this.reified(typeArgs[i])); + } + } + + return cls.reified(...reifiedTypeArgs); + } +} + +export const loader = new StructClassLoader(); +registerClasses(loader); diff --git a/src/services/models/sui/_framework/reified.ts b/src/services/models/sui/_framework/reified.ts new file mode 100644 index 00000000..76e10046 --- /dev/null +++ b/src/services/models/sui/_framework/reified.ts @@ -0,0 +1,434 @@ +// @ts-nocheck + +import { bcs, BcsType } from "@mysten/sui/bcs"; +import { fromHEX, toHEX } from "@mysten/sui/utils"; +import { FieldsWithTypes, compressSuiType, parseTypeName } from "./util"; +import { SuiClient, SuiParsedData, SuiObjectData } from "@mysten/sui/client"; + +// for backwards compatibility +export { vector } from "./vector"; + +export interface StructClass { + readonly $typeName: string; + readonly $fullTypeName: string; + readonly $typeArgs: string[]; + readonly $isPhantom: readonly boolean[]; + toJSONField(): Record; + toJSON(): Record; + + __StructClass: true; +} + +export interface VectorClass { + readonly $typeName: "vector"; + readonly $fullTypeName: string; + readonly $typeArgs: [string]; + readonly $isPhantom: readonly [false]; + toJSONField(): any[]; + toJSON(): Record; + + readonly elements: any; + + __VectorClass: true; +} + +export type Primitive = "bool" | "u8" | "u16" | "u32" | "u64" | "u128" | "u256" | "address"; +export type TypeArgument = StructClass | Primitive | VectorClass; + +export interface StructClassReified { + typeName: T["$typeName"]; // e.g., '0x2::balance::Balance', without type arguments + fullTypeName: ToTypeStr; // e.g., '0x2::balance::Balance<0x2::sui:SUI>' + typeArgs: T["$typeArgs"]; // e.g., ['0x2::sui:SUI'] + isPhantom: T["$isPhantom"]; // e.g., [true, false] + reifiedTypeArgs: Array | PhantomReified>; + bcs: BcsType; + fromFields(fields: Record): T; + fromFieldsWithTypes(item: FieldsWithTypes): T; + fromBcs(data: Uint8Array): T; + fromJSONField: (field: any) => T; + fromJSON: (json: Record) => T; + fromSuiParsedData: (content: SuiParsedData) => T; + fromSuiObjectData: (data: SuiObjectData) => T; + fetch: (client: SuiClient, id: string) => Promise; + new: (fields: Fields) => T; + kind: "StructClassReified"; +} + +export interface VectorClassReified { + typeName: T["$typeName"]; + fullTypeName: ToTypeStr; + typeArgs: T["$typeArgs"]; + isPhantom: readonly [false]; + reifiedTypeArgs: Array>; + bcs: BcsType; + fromFields(fields: any[]): T; + fromFieldsWithTypes(item: FieldsWithTypes): T; + fromBcs(data: Uint8Array): T; + fromJSONField: (field: any) => T; + fromJSON: (json: Record) => T; + new: (elements: Elements) => T; + kind: "VectorClassReified"; +} + +export type Reified = T extends Primitive + ? Primitive + : T extends StructClass + ? StructClassReified + : T extends VectorClass + ? VectorClassReified + : never; + +export type ToTypeArgument< + T extends Primitive | StructClassReified | VectorClassReified, +> = T extends Primitive + ? T + : T extends StructClassReified + ? U + : T extends VectorClassReified + ? U + : never; + +export type ToPhantomTypeArgument> = + T extends PhantomReified ? U : never; + +export type PhantomTypeArgument = string; + +export interface PhantomReified

{ + phantomType: P; + kind: "PhantomReified"; +} + +export function phantom>(reified: T): PhantomReified>>; +export function phantom

(phantomType: P): PhantomReified

; +export function phantom(type: string | Reified): PhantomReified { + if (typeof type === "string") { + return { + phantomType: type, + kind: "PhantomReified", + }; + } else { + return { + phantomType: type.fullTypeName, + kind: "PhantomReified", + }; + } +} + +export type ToTypeStr = T extends Primitive + ? T + : T extends StructClass + ? T["$fullTypeName"] + : T extends VectorClass + ? T["$fullTypeName"] + : never; + +export type PhantomToTypeStr = T extends PhantomTypeArgument ? T : never; + +export type ToJSON = T extends "bool" + ? boolean + : T extends "u8" + ? number + : T extends "u16" + ? number + : T extends "u32" + ? number + : T extends "u64" + ? string + : T extends "u128" + ? string + : T extends "u256" + ? string + : T extends "address" + ? string + : T extends { $typeName: "0x1::string::String" } + ? string + : T extends { $typeName: "0x1::ascii::String" } + ? string + : T extends { $typeName: "0x2::object::UID" } + ? string + : T extends { $typeName: "0x2::object::ID" } + ? string + : T extends { $typeName: "0x2::url::Url" } + ? string + : T extends { + $typeName: "0x1::option::Option"; + __inner: infer U extends TypeArgument; + } + ? ToJSON | null + : T extends VectorClass + ? ReturnType + : T extends StructClass + ? ReturnType + : never; + +export type ToField = T extends "bool" + ? boolean + : T extends "u8" + ? number + : T extends "u16" + ? number + : T extends "u32" + ? number + : T extends "u64" + ? bigint + : T extends "u128" + ? bigint + : T extends "u256" + ? bigint + : T extends "address" + ? string + : T extends { $typeName: "0x1::string::String" } + ? string + : T extends { $typeName: "0x1::ascii::String" } + ? string + : T extends { $typeName: "0x2::object::UID" } + ? string + : T extends { $typeName: "0x2::object::ID" } + ? string + : T extends { $typeName: "0x2::url::Url" } + ? string + : T extends { + $typeName: "0x1::option::Option"; + __inner: infer U extends TypeArgument; + } + ? ToField | null + : T extends VectorClass + ? T["elements"] + : T extends StructClass + ? T + : never; + +const Address = bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val) => toHEX(val), +}); + +export function toBcs>(arg: T): BcsType { + switch (arg) { + case "bool": + return bcs.bool(); + case "u8": + return bcs.u8(); + case "u16": + return bcs.u16(); + case "u32": + return bcs.u32(); + case "u64": + return bcs.u64(); + case "u128": + return bcs.u128(); + case "u256": + return bcs.u256(); + case "address": + return Address; + default: + return arg.bcs; + } +} + +export function extractType>(reified: T): ToTypeStr>; +export function extractType>( + reified: T +): PhantomToTypeStr>; +export function extractType | PhantomReified>( + reified: T +): string; +export function extractType(reified: Reified | PhantomReified): string { + switch (reified) { + case "u8": + case "u16": + case "u32": + case "u64": + case "u128": + case "u256": + case "bool": + case "address": + return reified; + } + switch (reified.kind) { + case "PhantomReified": + return reified.phantomType; + case "StructClassReified": + return reified.fullTypeName; + case "VectorClassReified": + return reified.fullTypeName; + } + + throw new Error("unreachable"); +} + +export function decodeFromFields(reified: Reified, field: any) { + switch (reified) { + case "bool": + case "u8": + case "u16": + case "u32": + return field; + case "u64": + case "u128": + case "u256": + return BigInt(field); + case "address": + return `0x${field}`; + } + if (reified.kind === "VectorClassReified") { + return reified.fromFields(field).elements; + } + switch (reified.typeName) { + case "0x1::string::String": + case "0x1::ascii::String": + return new TextDecoder().decode(Uint8Array.from(field.bytes)).toString(); + case "0x2::url::Url": + return new TextDecoder().decode(Uint8Array.from(field.url.bytes)).toString(); + case "0x2::object::ID": + return `0x${field.bytes}`; + case "0x2::object::UID": + return `0x${field.id.bytes}`; + case "0x1::option::Option": { + if (field.vec.length === 0) { + return null; + } + return (reified.fromFields(field) as any).vec[0]; + } + default: + return reified.fromFields(field); + } +} + +export function decodeFromFieldsWithTypes(reified: Reified, item: any) { + switch (reified) { + case "bool": + case "u8": + case "u16": + case "u32": + return item; + case "u64": + case "u128": + case "u256": + return BigInt(item); + case "address": + return item; + } + if (reified.kind === "VectorClassReified") { + return reified.fromFieldsWithTypes(item).elements; + } + switch (reified.typeName) { + case "0x1::string::String": + case "0x1::ascii::String": + case "0x2::url::Url": + case "0x2::object::ID": + return item; + case "0x2::object::UID": + return item.id; + case "0x2::balance::Balance": + return reified.fromFields({ value: BigInt(item) }); + case "0x1::option::Option": { + if (item === null) { + return null; + } + return decodeFromFieldsWithTypes((reified as any).reifiedTypeArgs[0], item); + } + default: + return reified.fromFieldsWithTypes(item); + } +} + +export function assertReifiedTypeArgsMatch( + fullType: string, + typeArgs: string[], + reifiedTypeArgs: Array | PhantomReified> +) { + if (reifiedTypeArgs.length !== typeArgs.length) { + throw new Error( + `provided item has mismatching number of type argments ${fullType} (expected ${reifiedTypeArgs.length}, got ${typeArgs.length}))` + ); + } + for (let i = 0; i < typeArgs.length; i++) { + if (compressSuiType(typeArgs[i]) !== compressSuiType(extractType(reifiedTypeArgs[i]))) { + throw new Error( + `provided item has mismatching type argments ${fullType} (expected ${extractType(reifiedTypeArgs[i])}, got ${ + typeArgs[i] + }))` + ); + } + } +} + +export function assertFieldsWithTypesArgsMatch( + item: FieldsWithTypes, + reifiedTypeArgs: Array | PhantomReified> +) { + const { typeArgs: itemTypeArgs } = parseTypeName(item.type); + assertReifiedTypeArgsMatch(item.type, itemTypeArgs, reifiedTypeArgs); +} + +export function fieldToJSON(type: string, field: ToField): ToJSON { + const { typeName, typeArgs } = parseTypeName(type); + switch (typeName) { + case "bool": + return field as any; + case "u8": + case "u16": + case "u32": + return field as any; + case "u64": + case "u128": + case "u256": + return field.toString() as any; + case "address": + case "signer": + return field as any; + case "vector": + return (field as any[]).map((item: any) => fieldToJSON(typeArgs[0], item)) as any; + // handle special types + case "0x1::string::String": + case "0x1::ascii::String": + case "0x2::url::Url": + case "0x2::object::ID": + case "0x2::object::UID": + return field as any; + case "0x1::option::Option": { + if (field === null) { + return null as any; + } + return fieldToJSON(typeArgs[0], field); + } + default: + return (field as any).toJSONField(); + } +} + +export function decodeFromJSONField(typeArg: Reified, field: any) { + switch (typeArg) { + case "bool": + case "u8": + case "u16": + case "u32": + return field; + case "u64": + case "u128": + case "u256": + return BigInt(field); + case "address": + return field; + } + if (typeArg.kind === "VectorClassReified") { + return typeArg.fromJSONField(field).elements; + } + switch (typeArg.typeName) { + case "0x1::string::String": + case "0x1::ascii::String": + case "0x2::url::Url": + case "0x2::object::ID": + case "0x2::object::UID": + return field; + case "0x1::option::Option": { + if (field === null) { + return null; + } + return decodeFromJSONField(typeArg.reifiedTypeArgs[0] as any, field); + } + default: + return typeArg.fromJSONField(field); + } +} diff --git a/src/services/models/sui/_framework/util.ts b/src/services/models/sui/_framework/util.ts new file mode 100644 index 00000000..afbbda9e --- /dev/null +++ b/src/services/models/sui/_framework/util.ts @@ -0,0 +1,378 @@ +// @ts-nocheck + +import { bcs, BcsType } from "@mysten/sui/bcs"; +import { + Transaction, + TransactionArgument, + TransactionObjectArgument, + TransactionObjectInput, +} from "@mysten/sui/transactions"; + +export interface FieldsWithTypes { + fields: Record; + type: string; +} + +export type ObjectId = string; + +export type PureArg = bigint | string | number | boolean | null | TransactionArgument | Array; +export type GenericArg = + | TransactionObjectInput + | PureArg + | Array + | Array + | Array; + +export function splitGenericParameters(str: string, genericSeparators: [string, string] = ["<", ">"]) { + const [left, right] = genericSeparators; + const tok: string[] = []; + let word = ""; + let nestedAngleBrackets = 0; + + for (let i = 0; i < str.length; i++) { + const char = str[i]; + if (char === left) { + nestedAngleBrackets++; + } + if (char === right) { + nestedAngleBrackets--; + } + if (nestedAngleBrackets === 0 && char === ",") { + tok.push(word.trim()); + word = ""; + continue; + } + word += char; + } + + tok.push(word.trim()); + + return tok; +} + +export function parseTypeName(name: string): { + typeName: string; + typeArgs: string[]; +} { + if (typeof name !== "string") { + throw new Error(`Illegal type passed as a name of the type: ${name}`); + } + + const [left, right] = ["<", ">"]; + + const l_bound = name.indexOf(left); + const r_bound = Array.from(name).reverse().indexOf(right); + + // if there are no generics - exit gracefully. + if (l_bound === -1 && r_bound === -1) { + return { typeName: name, typeArgs: [] }; + } + + // if one of the bounds is not defined - throw an Error. + if (l_bound === -1 || r_bound === -1) { + throw new Error(`Unclosed generic in name '${name}'`); + } + + const typeName = name.slice(0, l_bound); + const typeArgs = splitGenericParameters(name.slice(l_bound + 1, name.length - r_bound - 1), [left, right]); + + return { typeName, typeArgs }; +} + +export function isTransactionArgument(arg: GenericArg): arg is TransactionArgument { + if (!arg || typeof arg !== "object" || Array.isArray(arg)) { + return false; + } + + return "GasCoin" in arg || "Input" in arg || "Result" in arg || "NestedResult" in arg; +} + +export function obj(tx: Transaction, arg: TransactionObjectInput) { + return isTransactionArgument(arg) ? arg : tx.object(arg); +} + +export function pure(tx: Transaction, arg: PureArg, type: string): TransactionArgument { + if (isTransactionArgument(arg)) { + return obj(tx, arg); + } + + function getBcsForType(type: string): BcsType { + const { typeName, typeArgs } = parseTypeName(type); + switch (typeName) { + case "bool": + return bcs.Bool; + case "u8": + return bcs.U8; + case "u16": + return bcs.U16; + case "u32": + return bcs.U32; + case "u64": + return bcs.U64; + case "u128": + return bcs.U128; + case "u256": + return bcs.U256; + case "address": + return bcs.Address; + case "0x1::string::String": + case "0x1::ascii::String": + return bcs.String; + case "0x2::object::ID": + return bcs.Address; + case "0x1::option::Option": + return bcs.option(getBcsForType(typeArgs[0])); + case "vector": + return bcs.vector(getBcsForType(typeArgs[0])); + default: + throw new Error(`invalid primitive type ${type}`); + } + } + + function hasUndefinedOrNull(items: PureArg[]) { + for (const item of items) { + if (typeof item === "undefined" || item === null) { + return true; + } + + if (Array.isArray(item)) { + return hasUndefinedOrNull(item); + } + } + + return false; + } + + function consistsOnlyOfPrimitiveValues(items: PureArg[]) { + for (const item of items) { + if (!Array.isArray(item)) { + if (item === null) { + continue; + } + switch (typeof item) { + case "string": + case "number": + case "bigint": + case "boolean": + continue; + default: + return false; + } + } + + return consistsOnlyOfPrimitiveValues(item); + } + + return true; + } + + function hasPrimitiveValues(items: PureArg[]) { + for (const item of items) { + if (!Array.isArray(item)) { + switch (typeof item) { + case "string": + case "number": + case "bigint": + case "boolean": + return true; + default: + continue; + } + } + + return hasPrimitiveValues(item); + } + + return false; + } + + // handle some cases when TransactionArgument is nested within a vector or option + const { typeName, typeArgs } = parseTypeName(type); + switch (typeName) { + case "0x1::option::Option": + if (arg === null) { + return tx.pure.option("bool", null); // 'bool' is arbitrary + } + if (consistsOnlyOfPrimitiveValues([arg])) { + return tx.pure(getBcsForType(type).serialize(arg)); + } + if (hasPrimitiveValues([arg])) { + throw new Error("mixing primitive and TransactionArgument values is not supported"); + } + + // wrap it with some + return tx.moveCall({ + target: `0x1::option::some`, + typeArguments: [typeArgs[0]], + arguments: [pure(tx, arg, typeArgs[0])], + }); + case "vector": + if (!Array.isArray(arg)) { + throw new Error("expected an array for vector type"); + } + if (arg.length === 0) { + return tx.pure(bcs.vector(bcs.Bool).serialize([])); // bcs.Bool is arbitrary + } + if (hasUndefinedOrNull(arg)) { + throw new Error("the provided array contains undefined or null values"); + } + if (consistsOnlyOfPrimitiveValues(arg)) { + return tx.pure(getBcsForType(type).serialize(arg)); + } + if (hasPrimitiveValues(arg)) { + throw new Error("mixing primitive and TransactionArgument values is not supported"); + } + + return tx.makeMoveVec({ + type: typeArgs[0], + elements: arg as Array, + }); + default: + return tx.pure(getBcsForType(type).serialize(arg)); + } +} + +export function option(tx: Transaction, type: string, arg: GenericArg | null) { + if (isTransactionArgument(arg)) { + return arg; + } + + if (typeArgIsPure(type)) { + return pure(tx, arg as PureArg | TransactionArgument, `0x1::option::Option<${type}>`); + } + + if (arg === null) { + return tx.moveCall({ + target: `0x1::option::none`, + typeArguments: [type], + arguments: [], + }); + } + + // wrap it with some + const val = generic(tx, type, arg); + return tx.moveCall({ + target: `0x1::option::some`, + typeArguments: [type], + arguments: [val], + }); +} + +export function generic(tx: Transaction, type: string, arg: GenericArg) { + if (typeArgIsPure(type)) { + return pure(tx, arg as PureArg | TransactionArgument, type); + } else { + const { typeName, typeArgs } = parseTypeName(type); + if (typeName === "vector" && Array.isArray(arg)) { + const itemType = typeArgs[0]; + + return tx.makeMoveVec({ + type: itemType, + elements: arg.map((item) => obj(tx, item as TransactionObjectInput)) as Array, + }); + } else { + return obj(tx, arg as TransactionObjectInput); + } + } +} + +export function vector(tx: Transaction, itemType: string, items: Array | TransactionArgument) { + if (typeof items === "function") { + throw new Error("Transaction plugins are not supported"); + } + + if (typeArgIsPure(itemType)) { + return pure(tx, items as PureArg, `vector<${itemType}>`); + } else if (isTransactionArgument(items)) { + return items; + } else { + const { typeName: itemTypeName, typeArgs: itemTypeArgs } = parseTypeName(itemType); + if (itemTypeName === "0x1::option::Option") { + const elements = items.map((item) => option(tx, itemTypeArgs[0], item)) as Array; + return tx.makeMoveVec({ + type: itemType, + elements, + }); + } + + return tx.makeMoveVec({ + type: itemType, + elements: items as Array, + }); + } +} + +export function typeArgIsPure(type: string): boolean { + const { typeName, typeArgs } = parseTypeName(type); + switch (typeName) { + case "bool": + case "u8": + case "u16": + case "u32": + case "u64": + case "u128": + case "u256": + case "address": + case "signer": + return true; + case "vector": + return typeArgIsPure(typeArgs[0]); + case "0x1::string::String": + case "0x1::ascii::String": + case "0x2::object::ID": + return true; + case "0x1::option::Option": + return typeArgIsPure(typeArgs[0]); + default: + return false; + } +} + +export function compressSuiAddress(addr: string): string { + // remove leading zeros + const stripped = addr.split("0x").join(""); + for (let i = 0; i < stripped.length; i++) { + if (stripped[i] !== "0") { + return `0x${stripped.substring(i)}`; + } + } + return "0x0"; +} + +// Recursively removes leading zeros from a type. +// e.g. `0x00000002::module::Name<0x00001::a::C>` -> `0x2::module::Name<0x1::a::C>` +export function compressSuiType(type: string): string { + const { typeName, typeArgs } = parseTypeName(type); + switch (typeName) { + case "bool": + case "u8": + case "u16": + case "u32": + case "u64": + case "u128": + case "u256": + case "address": + case "signer": + return typeName; + case "vector": + return `vector<${compressSuiType(typeArgs[0])}>`; + default: { + const tok = typeName.split("::"); + tok[0] = compressSuiAddress(tok[0]); + const compressedName = tok.join("::"); + if (typeArgs.length > 0) { + return `${compressedName}<${typeArgs.map((typeArg) => compressSuiType(typeArg)).join(",")}>`; + } else { + return compressedName; + } + } + } +} + +export function composeSuiType(typeName: string, ...typeArgs: string[]): string { + if (typeArgs.length > 0) { + return `${typeName}<${typeArgs.join(", ")}>`; + } else { + return typeName; + } +} diff --git a/src/services/models/sui/_framework/vector.ts b/src/services/models/sui/_framework/vector.ts new file mode 100644 index 00000000..6f167dec --- /dev/null +++ b/src/services/models/sui/_framework/vector.ts @@ -0,0 +1,120 @@ +// @ts-nocheck + +import { bcs } from "@mysten/sui/bcs"; +import { + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + Reified, + toBcs, + ToField, + ToTypeArgument, + ToTypeStr, + TypeArgument, + VectorClass, + VectorClassReified, + fieldToJSON, +} from "./reified"; +import { composeSuiType, FieldsWithTypes } from "./util"; + +export type VectorElements = Array>; + +export type VectorReified = VectorClassReified, VectorElements>; + +export class Vector implements VectorClass { + __VectorClass = true as const; + + static readonly $typeName = "vector"; + static readonly $numTypeParams = 1; + static readonly $isPhantom = [false] as const; + + readonly $typeName = "vector"; + readonly $fullTypeName: `vector<${ToTypeStr}>`; + readonly $typeArgs: [ToTypeStr]; + readonly $isPhantom = [false] as const; + + readonly elements: Array>; + + constructor(typeArgs: [ToTypeStr], elements: VectorElements) { + this.$fullTypeName = composeSuiType(this.$typeName, ...typeArgs) as `vector<${ToTypeStr}>`; + this.$typeArgs = typeArgs; + + this.elements = elements; + } + + static reified>(T: T): VectorReified> { + return { + typeName: Vector.$typeName, + fullTypeName: composeSuiType(Vector.$typeName, ...[extractType(T)]) as `vector<${ToTypeStr>}>`, + typeArgs: [extractType(T)] as [ToTypeStr>], + isPhantom: Vector.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (elements: any[]) => Vector.fromFields(T, elements), + fromFieldsWithTypes: (item: FieldsWithTypes) => Vector.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => Vector.fromBcs(T, data), + bcs: Vector.bcs(toBcs(T)), + fromJSONField: (field: any) => Vector.fromJSONField(T, field), + fromJSON: (json: any) => Vector.fromJSON(T, json), + new: (elements: VectorElements>) => { + return new Vector([extractType(T)], elements); + }, + kind: "VectorClassReified", + }; + } + + static get r() { + return Vector.reified; + } + + static get bcs() { + return bcs.vector; + } + + static fromFields>(typeArg: T, elements: any[]): Vector> { + return Vector.reified(typeArg).new(elements.map((element) => decodeFromFields(typeArg, element))); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): Vector> { + return Vector.reified(typeArg).new( + (item as unknown as any[]).map((field: any) => decodeFromFieldsWithTypes(typeArg, field)) + ); + } + + static fromBcs>(typeArg: T, data: Uint8Array): Vector> { + return Vector.fromFields(typeArg, Vector.bcs(toBcs(typeArg)).parse(data)); + } + + toJSONField() { + return this.elements.map((element) => fieldToJSON(this.$typeArgs[0], element)); + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + elements: this.toJSONField(), + }; + } + + static fromJSONField>(typeArg: T, field: any[]): Vector> { + return Vector.reified(typeArg).new(field.map((field) => decodeFromJSONField(typeArg, field))); + } + + static fromJSON>(typeArg: T, json: any): Vector> { + if (json.$typeName !== Vector.$typeName) { + throw new Error("not a vector json object"); + } + + return Vector.fromJSONField(typeArg, json.elements); + } +} + +export function vector>( + T: T +): VectorClassReified>, VectorElements>> { + return Vector.r(T); +} diff --git a/src/services/models/sui/bridge/another-bridge/functions.ts b/src/services/models/sui/bridge/another-bridge/functions.ts new file mode 100644 index 00000000..879a5f92 --- /dev/null +++ b/src/services/models/sui/bridge/another-bridge/functions.ts @@ -0,0 +1,92 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function destroyEmpty(tx: Transaction, userDeposit: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::another_bridge::destroy_empty`, + arguments: [obj(tx, userDeposit)], + }); +} + +export function new_(tx: Transaction, address: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::another_bridge::new`, + arguments: [obj(tx, address)], + }); +} + +export interface SetGasUsageArgs { + anotherBridge: TransactionObjectInput; + gasUsage: bigint | TransactionArgument; +} + +export function setGasUsage(tx: Transaction, args: SetGasUsageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::another_bridge::set_gas_usage`, + arguments: [obj(tx, args.anotherBridge), pure(tx, args.gasUsage, `u64`)], + }); +} + +export function gasUsage(tx: Transaction, anotherBridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::another_bridge::gas_usage`, + arguments: [obj(tx, anotherBridge)], + }); +} + +export interface AddTokenArgs { + anotherBridge: TransactionObjectInput; + address: TransactionObjectInput; +} + +export function addToken(tx: Transaction, args: AddTokenArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::another_bridge::add_token`, + arguments: [obj(tx, args.anotherBridge), obj(tx, args.address)], + }); +} + +export function bridgeAddress(tx: Transaction, anotherBridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::another_bridge::bridge_address`, + arguments: [obj(tx, anotherBridge)], + }); +} + +export interface HasTokenArgs { + anotherBridge: TransactionObjectInput; + address: TransactionObjectInput; +} + +export function hasToken(tx: Transaction, args: HasTokenArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::another_bridge::has_token`, + arguments: [obj(tx, args.anotherBridge), obj(tx, args.address)], + }); +} + +export interface RemoveTokenArgs { + anotherBridge: TransactionObjectInput; + address: TransactionObjectInput; +} + +export function removeToken(tx: Transaction, args: RemoveTokenArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::another_bridge::remove_token`, + arguments: [obj(tx, args.anotherBridge), obj(tx, args.address)], + }); +} + +export interface SetAddressArgs { + anotherBridge: TransactionObjectInput; + address: TransactionObjectInput; +} + +export function setAddress(tx: Transaction, args: SetAddressArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::another_bridge::set_address`, + arguments: [obj(tx, args.anotherBridge), obj(tx, args.address)], + }); +} diff --git a/src/services/models/sui/bridge/another-bridge/structs.ts b/src/services/models/sui/bridge/another-bridge/structs.ts new file mode 100644 index 00000000..c9b85ee7 --- /dev/null +++ b/src/services/models/sui/bridge/another-bridge/structs.ts @@ -0,0 +1,200 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, + ToTypeStr as ToPhantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { Bytes32 } from "../../utils/bytes32/structs"; +import { Set } from "../../utils/set/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== AnotherBridge =============================== */ + +export function isAnotherBridge(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::another_bridge::AnotherBridge`; +} + +export interface AnotherBridgeFields { + address: ToField; + tokens: ToField>>; + gasUsage: ToField<"u64">; +} + +export type AnotherBridgeReified = Reified; + +export class AnotherBridge implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::another_bridge::AnotherBridge`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = AnotherBridge.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = AnotherBridge.$isPhantom; + + readonly address: ToField; + readonly tokens: ToField>>; + readonly gasUsage: ToField<"u64">; + + private constructor(typeArgs: [], fields: AnotherBridgeFields) { + this.$fullTypeName = composeSuiType(AnotherBridge.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.address = fields.address; + this.tokens = fields.tokens; + this.gasUsage = fields.gasUsage; + } + + static reified(): AnotherBridgeReified { + return { + typeName: AnotherBridge.$typeName, + fullTypeName: composeSuiType(AnotherBridge.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: AnotherBridge.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => AnotherBridge.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => AnotherBridge.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => AnotherBridge.fromBcs(data), + bcs: AnotherBridge.bcs, + fromJSONField: (field: any) => AnotherBridge.fromJSONField(field), + fromJSON: (json: Record) => AnotherBridge.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => AnotherBridge.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => AnotherBridge.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => AnotherBridge.fetch(client, id), + new: (fields: AnotherBridgeFields) => { + return new AnotherBridge([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return AnotherBridge.reified(); + } + + static phantom(): PhantomReified> { + return phantom(AnotherBridge.reified()); + } + static get p() { + return AnotherBridge.phantom(); + } + + static get bcs() { + return bcs.struct("AnotherBridge", { + address: Bytes32.bcs, + tokens: Set.bcs, + gas_usage: bcs.u64(), + }); + } + + static fromFields(fields: Record): AnotherBridge { + return AnotherBridge.reified().new({ + address: decodeFromFields(Bytes32.reified(), fields.address), + tokens: decodeFromFields(Set.reified(reified.phantom(Bytes32.reified())), fields.tokens), + gasUsage: decodeFromFields("u64", fields.gas_usage), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): AnotherBridge { + if (!isAnotherBridge(item.type)) { + throw new Error("not a AnotherBridge type"); + } + + return AnotherBridge.reified().new({ + address: decodeFromFieldsWithTypes(Bytes32.reified(), item.fields.address), + tokens: decodeFromFieldsWithTypes(Set.reified(reified.phantom(Bytes32.reified())), item.fields.tokens), + gasUsage: decodeFromFieldsWithTypes("u64", item.fields.gas_usage), + }); + } + + static fromBcs(data: Uint8Array): AnotherBridge { + return AnotherBridge.fromFields(AnotherBridge.bcs.parse(data)); + } + + toJSONField() { + return { + address: this.address.toJSONField(), + tokens: this.tokens.toJSONField(), + gasUsage: this.gasUsage.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): AnotherBridge { + return AnotherBridge.reified().new({ + address: decodeFromJSONField(Bytes32.reified(), field.address), + tokens: decodeFromJSONField(Set.reified(reified.phantom(Bytes32.reified())), field.tokens), + gasUsage: decodeFromJSONField("u64", field.gasUsage), + }); + } + + static fromJSON(json: Record): AnotherBridge { + if (json.$typeName !== AnotherBridge.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return AnotherBridge.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): AnotherBridge { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isAnotherBridge(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a AnotherBridge object`); + } + return AnotherBridge.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): AnotherBridge { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isAnotherBridge(data.bcs.type)) { + throw new Error(`object at is not a AnotherBridge object`); + } + + return AnotherBridge.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return AnotherBridge.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching AnotherBridge object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isAnotherBridge(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a AnotherBridge object`); + } + + return AnotherBridge.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/bridge/bridge-interface/functions.ts b/src/services/models/sui/bridge/bridge-interface/functions.ts new file mode 100644 index 00000000..68bf74dd --- /dev/null +++ b/src/services/models/sui/bridge/bridge-interface/functions.ts @@ -0,0 +1,722 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function destroyEmpty(tx: Transaction, typeArg: string, userDeposit: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::destroy_empty`, + typeArguments: [typeArg], + arguments: [obj(tx, userDeposit)], + }); +} + +export interface SwapArgs { + bridge: TransactionObjectInput; + coin: TransactionObjectInput; + receiveAmountMin: bigint | TransactionArgument; +} + +export function swap(tx: Transaction, typeArgs: [string, string], args: SwapArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::swap`, + typeArguments: typeArgs, + arguments: [obj(tx, args.bridge), obj(tx, args.coin), pure(tx, args.receiveAmountMin, `u64`)], + }); +} + +export interface DepositArgs { + bridge: TransactionObjectInput; + userDeposit: TransactionObjectInput; + coin: TransactionObjectInput; +} + +export function deposit(tx: Transaction, typeArg: string, args: DepositArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::deposit`, + typeArguments: [typeArg], + arguments: [obj(tx, args.bridge), obj(tx, args.userDeposit), obj(tx, args.coin)], + }); +} + +export interface WithdrawArgs { + bridge: TransactionObjectInput; + userDeposit: TransactionObjectInput; + amountLp: bigint | TransactionArgument; +} + +export function withdraw(tx: Transaction, typeArg: string, args: WithdrawArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::withdraw`, + typeArguments: [typeArg], + arguments: [obj(tx, args.bridge), obj(tx, args.userDeposit), pure(tx, args.amountLp, `u64`)], + }); +} + +export interface DepositFeeArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; + coin: TransactionObjectInput; +} + +export function depositFee(tx: Transaction, typeArg: string, args: DepositFeeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::deposit_fee`, + typeArguments: [typeArg], + arguments: [obj(tx, args.adminCap), obj(tx, args.bridge), obj(tx, args.coin)], + }); +} + +export interface MigrateArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; +} + +export function migrate(tx: Transaction, args: MigrateArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::migrate`, + arguments: [obj(tx, args.adminCap), obj(tx, args.bridge)], + }); +} + +export interface SetGasUsageArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; + chainId: number | TransactionArgument; + value: bigint | TransactionArgument; +} + +export function setGasUsage(tx: Transaction, args: SetGasUsageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::set_gas_usage`, + arguments: [ + obj(tx, args.adminCap), + obj(tx, args.bridge), + pure(tx, args.chainId, `u8`), + pure(tx, args.value, `u64`), + ], + }); +} + +export interface WithdrawFeeArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; + amount: bigint | TransactionArgument; +} + +export function withdrawFee(tx: Transaction, typeArg: string, args: WithdrawFeeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::withdraw_fee`, + typeArguments: [typeArg], + arguments: [obj(tx, args.adminCap), obj(tx, args.bridge), pure(tx, args.amount, `u64`)], + }); +} + +export interface GasUsageArgs { + bridge: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function gasUsage(tx: Transaction, args: GasUsageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::gas_usage`, + arguments: [obj(tx, args.bridge), pure(tx, args.chainId, `u8`)], + }); +} + +export function lpAmount(tx: Transaction, typeArg: string, userDeposit: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::lp_amount`, + typeArguments: [typeArg], + arguments: [obj(tx, userDeposit)], + }); +} + +export function rewardDebt(tx: Transaction, typeArg: string, userDeposit: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::reward_debt`, + typeArguments: [typeArg], + arguments: [obj(tx, userDeposit)], + }); +} + +export interface ClaimAdminFeeArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; +} + +export function claimAdminFee(tx: Transaction, typeArg: string, args: ClaimAdminFeeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::claim_admin_fee`, + typeArguments: [typeArg], + arguments: [obj(tx, args.adminCap), obj(tx, args.bridge)], + }); +} + +export interface ClaimRewardArgs { + bridge: TransactionObjectInput; + userDeposit: TransactionObjectInput; +} + +export function claimReward(tx: Transaction, typeArg: string, args: ClaimRewardArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::claim_reward`, + typeArguments: [typeArg], + arguments: [obj(tx, args.bridge), obj(tx, args.userDeposit)], + }); +} + +export interface SetAdminFeeShareBpArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; + adminFeeShareBp: bigint | TransactionArgument; +} + +export function setAdminFeeShareBp(tx: Transaction, typeArg: string, args: SetAdminFeeShareBpArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::set_admin_fee_share_bp`, + typeArguments: [typeArg], + arguments: [obj(tx, args.adminCap), obj(tx, args.bridge), pure(tx, args.adminFeeShareBp, `u64`)], + }); +} + +export function adminFeeShareBp(tx: Transaction, typeArg: string, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::admin_fee_share_bp`, + typeArguments: [typeArg], + arguments: [obj(tx, bridge)], + }); +} + +export interface SetBalanceRatioMinBpArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; + balanceRatioMinBp: bigint | TransactionArgument; +} + +export function setBalanceRatioMinBp(tx: Transaction, typeArg: string, args: SetBalanceRatioMinBpArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::set_balance_ratio_min_bp`, + typeArguments: [typeArg], + arguments: [obj(tx, args.adminCap), obj(tx, args.bridge), pure(tx, args.balanceRatioMinBp, `u64`)], + }); +} + +export function pool(tx: Transaction, typeArg: string, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::pool`, + typeArguments: [typeArg], + arguments: [obj(tx, bridge)], + }); +} + +export interface AdjustTotalLpAmountArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; + userDeposit: TransactionObjectInput; +} + +export function adjustTotalLpAmount(tx: Transaction, typeArg: string, args: AdjustTotalLpAmountArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::adjust_total_lp_amount`, + typeArguments: [typeArg], + arguments: [obj(tx, args.adminCap), obj(tx, args.bridge), obj(tx, args.userDeposit)], + }); +} + +export function canDeposit(tx: Transaction, typeArg: string, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::can_deposit`, + typeArguments: [typeArg], + arguments: [obj(tx, bridge)], + }); +} + +export function canWithdraw(tx: Transaction, typeArg: string, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::can_withdraw`, + typeArguments: [typeArg], + arguments: [obj(tx, bridge)], + }); +} + +export function feeShare(tx: Transaction, typeArg: string, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::fee_share`, + typeArguments: [typeArg], + arguments: [obj(tx, bridge)], + }); +} + +export interface SetFeeShareArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; + feeShareBp: bigint | TransactionArgument; +} + +export function setFeeShare(tx: Transaction, typeArg: string, args: SetFeeShareArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::set_fee_share`, + typeArguments: [typeArg], + arguments: [obj(tx, args.adminCap), obj(tx, args.bridge), pure(tx, args.feeShareBp, `u64`)], + }); +} + +export interface StartDepositArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; +} + +export function startDeposit(tx: Transaction, typeArg: string, args: StartDepositArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::start_deposit`, + typeArguments: [typeArg], + arguments: [obj(tx, args.adminCap), obj(tx, args.bridge)], + }); +} + +export interface StartWithdrawArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; +} + +export function startWithdraw(tx: Transaction, typeArg: string, args: StartWithdrawArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::start_withdraw`, + typeArguments: [typeArg], + arguments: [obj(tx, args.adminCap), obj(tx, args.bridge)], + }); +} + +export interface StopDepositArgs { + stopCap: TransactionObjectInput; + bridge: TransactionObjectInput; +} + +export function stopDeposit(tx: Transaction, typeArg: string, args: StopDepositArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::stop_deposit`, + typeArguments: [typeArg], + arguments: [obj(tx, args.stopCap), obj(tx, args.bridge)], + }); +} + +export interface StopWithdrawArgs { + stopCap: TransactionObjectInput; + bridge: TransactionObjectInput; +} + +export function stopWithdraw(tx: Transaction, typeArg: string, args: StopWithdrawArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::stop_withdraw`, + typeArguments: [typeArg], + arguments: [obj(tx, args.stopCap), obj(tx, args.bridge)], + }); +} + +export interface AddBridgeArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; + chainId: number | TransactionArgument; + bridgeAddress: TransactionObjectInput; +} + +export function addBridge(tx: Transaction, args: AddBridgeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::add_bridge`, + arguments: [ + obj(tx, args.adminCap), + obj(tx, args.bridge), + pure(tx, args.chainId, `u8`), + obj(tx, args.bridgeAddress), + ], + }); +} + +export interface AddBridgeTokenArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; + chainId: number | TransactionArgument; + tokenAddress: TransactionObjectInput; +} + +export function addBridgeToken(tx: Transaction, args: AddBridgeTokenArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::add_bridge_token`, + arguments: [obj(tx, args.adminCap), obj(tx, args.bridge), pure(tx, args.chainId, `u8`), obj(tx, args.tokenAddress)], + }); +} + +export interface AddPoolArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; + pool: TransactionObjectInput; +} + +export function addPool(tx: Transaction, typeArg: string, args: AddPoolArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::add_pool`, + typeArguments: [typeArg], + arguments: [obj(tx, args.adminCap), obj(tx, args.bridge), obj(tx, args.pool)], + }); +} + +export function canSwap(tx: Transaction, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::can_swap`, + arguments: [obj(tx, bridge)], + }); +} + +export function feeValue(tx: Transaction, typeArg: string, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::fee_value`, + typeArguments: [typeArg], + arguments: [obj(tx, bridge)], + }); +} + +export interface GetBridgeAllbridgeCostArgs { + bridge: TransactionObjectInput; + messenger: TransactionObjectInput; + gasOracle: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getBridgeAllbridgeCost(tx: Transaction, args: GetBridgeAllbridgeCostArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::get_bridge_allbridge_cost`, + arguments: [obj(tx, args.bridge), obj(tx, args.messenger), obj(tx, args.gasOracle), pure(tx, args.chainId, `u8`)], + }); +} + +export interface GetBridgeCostArgs { + bridge: TransactionObjectInput; + gasOracle: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getBridgeCost(tx: Transaction, args: GetBridgeCostArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::get_bridge_cost`, + arguments: [obj(tx, args.bridge), obj(tx, args.gasOracle), pure(tx, args.chainId, `u8`)], + }); +} + +export interface GetBridgeWormholeCostArgs { + bridge: TransactionObjectInput; + messenger: TransactionObjectInput; + wormholeState: TransactionObjectInput; + gasOracle: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getBridgeWormholeCost(tx: Transaction, args: GetBridgeWormholeCostArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::get_bridge_wormhole_cost`, + arguments: [ + obj(tx, args.bridge), + obj(tx, args.messenger), + obj(tx, args.wormholeState), + obj(tx, args.gasOracle), + pure(tx, args.chainId, `u8`), + ], + }); +} + +export interface IsProcessedMessageArgs { + bridge: TransactionObjectInput; + message: TransactionObjectInput; +} + +export function isProcessedMessage(tx: Transaction, args: IsProcessedMessageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::is_processed_message`, + arguments: [obj(tx, args.bridge), obj(tx, args.message)], + }); +} + +export interface ReceiveTokensWormholeArgs { + bridge: TransactionObjectInput; + messenger: TransactionObjectInput; + amount: bigint | TransactionArgument; + recipient: TransactionObjectInput; + sourceChainId: number | TransactionArgument; + nonce: bigint | TransactionArgument; + receiveAmountMin: bigint | TransactionArgument; + extraGasCoin: TransactionObjectInput; +} + +export function receiveTokensWormhole(tx: Transaction, typeArg: string, args: ReceiveTokensWormholeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::receive_tokens_wormhole`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.bridge), + obj(tx, args.messenger), + pure(tx, args.amount, `u64`), + obj(tx, args.recipient), + pure(tx, args.sourceChainId, `u8`), + pure(tx, args.nonce, `u256`), + pure(tx, args.receiveAmountMin, `u64`), + obj(tx, args.extraGasCoin), + ], + }); +} + +export interface RemoveBridgeArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function removeBridge(tx: Transaction, args: RemoveBridgeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::remove_bridge`, + arguments: [obj(tx, args.adminCap), obj(tx, args.bridge), pure(tx, args.chainId, `u8`)], + }); +} + +export interface RemoveBridgeTokenArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; + chainId: number | TransactionArgument; + tokenAddress: TransactionObjectInput; +} + +export function removeBridgeToken(tx: Transaction, args: RemoveBridgeTokenArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::remove_bridge_token`, + arguments: [obj(tx, args.adminCap), obj(tx, args.bridge), pure(tx, args.chainId, `u8`), obj(tx, args.tokenAddress)], + }); +} + +export interface SetRebalancerArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; + rebalancer: string | TransactionArgument; +} + +export function setRebalancer(tx: Transaction, args: SetRebalancerArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::set_rebalancer`, + arguments: [obj(tx, args.adminCap), obj(tx, args.bridge), pure(tx, args.rebalancer, `address`)], + }); +} + +export interface StartSwapArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; +} + +export function startSwap(tx: Transaction, args: StartSwapArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::start_swap`, + arguments: [obj(tx, args.adminCap), obj(tx, args.bridge)], + }); +} + +export interface StopSwapArgs { + stopSwapCap: TransactionObjectInput; + bridge: TransactionObjectInput; +} + +export function stopSwap(tx: Transaction, args: StopSwapArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::stop_swap`, + arguments: [obj(tx, args.stopSwapCap), obj(tx, args.bridge)], + }); +} + +export interface SwapAndBridgeWormholeArgs { + bridge: TransactionObjectInput; + messenger: TransactionObjectInput; + wormholeState: TransactionObjectInput; + theClock: TransactionObjectInput; + gasOracle: TransactionObjectInput; + amount: TransactionObjectInput; + recipient: TransactionObjectInput; + destinationChainId: number | TransactionArgument; + receiveToken: TransactionObjectInput; + nonce: bigint | TransactionArgument; + feeSuiCoin: TransactionObjectInput; + feeTokenCoin: TransactionObjectInput; +} + +export function swapAndBridgeWormhole(tx: Transaction, typeArg: string, args: SwapAndBridgeWormholeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::swap_and_bridge_wormhole`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.bridge), + obj(tx, args.messenger), + obj(tx, args.wormholeState), + obj(tx, args.theClock), + obj(tx, args.gasOracle), + obj(tx, args.amount), + obj(tx, args.recipient), + pure(tx, args.destinationChainId, `u8`), + obj(tx, args.receiveToken), + pure(tx, args.nonce, `u256`), + obj(tx, args.feeSuiCoin), + obj(tx, args.feeTokenCoin), + ], + }); +} + +export interface NewPoolArgs { + adminCap: TransactionObjectInput; + coinMetadata: TransactionObjectInput; + a: bigint | TransactionArgument; + feeShareBp: bigint | TransactionArgument; +} + +export function newPool(tx: Transaction, typeArg: string, args: NewPoolArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::new_pool`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.adminCap), + obj(tx, args.coinMetadata), + pure(tx, args.a, `u64`), + pure(tx, args.feeShareBp, `u64`), + ], + }); +} + +export function newUserDeposit(tx: Transaction, typeArg: string) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::new_user_deposit`, + typeArguments: [typeArg], + arguments: [], + }); +} + +export function poolA(tx: Transaction, typeArg: string, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::pool_a`, + typeArguments: [typeArg], + arguments: [obj(tx, bridge)], + }); +} + +export function poolBalance(tx: Transaction, typeArg: string, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::pool_balance`, + typeArguments: [typeArg], + arguments: [obj(tx, bridge)], + }); +} + +export function poolD(tx: Transaction, typeArg: string, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::pool_d`, + typeArguments: [typeArg], + arguments: [obj(tx, bridge)], + }); +} + +export function poolDecimals(tx: Transaction, typeArg: string, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::pool_decimals`, + typeArguments: [typeArg], + arguments: [obj(tx, bridge)], + }); +} + +export function poolLpSupply(tx: Transaction, typeArg: string, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::pool_lp_supply`, + typeArguments: [typeArg], + arguments: [obj(tx, bridge)], + }); +} + +export interface PoolPendingRewardsArgs { + bridge: TransactionObjectInput; + userDeposit: TransactionObjectInput; +} + +export function poolPendingRewards(tx: Transaction, typeArg: string, args: PoolPendingRewardsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::pool_pending_rewards`, + typeArguments: [typeArg], + arguments: [obj(tx, args.bridge), obj(tx, args.userDeposit)], + }); +} + +export function poolTokenBalance(tx: Transaction, typeArg: string, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::pool_token_balance`, + typeArguments: [typeArg], + arguments: [obj(tx, bridge)], + }); +} + +export function poolVusdBalance(tx: Transaction, typeArg: string, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::pool_vusd_balance`, + typeArguments: [typeArg], + arguments: [obj(tx, bridge)], + }); +} + +export interface ReceiveTokensArgs { + bridge: TransactionObjectInput; + messenger: TransactionObjectInput; + amount: bigint | TransactionArgument; + recipient: TransactionObjectInput; + sourceChainId: number | TransactionArgument; + nonce: bigint | TransactionArgument; + receiveAmountMin: bigint | TransactionArgument; + extraGasCoin: TransactionObjectInput; +} + +export function receiveTokens(tx: Transaction, typeArg: string, args: ReceiveTokensArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::receive_tokens`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.bridge), + obj(tx, args.messenger), + pure(tx, args.amount, `u64`), + obj(tx, args.recipient), + pure(tx, args.sourceChainId, `u8`), + pure(tx, args.nonce, `u256`), + pure(tx, args.receiveAmountMin, `u64`), + obj(tx, args.extraGasCoin), + ], + }); +} + +export interface SwapAndBridgeArgs { + bridge: TransactionObjectInput; + messenger: TransactionObjectInput; + gasOracle: TransactionObjectInput; + amount: TransactionObjectInput; + recipient: TransactionObjectInput; + destinationChainId: number | TransactionArgument; + receiveToken: TransactionObjectInput; + nonce: bigint | TransactionArgument; + feeSuiCoin: TransactionObjectInput; + feeTokenCoin: TransactionObjectInput; +} + +export function swapAndBridge(tx: Transaction, typeArg: string, args: SwapAndBridgeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge_interface::swap_and_bridge`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.bridge), + obj(tx, args.messenger), + obj(tx, args.gasOracle), + obj(tx, args.amount), + obj(tx, args.recipient), + pure(tx, args.destinationChainId, `u8`), + obj(tx, args.receiveToken), + pure(tx, args.nonce, `u256`), + obj(tx, args.feeSuiCoin), + obj(tx, args.feeTokenCoin), + ], + }); +} diff --git a/src/services/models/sui/bridge/bridge/functions.ts b/src/services/models/sui/bridge/bridge/functions.ts new file mode 100644 index 00000000..5eda0773 --- /dev/null +++ b/src/services/models/sui/bridge/bridge/functions.ts @@ -0,0 +1,423 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface SwapArgs { + bridge: TransactionObjectInput; + coin: TransactionObjectInput; + receiveAmountMin: bigint | TransactionArgument; +} + +export function swap(tx: Transaction, typeArgs: [string, string], args: SwapArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::swap`, + typeArguments: typeArgs, + arguments: [obj(tx, args.bridge), obj(tx, args.coin), pure(tx, args.receiveAmountMin, `u64`)], + }); +} + +export interface DepositFeeArgs { + bridge: TransactionObjectInput; + coin: TransactionObjectInput; +} + +export function depositFee(tx: Transaction, typeArg: string, args: DepositFeeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::deposit_fee`, + typeArguments: [typeArg], + arguments: [obj(tx, args.bridge), obj(tx, args.coin)], + }); +} + +export function getId(tx: Transaction, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::get_id`, + arguments: [obj(tx, bridge)], + }); +} + +export function getVersion(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::get_version`, + arguments: [], + }); +} + +export function init(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::init`, + arguments: [], + }); +} + +export interface MigrateArgs { + adminCap: TransactionObjectInput; + bridge: TransactionObjectInput; +} + +export function migrate(tx: Transaction, args: MigrateArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::migrate`, + arguments: [obj(tx, args.adminCap), obj(tx, args.bridge)], + }); +} + +export interface SetGasUsageArgs { + bridge: TransactionObjectInput; + chainId: number | TransactionArgument; + value: bigint | TransactionArgument; +} + +export function setGasUsage(tx: Transaction, args: SetGasUsageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::set_gas_usage`, + arguments: [obj(tx, args.bridge), pure(tx, args.chainId, `u8`), pure(tx, args.value, `u64`)], + }); +} + +export interface WithdrawFeeArgs { + bridge: TransactionObjectInput; + amount: bigint | TransactionArgument; +} + +export function withdrawFee(tx: Transaction, typeArg: string, args: WithdrawFeeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::withdraw_fee`, + typeArguments: [typeArg], + arguments: [obj(tx, args.bridge), pure(tx, args.amount, `u64`)], + }); +} + +export interface GasUsageArgs { + bridge: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function gasUsage(tx: Transaction, args: GasUsageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::gas_usage`, + arguments: [obj(tx, args.bridge), pure(tx, args.chainId, `u8`)], + }); +} + +export function adminFeeShareBp(tx: Transaction, typeArg: string, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::admin_fee_share_bp`, + typeArguments: [typeArg], + arguments: [obj(tx, bridge)], + }); +} + +export function pool(tx: Transaction, typeArg: string, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::pool`, + typeArguments: [typeArg], + arguments: [obj(tx, bridge)], + }); +} + +export interface AddBridgeArgs { + bridge: TransactionObjectInput; + chainId: number | TransactionArgument; + bridgeAddress: TransactionObjectInput; +} + +export function addBridge(tx: Transaction, args: AddBridgeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::add_bridge`, + arguments: [obj(tx, args.bridge), pure(tx, args.chainId, `u8`), obj(tx, args.bridgeAddress)], + }); +} + +export interface AddBridgeTokenArgs { + bridge: TransactionObjectInput; + chainId: number | TransactionArgument; + tokenAddress: TransactionObjectInput; +} + +export function addBridgeToken(tx: Transaction, args: AddBridgeTokenArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::add_bridge_token`, + arguments: [obj(tx, args.bridge), pure(tx, args.chainId, `u8`), obj(tx, args.tokenAddress)], + }); +} + +export interface AddPoolArgs { + bridge: TransactionObjectInput; + pool: TransactionObjectInput; +} + +export function addPool(tx: Transaction, typeArg: string, args: AddPoolArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::add_pool`, + typeArguments: [typeArg], + arguments: [obj(tx, args.bridge), obj(tx, args.pool)], + }); +} + +export function canSwap(tx: Transaction, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::can_swap`, + arguments: [obj(tx, bridge)], + }); +} + +export function feeValue(tx: Transaction, typeArg: string, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::fee_value`, + typeArguments: [typeArg], + arguments: [obj(tx, bridge)], + }); +} + +export interface GetBridgeAllbridgeCostArgs { + bridge: TransactionObjectInput; + messenger: TransactionObjectInput; + gasOracle: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getBridgeAllbridgeCost(tx: Transaction, args: GetBridgeAllbridgeCostArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::get_bridge_allbridge_cost`, + arguments: [obj(tx, args.bridge), obj(tx, args.messenger), obj(tx, args.gasOracle), pure(tx, args.chainId, `u8`)], + }); +} + +export interface GetBridgeCostArgs { + bridge: TransactionObjectInput; + gasOracle: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getBridgeCost(tx: Transaction, args: GetBridgeCostArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::get_bridge_cost`, + arguments: [obj(tx, args.bridge), obj(tx, args.gasOracle), pure(tx, args.chainId, `u8`)], + }); +} + +export interface GetBridgeWormholeCostArgs { + bridge: TransactionObjectInput; + messenger: TransactionObjectInput; + wormholeState: TransactionObjectInput; + gasOracle: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getBridgeWormholeCost(tx: Transaction, args: GetBridgeWormholeCostArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::get_bridge_wormhole_cost`, + arguments: [ + obj(tx, args.bridge), + obj(tx, args.messenger), + obj(tx, args.wormholeState), + obj(tx, args.gasOracle), + pure(tx, args.chainId, `u8`), + ], + }); +} + +export function getPoolKey(tx: Transaction, typeArg: string) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::get_pool_key`, + typeArguments: [typeArg], + arguments: [], + }); +} + +export interface IsProcessedMessageArgs { + bridge: TransactionObjectInput; + message: TransactionObjectInput; +} + +export function isProcessedMessage(tx: Transaction, args: IsProcessedMessageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::is_processed_message`, + arguments: [obj(tx, args.bridge), obj(tx, args.message)], + }); +} + +export function poolMut(tx: Transaction, typeArg: string, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::pool_mut`, + typeArguments: [typeArg], + arguments: [obj(tx, bridge)], + }); +} + +export interface ReceiveTokensAllbridgeArgs { + bridge: TransactionObjectInput; + messenger: TransactionObjectInput; + amount: bigint | TransactionArgument; + recipient: TransactionObjectInput; + sourceChainId: number | TransactionArgument; + nonce: bigint | TransactionArgument; + receiveAmountMin: bigint | TransactionArgument; + extraGasCoin: TransactionObjectInput; +} + +export function receiveTokensAllbridge(tx: Transaction, typeArg: string, args: ReceiveTokensAllbridgeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::receive_tokens_allbridge`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.bridge), + obj(tx, args.messenger), + pure(tx, args.amount, `u64`), + obj(tx, args.recipient), + pure(tx, args.sourceChainId, `u8`), + pure(tx, args.nonce, `u256`), + pure(tx, args.receiveAmountMin, `u64`), + obj(tx, args.extraGasCoin), + ], + }); +} + +export interface ReceiveTokensWormholeArgs { + bridge: TransactionObjectInput; + messenger: TransactionObjectInput; + amount: bigint | TransactionArgument; + recipient: TransactionObjectInput; + sourceChainId: number | TransactionArgument; + nonce: bigint | TransactionArgument; + receiveAmountMin: bigint | TransactionArgument; + extraGasCoin: TransactionObjectInput; +} + +export function receiveTokensWormhole(tx: Transaction, typeArg: string, args: ReceiveTokensWormholeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::receive_tokens_wormhole`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.bridge), + obj(tx, args.messenger), + pure(tx, args.amount, `u64`), + obj(tx, args.recipient), + pure(tx, args.sourceChainId, `u8`), + pure(tx, args.nonce, `u256`), + pure(tx, args.receiveAmountMin, `u64`), + obj(tx, args.extraGasCoin), + ], + }); +} + +export interface RemoveBridgeArgs { + bridge: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function removeBridge(tx: Transaction, args: RemoveBridgeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::remove_bridge`, + arguments: [obj(tx, args.bridge), pure(tx, args.chainId, `u8`)], + }); +} + +export interface RemoveBridgeTokenArgs { + bridge: TransactionObjectInput; + chainId: number | TransactionArgument; + tokenAddress: TransactionObjectInput; +} + +export function removeBridgeToken(tx: Transaction, args: RemoveBridgeTokenArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::remove_bridge_token`, + arguments: [obj(tx, args.bridge), pure(tx, args.chainId, `u8`), obj(tx, args.tokenAddress)], + }); +} + +export interface SetRebalancerArgs { + bridge: TransactionObjectInput; + rebalancer: string | TransactionArgument; +} + +export function setRebalancer(tx: Transaction, args: SetRebalancerArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::set_rebalancer`, + arguments: [obj(tx, args.bridge), pure(tx, args.rebalancer, `address`)], + }); +} + +export function startSwap(tx: Transaction, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::start_swap`, + arguments: [obj(tx, bridge)], + }); +} + +export function stopSwap(tx: Transaction, bridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::stop_swap`, + arguments: [obj(tx, bridge)], + }); +} + +export interface SwapAndBridgeAllbridgeArgs { + bridge: TransactionObjectInput; + messenger: TransactionObjectInput; + gasOracle: TransactionObjectInput; + coin: TransactionObjectInput; + recipient: TransactionObjectInput; + destinationChainId: number | TransactionArgument; + receiveToken: TransactionObjectInput; + nonce: bigint | TransactionArgument; + feeSuiCoin: TransactionObjectInput; + feeTokenCoin: TransactionObjectInput; +} + +export function swapAndBridgeAllbridge(tx: Transaction, typeArg: string, args: SwapAndBridgeAllbridgeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::swap_and_bridge_allbridge`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.bridge), + obj(tx, args.messenger), + obj(tx, args.gasOracle), + obj(tx, args.coin), + obj(tx, args.recipient), + pure(tx, args.destinationChainId, `u8`), + obj(tx, args.receiveToken), + pure(tx, args.nonce, `u256`), + obj(tx, args.feeSuiCoin), + obj(tx, args.feeTokenCoin), + ], + }); +} + +export interface SwapAndBridgeWormholeArgs { + bridge: TransactionObjectInput; + messenger: TransactionObjectInput; + wormholeState: TransactionObjectInput; + theClock: TransactionObjectInput; + gasOracle: TransactionObjectInput; + coin: TransactionObjectInput; + recipient: TransactionObjectInput; + destinationChainId: number | TransactionArgument; + receiveToken: TransactionObjectInput; + nonce: bigint | TransactionArgument; + feeSuiCoin: TransactionObjectInput; + feeTokenCoin: TransactionObjectInput; +} + +export function swapAndBridgeWormhole(tx: Transaction, typeArg: string, args: SwapAndBridgeWormholeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bridge::swap_and_bridge_wormhole`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.bridge), + obj(tx, args.messenger), + obj(tx, args.wormholeState), + obj(tx, args.theClock), + obj(tx, args.gasOracle), + obj(tx, args.coin), + obj(tx, args.recipient), + pure(tx, args.destinationChainId, `u8`), + obj(tx, args.receiveToken), + pure(tx, args.nonce, `u256`), + obj(tx, args.feeSuiCoin), + obj(tx, args.feeTokenCoin), + ], + }); +} diff --git a/src/services/models/sui/bridge/bridge/structs.ts b/src/services/models/sui/bridge/bridge/structs.ts new file mode 100644 index 00000000..dd8c03f6 --- /dev/null +++ b/src/services/models/sui/bridge/bridge/structs.ts @@ -0,0 +1,769 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, + ToTypeStr as ToPhantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { ObjectBag } from "../../sui/object-bag/structs"; +import { UID } from "../../sui/object/structs"; +import { Table } from "../../sui/table/structs"; +import { FeeCollector } from "../../utils/fee-collector/structs"; +import { Message } from "../../utils/message/structs"; +import { Set } from "../../utils/set/structs"; +import { AnotherBridge } from "../another-bridge/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64, fromHEX, toHEX } from "@mysten/sui/utils"; + +/* ============================== AdminCap =============================== */ + +export function isAdminCap(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::bridge::AdminCap`; +} + +export interface AdminCapFields { + id: ToField; +} + +export type AdminCapReified = Reified; + +export class AdminCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::bridge::AdminCap`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = AdminCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = AdminCap.$isPhantom; + + readonly id: ToField; + + private constructor(typeArgs: [], fields: AdminCapFields) { + this.$fullTypeName = composeSuiType(AdminCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified(): AdminCapReified { + return { + typeName: AdminCap.$typeName, + fullTypeName: composeSuiType(AdminCap.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: AdminCap.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => AdminCap.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => AdminCap.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => AdminCap.fromBcs(data), + bcs: AdminCap.bcs, + fromJSONField: (field: any) => AdminCap.fromJSONField(field), + fromJSON: (json: Record) => AdminCap.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => AdminCap.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => AdminCap.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => AdminCap.fetch(client, id), + new: (fields: AdminCapFields) => { + return new AdminCap([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return AdminCap.reified(); + } + + static phantom(): PhantomReified> { + return phantom(AdminCap.reified()); + } + static get p() { + return AdminCap.phantom(); + } + + static get bcs() { + return bcs.struct("AdminCap", { + id: UID.bcs, + }); + } + + static fromFields(fields: Record): AdminCap { + return AdminCap.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): AdminCap { + if (!isAdminCap(item.type)) { + throw new Error("not a AdminCap type"); + } + + return AdminCap.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + }); + } + + static fromBcs(data: Uint8Array): AdminCap { + return AdminCap.fromFields(AdminCap.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): AdminCap { + return AdminCap.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + }); + } + + static fromJSON(json: Record): AdminCap { + if (json.$typeName !== AdminCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return AdminCap.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): AdminCap { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isAdminCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a AdminCap object`); + } + return AdminCap.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): AdminCap { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isAdminCap(data.bcs.type)) { + throw new Error(`object at is not a AdminCap object`); + } + + return AdminCap.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return AdminCap.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching AdminCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isAdminCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a AdminCap object`); + } + + return AdminCap.fromSuiObjectData(res.data); + } +} + +/* ============================== Bridge =============================== */ + +export function isBridge(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::bridge::Bridge`; +} + +export interface BridgeFields { + id: ToField; + pools: ToField; + otherBridges: ToField>>; + processedMessages: ToField>>; + sentMessages: ToField>>; + feeCollector: ToField>>; + feeCollectorCap: ToField; + rebalancer: ToField<"address">; + canSwap: ToField<"bool">; +} + +export type BridgeReified = Reified; + +export class Bridge implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::bridge::Bridge`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Bridge.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Bridge.$isPhantom; + + readonly id: ToField; + readonly pools: ToField; + readonly otherBridges: ToField>>; + readonly processedMessages: ToField>>; + readonly sentMessages: ToField>>; + readonly feeCollector: ToField>>; + readonly feeCollectorCap: ToField; + readonly rebalancer: ToField<"address">; + readonly canSwap: ToField<"bool">; + + private constructor(typeArgs: [], fields: BridgeFields) { + this.$fullTypeName = composeSuiType(Bridge.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.pools = fields.pools; + this.otherBridges = fields.otherBridges; + this.processedMessages = fields.processedMessages; + this.sentMessages = fields.sentMessages; + this.feeCollector = fields.feeCollector; + this.feeCollectorCap = fields.feeCollectorCap; + this.rebalancer = fields.rebalancer; + this.canSwap = fields.canSwap; + } + + static reified(): BridgeReified { + return { + typeName: Bridge.$typeName, + fullTypeName: composeSuiType(Bridge.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Bridge.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Bridge.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Bridge.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Bridge.fromBcs(data), + bcs: Bridge.bcs, + fromJSONField: (field: any) => Bridge.fromJSONField(field), + fromJSON: (json: Record) => Bridge.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Bridge.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Bridge.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Bridge.fetch(client, id), + new: (fields: BridgeFields) => { + return new Bridge([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Bridge.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Bridge.reified()); + } + static get p() { + return Bridge.phantom(); + } + + static get bcs() { + return bcs.struct("Bridge", { + id: UID.bcs, + pools: ObjectBag.bcs, + other_bridges: Table.bcs, + processed_messages: Set.bcs, + sent_messages: Set.bcs, + fee_collector: FeeCollector.bcs, + fee_collector_cap: FeeCollectorCap.bcs, + rebalancer: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + can_swap: bcs.bool(), + }); + } + + static fromFields(fields: Record): Bridge { + return Bridge.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + pools: decodeFromFields(ObjectBag.reified(), fields.pools), + otherBridges: decodeFromFields( + Table.reified(reified.phantom("u8"), reified.phantom(AnotherBridge.reified())), + fields.other_bridges + ), + processedMessages: decodeFromFields(Set.reified(reified.phantom(Message.reified())), fields.processed_messages), + sentMessages: decodeFromFields(Set.reified(reified.phantom(Message.reified())), fields.sent_messages), + feeCollector: decodeFromFields( + FeeCollector.reified(reified.phantom(FeeCollectorCap.reified())), + fields.fee_collector + ), + feeCollectorCap: decodeFromFields(FeeCollectorCap.reified(), fields.fee_collector_cap), + rebalancer: decodeFromFields("address", fields.rebalancer), + canSwap: decodeFromFields("bool", fields.can_swap), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Bridge { + if (!isBridge(item.type)) { + throw new Error("not a Bridge type"); + } + + return Bridge.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + pools: decodeFromFieldsWithTypes(ObjectBag.reified(), item.fields.pools), + otherBridges: decodeFromFieldsWithTypes( + Table.reified(reified.phantom("u8"), reified.phantom(AnotherBridge.reified())), + item.fields.other_bridges + ), + processedMessages: decodeFromFieldsWithTypes( + Set.reified(reified.phantom(Message.reified())), + item.fields.processed_messages + ), + sentMessages: decodeFromFieldsWithTypes( + Set.reified(reified.phantom(Message.reified())), + item.fields.sent_messages + ), + feeCollector: decodeFromFieldsWithTypes( + FeeCollector.reified(reified.phantom(FeeCollectorCap.reified())), + item.fields.fee_collector + ), + feeCollectorCap: decodeFromFieldsWithTypes(FeeCollectorCap.reified(), item.fields.fee_collector_cap), + rebalancer: decodeFromFieldsWithTypes("address", item.fields.rebalancer), + canSwap: decodeFromFieldsWithTypes("bool", item.fields.can_swap), + }); + } + + static fromBcs(data: Uint8Array): Bridge { + return Bridge.fromFields(Bridge.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + pools: this.pools.toJSONField(), + otherBridges: this.otherBridges.toJSONField(), + processedMessages: this.processedMessages.toJSONField(), + sentMessages: this.sentMessages.toJSONField(), + feeCollector: this.feeCollector.toJSONField(), + feeCollectorCap: this.feeCollectorCap.toJSONField(), + rebalancer: this.rebalancer, + canSwap: this.canSwap, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Bridge { + return Bridge.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + pools: decodeFromJSONField(ObjectBag.reified(), field.pools), + otherBridges: decodeFromJSONField( + Table.reified(reified.phantom("u8"), reified.phantom(AnotherBridge.reified())), + field.otherBridges + ), + processedMessages: decodeFromJSONField(Set.reified(reified.phantom(Message.reified())), field.processedMessages), + sentMessages: decodeFromJSONField(Set.reified(reified.phantom(Message.reified())), field.sentMessages), + feeCollector: decodeFromJSONField( + FeeCollector.reified(reified.phantom(FeeCollectorCap.reified())), + field.feeCollector + ), + feeCollectorCap: decodeFromJSONField(FeeCollectorCap.reified(), field.feeCollectorCap), + rebalancer: decodeFromJSONField("address", field.rebalancer), + canSwap: decodeFromJSONField("bool", field.canSwap), + }); + } + + static fromJSON(json: Record): Bridge { + if (json.$typeName !== Bridge.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Bridge.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Bridge { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isBridge(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Bridge object`); + } + return Bridge.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Bridge { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isBridge(data.bcs.type)) { + throw new Error(`object at is not a Bridge object`); + } + + return Bridge.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Bridge.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Bridge object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isBridge(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Bridge object`); + } + + return Bridge.fromSuiObjectData(res.data); + } +} + +/* ============================== FeeCollectorCap =============================== */ + +export function isFeeCollectorCap(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::bridge::FeeCollectorCap`; +} + +export interface FeeCollectorCapFields { + dummyField: ToField<"bool">; +} + +export type FeeCollectorCapReified = Reified; + +export class FeeCollectorCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::bridge::FeeCollectorCap`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = FeeCollectorCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = FeeCollectorCap.$isPhantom; + + readonly dummyField: ToField<"bool">; + + private constructor(typeArgs: [], fields: FeeCollectorCapFields) { + this.$fullTypeName = composeSuiType(FeeCollectorCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.dummyField = fields.dummyField; + } + + static reified(): FeeCollectorCapReified { + return { + typeName: FeeCollectorCap.$typeName, + fullTypeName: composeSuiType(FeeCollectorCap.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: FeeCollectorCap.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => FeeCollectorCap.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => FeeCollectorCap.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => FeeCollectorCap.fromBcs(data), + bcs: FeeCollectorCap.bcs, + fromJSONField: (field: any) => FeeCollectorCap.fromJSONField(field), + fromJSON: (json: Record) => FeeCollectorCap.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => FeeCollectorCap.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => FeeCollectorCap.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => FeeCollectorCap.fetch(client, id), + new: (fields: FeeCollectorCapFields) => { + return new FeeCollectorCap([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return FeeCollectorCap.reified(); + } + + static phantom(): PhantomReified> { + return phantom(FeeCollectorCap.reified()); + } + static get p() { + return FeeCollectorCap.phantom(); + } + + static get bcs() { + return bcs.struct("FeeCollectorCap", { + dummy_field: bcs.bool(), + }); + } + + static fromFields(fields: Record): FeeCollectorCap { + return FeeCollectorCap.reified().new({ + dummyField: decodeFromFields("bool", fields.dummy_field), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): FeeCollectorCap { + if (!isFeeCollectorCap(item.type)) { + throw new Error("not a FeeCollectorCap type"); + } + + return FeeCollectorCap.reified().new({ + dummyField: decodeFromFieldsWithTypes("bool", item.fields.dummy_field), + }); + } + + static fromBcs(data: Uint8Array): FeeCollectorCap { + return FeeCollectorCap.fromFields(FeeCollectorCap.bcs.parse(data)); + } + + toJSONField() { + return { + dummyField: this.dummyField, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): FeeCollectorCap { + return FeeCollectorCap.reified().new({ + dummyField: decodeFromJSONField("bool", field.dummyField), + }); + } + + static fromJSON(json: Record): FeeCollectorCap { + if (json.$typeName !== FeeCollectorCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return FeeCollectorCap.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): FeeCollectorCap { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isFeeCollectorCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a FeeCollectorCap object`); + } + return FeeCollectorCap.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): FeeCollectorCap { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isFeeCollectorCap(data.bcs.type)) { + throw new Error(`object at is not a FeeCollectorCap object`); + } + + return FeeCollectorCap.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return FeeCollectorCap.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching FeeCollectorCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isFeeCollectorCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a FeeCollectorCap object`); + } + + return FeeCollectorCap.fromSuiObjectData(res.data); + } +} + +/* ============================== StopSwapCap =============================== */ + +export function isStopSwapCap(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::bridge::StopSwapCap`; +} + +export interface StopSwapCapFields { + id: ToField; +} + +export type StopSwapCapReified = Reified; + +export class StopSwapCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::bridge::StopSwapCap`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = StopSwapCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = StopSwapCap.$isPhantom; + + readonly id: ToField; + + private constructor(typeArgs: [], fields: StopSwapCapFields) { + this.$fullTypeName = composeSuiType(StopSwapCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified(): StopSwapCapReified { + return { + typeName: StopSwapCap.$typeName, + fullTypeName: composeSuiType(StopSwapCap.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: StopSwapCap.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => StopSwapCap.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => StopSwapCap.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => StopSwapCap.fromBcs(data), + bcs: StopSwapCap.bcs, + fromJSONField: (field: any) => StopSwapCap.fromJSONField(field), + fromJSON: (json: Record) => StopSwapCap.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => StopSwapCap.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => StopSwapCap.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => StopSwapCap.fetch(client, id), + new: (fields: StopSwapCapFields) => { + return new StopSwapCap([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return StopSwapCap.reified(); + } + + static phantom(): PhantomReified> { + return phantom(StopSwapCap.reified()); + } + static get p() { + return StopSwapCap.phantom(); + } + + static get bcs() { + return bcs.struct("StopSwapCap", { + id: UID.bcs, + }); + } + + static fromFields(fields: Record): StopSwapCap { + return StopSwapCap.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): StopSwapCap { + if (!isStopSwapCap(item.type)) { + throw new Error("not a StopSwapCap type"); + } + + return StopSwapCap.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + }); + } + + static fromBcs(data: Uint8Array): StopSwapCap { + return StopSwapCap.fromFields(StopSwapCap.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): StopSwapCap { + return StopSwapCap.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + }); + } + + static fromJSON(json: Record): StopSwapCap { + if (json.$typeName !== StopSwapCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return StopSwapCap.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): StopSwapCap { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isStopSwapCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a StopSwapCap object`); + } + return StopSwapCap.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): StopSwapCap { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isStopSwapCap(data.bcs.type)) { + throw new Error(`object at is not a StopSwapCap object`); + } + + return StopSwapCap.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return StopSwapCap.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching StopSwapCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isStopSwapCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a StopSwapCap object`); + } + + return StopSwapCap.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/bridge/events/functions.ts b/src/services/models/sui/bridge/events/functions.ts new file mode 100644 index 00000000..9aef3a7a --- /dev/null +++ b/src/services/models/sui/bridge/events/functions.ts @@ -0,0 +1,157 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface DepositEventArgs { + amount: bigint | TransactionArgument; + lpAmount: bigint | TransactionArgument; +} + +export function depositEvent(tx: Transaction, typeArg: string, args: DepositEventArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::events::deposit_event`, + typeArguments: [typeArg], + arguments: [pure(tx, args.amount, `u64`), pure(tx, args.lpAmount, `u64`)], + }); +} + +export interface ReceiveFeeEventArgs { + userPaySui: bigint | TransactionArgument; + userPayStable: bigint | TransactionArgument; + totalPaySui: bigint | TransactionArgument; + bridgeFeeSui: bigint | TransactionArgument; + messengerFeeSui: bigint | TransactionArgument; + totalFeeSui: bigint | TransactionArgument; +} + +export function receiveFeeEvent(tx: Transaction, args: ReceiveFeeEventArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::events::receive_fee_event`, + arguments: [ + pure(tx, args.userPaySui, `u64`), + pure(tx, args.userPayStable, `u64`), + pure(tx, args.totalPaySui, `u64`), + pure(tx, args.bridgeFeeSui, `u64`), + pure(tx, args.messengerFeeSui, `u64`), + pure(tx, args.totalFeeSui, `u64`), + ], + }); +} + +export function rewardsClaimedEvent(tx: Transaction, typeArg: string, amount: bigint | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::events::rewards_claimed_event`, + typeArguments: [typeArg], + arguments: [pure(tx, amount, `u64`)], + }); +} + +export interface SwappedEventArgs { + sentAmount: bigint | TransactionArgument; + receivedAmount: bigint | TransactionArgument; + sender: string | TransactionArgument; +} + +export function swappedEvent(tx: Transaction, typeArgs: [string, string], args: SwappedEventArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::events::swapped_event`, + typeArguments: typeArgs, + arguments: [ + pure(tx, args.sentAmount, `u64`), + pure(tx, args.receivedAmount, `u64`), + pure(tx, args.sender, `address`), + ], + }); +} + +export interface SwappedFromVusdEventArgs { + amount: bigint | TransactionArgument; + vusdAmount: bigint | TransactionArgument; + fee: bigint | TransactionArgument; +} + +export function swappedFromVusdEvent(tx: Transaction, typeArg: string, args: SwappedFromVusdEventArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::events::swapped_from_vusd_event`, + typeArguments: [typeArg], + arguments: [pure(tx, args.amount, `u64`), pure(tx, args.vusdAmount, `u64`), pure(tx, args.fee, `u64`)], + }); +} + +export interface SwappedToVusdEventArgs { + amount: bigint | TransactionArgument; + vusdAmount: bigint | TransactionArgument; + fee: bigint | TransactionArgument; +} + +export function swappedToVusdEvent(tx: Transaction, typeArg: string, args: SwappedToVusdEventArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::events::swapped_to_vusd_event`, + typeArguments: [typeArg], + arguments: [pure(tx, args.amount, `u64`), pure(tx, args.vusdAmount, `u64`), pure(tx, args.fee, `u64`)], + }); +} + +export interface TokensReceivedEventArgs { + amount: bigint | TransactionArgument; + extraGasAmount: bigint | TransactionArgument; + recipient: string | TransactionArgument; + nonce: bigint | TransactionArgument; + messenger: TransactionObjectInput; + message: TransactionObjectInput; +} + +export function tokensReceivedEvent(tx: Transaction, typeArg: string, args: TokensReceivedEventArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::events::tokens_received_event`, + typeArguments: [typeArg], + arguments: [ + pure(tx, args.amount, `u64`), + pure(tx, args.extraGasAmount, `u64`), + pure(tx, args.recipient, `address`), + pure(tx, args.nonce, `u256`), + obj(tx, args.messenger), + obj(tx, args.message), + ], + }); +} + +export interface TokensSentEventArgs { + vusdAmount: bigint | TransactionArgument; + sender: string | TransactionArgument; + recipient: TransactionObjectInput; + destinationChainId: number | TransactionArgument; + receiveToken: TransactionObjectInput; + nonce: bigint | TransactionArgument; + messenger: TransactionObjectInput; +} + +export function tokensSentEvent(tx: Transaction, typeArg: string, args: TokensSentEventArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::events::tokens_sent_event`, + typeArguments: [typeArg], + arguments: [ + pure(tx, args.vusdAmount, `u64`), + pure(tx, args.sender, `address`), + obj(tx, args.recipient), + pure(tx, args.destinationChainId, `u8`), + obj(tx, args.receiveToken), + pure(tx, args.nonce, `u256`), + obj(tx, args.messenger), + ], + }); +} + +export interface WithdrawEventArgs { + amount: bigint | TransactionArgument; + lpAmount: bigint | TransactionArgument; +} + +export function withdrawEvent(tx: Transaction, typeArg: string, args: WithdrawEventArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::events::withdraw_event`, + typeArguments: [typeArg], + arguments: [pure(tx, args.amount, `u64`), pure(tx, args.lpAmount, `u64`)], + }); +} diff --git a/src/services/models/sui/bridge/events/structs.ts b/src/services/models/sui/bridge/events/structs.ts new file mode 100644 index 00000000..40243d8a --- /dev/null +++ b/src/services/models/sui/bridge/events/structs.ts @@ -0,0 +1,1758 @@ +// @ts-nocheck +import { String } from "../../_dependencies/source/0x1/ascii/structs"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64, fromHEX, toHEX } from "@mysten/sui/utils"; + +/* ============================== DepositEvent =============================== */ + +export function isDepositEvent(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::events::DepositEvent`; +} + +export interface DepositEventFields { + token: ToField; + amount: ToField<"u64">; + lpAmount: ToField<"u64">; +} + +export type DepositEventReified = Reified; + +export class DepositEvent implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::events::DepositEvent`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = DepositEvent.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = DepositEvent.$isPhantom; + + readonly token: ToField; + readonly amount: ToField<"u64">; + readonly lpAmount: ToField<"u64">; + + private constructor(typeArgs: [], fields: DepositEventFields) { + this.$fullTypeName = composeSuiType(DepositEvent.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.token = fields.token; + this.amount = fields.amount; + this.lpAmount = fields.lpAmount; + } + + static reified(): DepositEventReified { + return { + typeName: DepositEvent.$typeName, + fullTypeName: composeSuiType(DepositEvent.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: DepositEvent.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => DepositEvent.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => DepositEvent.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => DepositEvent.fromBcs(data), + bcs: DepositEvent.bcs, + fromJSONField: (field: any) => DepositEvent.fromJSONField(field), + fromJSON: (json: Record) => DepositEvent.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => DepositEvent.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => DepositEvent.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => DepositEvent.fetch(client, id), + new: (fields: DepositEventFields) => { + return new DepositEvent([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return DepositEvent.reified(); + } + + static phantom(): PhantomReified> { + return phantom(DepositEvent.reified()); + } + static get p() { + return DepositEvent.phantom(); + } + + static get bcs() { + return bcs.struct("DepositEvent", { + token: String.bcs, + amount: bcs.u64(), + lp_amount: bcs.u64(), + }); + } + + static fromFields(fields: Record): DepositEvent { + return DepositEvent.reified().new({ + token: decodeFromFields(String.reified(), fields.token), + amount: decodeFromFields("u64", fields.amount), + lpAmount: decodeFromFields("u64", fields.lp_amount), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): DepositEvent { + if (!isDepositEvent(item.type)) { + throw new Error("not a DepositEvent type"); + } + + return DepositEvent.reified().new({ + token: decodeFromFieldsWithTypes(String.reified(), item.fields.token), + amount: decodeFromFieldsWithTypes("u64", item.fields.amount), + lpAmount: decodeFromFieldsWithTypes("u64", item.fields.lp_amount), + }); + } + + static fromBcs(data: Uint8Array): DepositEvent { + return DepositEvent.fromFields(DepositEvent.bcs.parse(data)); + } + + toJSONField() { + return { + token: this.token, + amount: this.amount.toString(), + lpAmount: this.lpAmount.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): DepositEvent { + return DepositEvent.reified().new({ + token: decodeFromJSONField(String.reified(), field.token), + amount: decodeFromJSONField("u64", field.amount), + lpAmount: decodeFromJSONField("u64", field.lpAmount), + }); + } + + static fromJSON(json: Record): DepositEvent { + if (json.$typeName !== DepositEvent.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return DepositEvent.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): DepositEvent { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isDepositEvent(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a DepositEvent object`); + } + return DepositEvent.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): DepositEvent { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isDepositEvent(data.bcs.type)) { + throw new Error(`object at is not a DepositEvent object`); + } + + return DepositEvent.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return DepositEvent.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching DepositEvent object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isDepositEvent(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a DepositEvent object`); + } + + return DepositEvent.fromSuiObjectData(res.data); + } +} + +/* ============================== ReceiveFeeEvent =============================== */ + +export function isReceiveFeeEvent(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::events::ReceiveFeeEvent`; +} + +export interface ReceiveFeeEventFields { + userPaySui: ToField<"u64">; + userPayStable: ToField<"u64">; + totalPaySui: ToField<"u64">; + bridgeFeeSui: ToField<"u64">; + messengerFeeSui: ToField<"u64">; + totalFeeSui: ToField<"u64">; +} + +export type ReceiveFeeEventReified = Reified; + +export class ReceiveFeeEvent implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::events::ReceiveFeeEvent`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = ReceiveFeeEvent.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = ReceiveFeeEvent.$isPhantom; + + readonly userPaySui: ToField<"u64">; + readonly userPayStable: ToField<"u64">; + readonly totalPaySui: ToField<"u64">; + readonly bridgeFeeSui: ToField<"u64">; + readonly messengerFeeSui: ToField<"u64">; + readonly totalFeeSui: ToField<"u64">; + + private constructor(typeArgs: [], fields: ReceiveFeeEventFields) { + this.$fullTypeName = composeSuiType(ReceiveFeeEvent.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.userPaySui = fields.userPaySui; + this.userPayStable = fields.userPayStable; + this.totalPaySui = fields.totalPaySui; + this.bridgeFeeSui = fields.bridgeFeeSui; + this.messengerFeeSui = fields.messengerFeeSui; + this.totalFeeSui = fields.totalFeeSui; + } + + static reified(): ReceiveFeeEventReified { + return { + typeName: ReceiveFeeEvent.$typeName, + fullTypeName: composeSuiType(ReceiveFeeEvent.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: ReceiveFeeEvent.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => ReceiveFeeEvent.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => ReceiveFeeEvent.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => ReceiveFeeEvent.fromBcs(data), + bcs: ReceiveFeeEvent.bcs, + fromJSONField: (field: any) => ReceiveFeeEvent.fromJSONField(field), + fromJSON: (json: Record) => ReceiveFeeEvent.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => ReceiveFeeEvent.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => ReceiveFeeEvent.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => ReceiveFeeEvent.fetch(client, id), + new: (fields: ReceiveFeeEventFields) => { + return new ReceiveFeeEvent([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return ReceiveFeeEvent.reified(); + } + + static phantom(): PhantomReified> { + return phantom(ReceiveFeeEvent.reified()); + } + static get p() { + return ReceiveFeeEvent.phantom(); + } + + static get bcs() { + return bcs.struct("ReceiveFeeEvent", { + user_pay_sui: bcs.u64(), + user_pay_stable: bcs.u64(), + total_pay_sui: bcs.u64(), + bridge_fee_sui: bcs.u64(), + messenger_fee_sui: bcs.u64(), + total_fee_sui: bcs.u64(), + }); + } + + static fromFields(fields: Record): ReceiveFeeEvent { + return ReceiveFeeEvent.reified().new({ + userPaySui: decodeFromFields("u64", fields.user_pay_sui), + userPayStable: decodeFromFields("u64", fields.user_pay_stable), + totalPaySui: decodeFromFields("u64", fields.total_pay_sui), + bridgeFeeSui: decodeFromFields("u64", fields.bridge_fee_sui), + messengerFeeSui: decodeFromFields("u64", fields.messenger_fee_sui), + totalFeeSui: decodeFromFields("u64", fields.total_fee_sui), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): ReceiveFeeEvent { + if (!isReceiveFeeEvent(item.type)) { + throw new Error("not a ReceiveFeeEvent type"); + } + + return ReceiveFeeEvent.reified().new({ + userPaySui: decodeFromFieldsWithTypes("u64", item.fields.user_pay_sui), + userPayStable: decodeFromFieldsWithTypes("u64", item.fields.user_pay_stable), + totalPaySui: decodeFromFieldsWithTypes("u64", item.fields.total_pay_sui), + bridgeFeeSui: decodeFromFieldsWithTypes("u64", item.fields.bridge_fee_sui), + messengerFeeSui: decodeFromFieldsWithTypes("u64", item.fields.messenger_fee_sui), + totalFeeSui: decodeFromFieldsWithTypes("u64", item.fields.total_fee_sui), + }); + } + + static fromBcs(data: Uint8Array): ReceiveFeeEvent { + return ReceiveFeeEvent.fromFields(ReceiveFeeEvent.bcs.parse(data)); + } + + toJSONField() { + return { + userPaySui: this.userPaySui.toString(), + userPayStable: this.userPayStable.toString(), + totalPaySui: this.totalPaySui.toString(), + bridgeFeeSui: this.bridgeFeeSui.toString(), + messengerFeeSui: this.messengerFeeSui.toString(), + totalFeeSui: this.totalFeeSui.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): ReceiveFeeEvent { + return ReceiveFeeEvent.reified().new({ + userPaySui: decodeFromJSONField("u64", field.userPaySui), + userPayStable: decodeFromJSONField("u64", field.userPayStable), + totalPaySui: decodeFromJSONField("u64", field.totalPaySui), + bridgeFeeSui: decodeFromJSONField("u64", field.bridgeFeeSui), + messengerFeeSui: decodeFromJSONField("u64", field.messengerFeeSui), + totalFeeSui: decodeFromJSONField("u64", field.totalFeeSui), + }); + } + + static fromJSON(json: Record): ReceiveFeeEvent { + if (json.$typeName !== ReceiveFeeEvent.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return ReceiveFeeEvent.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): ReceiveFeeEvent { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isReceiveFeeEvent(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a ReceiveFeeEvent object`); + } + return ReceiveFeeEvent.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): ReceiveFeeEvent { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isReceiveFeeEvent(data.bcs.type)) { + throw new Error(`object at is not a ReceiveFeeEvent object`); + } + + return ReceiveFeeEvent.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return ReceiveFeeEvent.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching ReceiveFeeEvent object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isReceiveFeeEvent(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a ReceiveFeeEvent object`); + } + + return ReceiveFeeEvent.fromSuiObjectData(res.data); + } +} + +/* ============================== RewardsClaimedEvent =============================== */ + +export function isRewardsClaimedEvent(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::events::RewardsClaimedEvent`; +} + +export interface RewardsClaimedEventFields { + token: ToField; + amount: ToField<"u64">; +} + +export type RewardsClaimedEventReified = Reified; + +export class RewardsClaimedEvent implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::events::RewardsClaimedEvent`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = RewardsClaimedEvent.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = RewardsClaimedEvent.$isPhantom; + + readonly token: ToField; + readonly amount: ToField<"u64">; + + private constructor(typeArgs: [], fields: RewardsClaimedEventFields) { + this.$fullTypeName = composeSuiType(RewardsClaimedEvent.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.token = fields.token; + this.amount = fields.amount; + } + + static reified(): RewardsClaimedEventReified { + return { + typeName: RewardsClaimedEvent.$typeName, + fullTypeName: composeSuiType(RewardsClaimedEvent.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: RewardsClaimedEvent.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => RewardsClaimedEvent.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => RewardsClaimedEvent.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => RewardsClaimedEvent.fromBcs(data), + bcs: RewardsClaimedEvent.bcs, + fromJSONField: (field: any) => RewardsClaimedEvent.fromJSONField(field), + fromJSON: (json: Record) => RewardsClaimedEvent.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => RewardsClaimedEvent.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => RewardsClaimedEvent.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => RewardsClaimedEvent.fetch(client, id), + new: (fields: RewardsClaimedEventFields) => { + return new RewardsClaimedEvent([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return RewardsClaimedEvent.reified(); + } + + static phantom(): PhantomReified> { + return phantom(RewardsClaimedEvent.reified()); + } + static get p() { + return RewardsClaimedEvent.phantom(); + } + + static get bcs() { + return bcs.struct("RewardsClaimedEvent", { + token: String.bcs, + amount: bcs.u64(), + }); + } + + static fromFields(fields: Record): RewardsClaimedEvent { + return RewardsClaimedEvent.reified().new({ + token: decodeFromFields(String.reified(), fields.token), + amount: decodeFromFields("u64", fields.amount), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): RewardsClaimedEvent { + if (!isRewardsClaimedEvent(item.type)) { + throw new Error("not a RewardsClaimedEvent type"); + } + + return RewardsClaimedEvent.reified().new({ + token: decodeFromFieldsWithTypes(String.reified(), item.fields.token), + amount: decodeFromFieldsWithTypes("u64", item.fields.amount), + }); + } + + static fromBcs(data: Uint8Array): RewardsClaimedEvent { + return RewardsClaimedEvent.fromFields(RewardsClaimedEvent.bcs.parse(data)); + } + + toJSONField() { + return { + token: this.token, + amount: this.amount.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): RewardsClaimedEvent { + return RewardsClaimedEvent.reified().new({ + token: decodeFromJSONField(String.reified(), field.token), + amount: decodeFromJSONField("u64", field.amount), + }); + } + + static fromJSON(json: Record): RewardsClaimedEvent { + if (json.$typeName !== RewardsClaimedEvent.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return RewardsClaimedEvent.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): RewardsClaimedEvent { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isRewardsClaimedEvent(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a RewardsClaimedEvent object`); + } + return RewardsClaimedEvent.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): RewardsClaimedEvent { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isRewardsClaimedEvent(data.bcs.type)) { + throw new Error(`object at is not a RewardsClaimedEvent object`); + } + + return RewardsClaimedEvent.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return RewardsClaimedEvent.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching RewardsClaimedEvent object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isRewardsClaimedEvent(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a RewardsClaimedEvent object`); + } + + return RewardsClaimedEvent.fromSuiObjectData(res.data); + } +} + +/* ============================== SwappedEvent =============================== */ + +export function isSwappedEvent(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::events::SwappedEvent`; +} + +export interface SwappedEventFields { + tokenFrom: ToField; + tokenTo: ToField; + sentAmount: ToField<"u64">; + receivedAmount: ToField<"u64">; + sender: ToField<"address">; +} + +export type SwappedEventReified = Reified; + +export class SwappedEvent implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::events::SwappedEvent`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = SwappedEvent.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = SwappedEvent.$isPhantom; + + readonly tokenFrom: ToField; + readonly tokenTo: ToField; + readonly sentAmount: ToField<"u64">; + readonly receivedAmount: ToField<"u64">; + readonly sender: ToField<"address">; + + private constructor(typeArgs: [], fields: SwappedEventFields) { + this.$fullTypeName = composeSuiType(SwappedEvent.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.tokenFrom = fields.tokenFrom; + this.tokenTo = fields.tokenTo; + this.sentAmount = fields.sentAmount; + this.receivedAmount = fields.receivedAmount; + this.sender = fields.sender; + } + + static reified(): SwappedEventReified { + return { + typeName: SwappedEvent.$typeName, + fullTypeName: composeSuiType(SwappedEvent.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: SwappedEvent.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => SwappedEvent.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => SwappedEvent.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => SwappedEvent.fromBcs(data), + bcs: SwappedEvent.bcs, + fromJSONField: (field: any) => SwappedEvent.fromJSONField(field), + fromJSON: (json: Record) => SwappedEvent.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => SwappedEvent.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => SwappedEvent.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => SwappedEvent.fetch(client, id), + new: (fields: SwappedEventFields) => { + return new SwappedEvent([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return SwappedEvent.reified(); + } + + static phantom(): PhantomReified> { + return phantom(SwappedEvent.reified()); + } + static get p() { + return SwappedEvent.phantom(); + } + + static get bcs() { + return bcs.struct("SwappedEvent", { + token_from: String.bcs, + token_to: String.bcs, + sent_amount: bcs.u64(), + received_amount: bcs.u64(), + sender: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + }); + } + + static fromFields(fields: Record): SwappedEvent { + return SwappedEvent.reified().new({ + tokenFrom: decodeFromFields(String.reified(), fields.token_from), + tokenTo: decodeFromFields(String.reified(), fields.token_to), + sentAmount: decodeFromFields("u64", fields.sent_amount), + receivedAmount: decodeFromFields("u64", fields.received_amount), + sender: decodeFromFields("address", fields.sender), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): SwappedEvent { + if (!isSwappedEvent(item.type)) { + throw new Error("not a SwappedEvent type"); + } + + return SwappedEvent.reified().new({ + tokenFrom: decodeFromFieldsWithTypes(String.reified(), item.fields.token_from), + tokenTo: decodeFromFieldsWithTypes(String.reified(), item.fields.token_to), + sentAmount: decodeFromFieldsWithTypes("u64", item.fields.sent_amount), + receivedAmount: decodeFromFieldsWithTypes("u64", item.fields.received_amount), + sender: decodeFromFieldsWithTypes("address", item.fields.sender), + }); + } + + static fromBcs(data: Uint8Array): SwappedEvent { + return SwappedEvent.fromFields(SwappedEvent.bcs.parse(data)); + } + + toJSONField() { + return { + tokenFrom: this.tokenFrom, + tokenTo: this.tokenTo, + sentAmount: this.sentAmount.toString(), + receivedAmount: this.receivedAmount.toString(), + sender: this.sender, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): SwappedEvent { + return SwappedEvent.reified().new({ + tokenFrom: decodeFromJSONField(String.reified(), field.tokenFrom), + tokenTo: decodeFromJSONField(String.reified(), field.tokenTo), + sentAmount: decodeFromJSONField("u64", field.sentAmount), + receivedAmount: decodeFromJSONField("u64", field.receivedAmount), + sender: decodeFromJSONField("address", field.sender), + }); + } + + static fromJSON(json: Record): SwappedEvent { + if (json.$typeName !== SwappedEvent.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return SwappedEvent.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): SwappedEvent { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isSwappedEvent(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a SwappedEvent object`); + } + return SwappedEvent.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): SwappedEvent { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isSwappedEvent(data.bcs.type)) { + throw new Error(`object at is not a SwappedEvent object`); + } + + return SwappedEvent.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return SwappedEvent.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching SwappedEvent object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isSwappedEvent(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a SwappedEvent object`); + } + + return SwappedEvent.fromSuiObjectData(res.data); + } +} + +/* ============================== SwappedFromVUsdEvent =============================== */ + +export function isSwappedFromVUsdEvent(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::events::SwappedFromVUsdEvent`; +} + +export interface SwappedFromVUsdEventFields { + token: ToField; + amount: ToField<"u64">; + vusdAmount: ToField<"u64">; + fee: ToField<"u64">; +} + +export type SwappedFromVUsdEventReified = Reified; + +export class SwappedFromVUsdEvent implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::events::SwappedFromVUsdEvent`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = SwappedFromVUsdEvent.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = SwappedFromVUsdEvent.$isPhantom; + + readonly token: ToField; + readonly amount: ToField<"u64">; + readonly vusdAmount: ToField<"u64">; + readonly fee: ToField<"u64">; + + private constructor(typeArgs: [], fields: SwappedFromVUsdEventFields) { + this.$fullTypeName = composeSuiType(SwappedFromVUsdEvent.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.token = fields.token; + this.amount = fields.amount; + this.vusdAmount = fields.vusdAmount; + this.fee = fields.fee; + } + + static reified(): SwappedFromVUsdEventReified { + return { + typeName: SwappedFromVUsdEvent.$typeName, + fullTypeName: composeSuiType(SwappedFromVUsdEvent.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: SwappedFromVUsdEvent.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => SwappedFromVUsdEvent.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => SwappedFromVUsdEvent.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => SwappedFromVUsdEvent.fromBcs(data), + bcs: SwappedFromVUsdEvent.bcs, + fromJSONField: (field: any) => SwappedFromVUsdEvent.fromJSONField(field), + fromJSON: (json: Record) => SwappedFromVUsdEvent.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => SwappedFromVUsdEvent.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => SwappedFromVUsdEvent.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => SwappedFromVUsdEvent.fetch(client, id), + new: (fields: SwappedFromVUsdEventFields) => { + return new SwappedFromVUsdEvent([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return SwappedFromVUsdEvent.reified(); + } + + static phantom(): PhantomReified> { + return phantom(SwappedFromVUsdEvent.reified()); + } + static get p() { + return SwappedFromVUsdEvent.phantom(); + } + + static get bcs() { + return bcs.struct("SwappedFromVUsdEvent", { + token: String.bcs, + amount: bcs.u64(), + vusd_amount: bcs.u64(), + fee: bcs.u64(), + }); + } + + static fromFields(fields: Record): SwappedFromVUsdEvent { + return SwappedFromVUsdEvent.reified().new({ + token: decodeFromFields(String.reified(), fields.token), + amount: decodeFromFields("u64", fields.amount), + vusdAmount: decodeFromFields("u64", fields.vusd_amount), + fee: decodeFromFields("u64", fields.fee), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): SwappedFromVUsdEvent { + if (!isSwappedFromVUsdEvent(item.type)) { + throw new Error("not a SwappedFromVUsdEvent type"); + } + + return SwappedFromVUsdEvent.reified().new({ + token: decodeFromFieldsWithTypes(String.reified(), item.fields.token), + amount: decodeFromFieldsWithTypes("u64", item.fields.amount), + vusdAmount: decodeFromFieldsWithTypes("u64", item.fields.vusd_amount), + fee: decodeFromFieldsWithTypes("u64", item.fields.fee), + }); + } + + static fromBcs(data: Uint8Array): SwappedFromVUsdEvent { + return SwappedFromVUsdEvent.fromFields(SwappedFromVUsdEvent.bcs.parse(data)); + } + + toJSONField() { + return { + token: this.token, + amount: this.amount.toString(), + vusdAmount: this.vusdAmount.toString(), + fee: this.fee.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): SwappedFromVUsdEvent { + return SwappedFromVUsdEvent.reified().new({ + token: decodeFromJSONField(String.reified(), field.token), + amount: decodeFromJSONField("u64", field.amount), + vusdAmount: decodeFromJSONField("u64", field.vusdAmount), + fee: decodeFromJSONField("u64", field.fee), + }); + } + + static fromJSON(json: Record): SwappedFromVUsdEvent { + if (json.$typeName !== SwappedFromVUsdEvent.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return SwappedFromVUsdEvent.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): SwappedFromVUsdEvent { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isSwappedFromVUsdEvent(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a SwappedFromVUsdEvent object`); + } + return SwappedFromVUsdEvent.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): SwappedFromVUsdEvent { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isSwappedFromVUsdEvent(data.bcs.type)) { + throw new Error(`object at is not a SwappedFromVUsdEvent object`); + } + + return SwappedFromVUsdEvent.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return SwappedFromVUsdEvent.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching SwappedFromVUsdEvent object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isSwappedFromVUsdEvent(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a SwappedFromVUsdEvent object`); + } + + return SwappedFromVUsdEvent.fromSuiObjectData(res.data); + } +} + +/* ============================== SwappedToVUsdEvent =============================== */ + +export function isSwappedToVUsdEvent(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::events::SwappedToVUsdEvent`; +} + +export interface SwappedToVUsdEventFields { + token: ToField; + amount: ToField<"u64">; + vusdAmount: ToField<"u64">; + fee: ToField<"u64">; +} + +export type SwappedToVUsdEventReified = Reified; + +export class SwappedToVUsdEvent implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::events::SwappedToVUsdEvent`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = SwappedToVUsdEvent.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = SwappedToVUsdEvent.$isPhantom; + + readonly token: ToField; + readonly amount: ToField<"u64">; + readonly vusdAmount: ToField<"u64">; + readonly fee: ToField<"u64">; + + private constructor(typeArgs: [], fields: SwappedToVUsdEventFields) { + this.$fullTypeName = composeSuiType(SwappedToVUsdEvent.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.token = fields.token; + this.amount = fields.amount; + this.vusdAmount = fields.vusdAmount; + this.fee = fields.fee; + } + + static reified(): SwappedToVUsdEventReified { + return { + typeName: SwappedToVUsdEvent.$typeName, + fullTypeName: composeSuiType(SwappedToVUsdEvent.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: SwappedToVUsdEvent.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => SwappedToVUsdEvent.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => SwappedToVUsdEvent.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => SwappedToVUsdEvent.fromBcs(data), + bcs: SwappedToVUsdEvent.bcs, + fromJSONField: (field: any) => SwappedToVUsdEvent.fromJSONField(field), + fromJSON: (json: Record) => SwappedToVUsdEvent.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => SwappedToVUsdEvent.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => SwappedToVUsdEvent.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => SwappedToVUsdEvent.fetch(client, id), + new: (fields: SwappedToVUsdEventFields) => { + return new SwappedToVUsdEvent([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return SwappedToVUsdEvent.reified(); + } + + static phantom(): PhantomReified> { + return phantom(SwappedToVUsdEvent.reified()); + } + static get p() { + return SwappedToVUsdEvent.phantom(); + } + + static get bcs() { + return bcs.struct("SwappedToVUsdEvent", { + token: String.bcs, + amount: bcs.u64(), + vusd_amount: bcs.u64(), + fee: bcs.u64(), + }); + } + + static fromFields(fields: Record): SwappedToVUsdEvent { + return SwappedToVUsdEvent.reified().new({ + token: decodeFromFields(String.reified(), fields.token), + amount: decodeFromFields("u64", fields.amount), + vusdAmount: decodeFromFields("u64", fields.vusd_amount), + fee: decodeFromFields("u64", fields.fee), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): SwappedToVUsdEvent { + if (!isSwappedToVUsdEvent(item.type)) { + throw new Error("not a SwappedToVUsdEvent type"); + } + + return SwappedToVUsdEvent.reified().new({ + token: decodeFromFieldsWithTypes(String.reified(), item.fields.token), + amount: decodeFromFieldsWithTypes("u64", item.fields.amount), + vusdAmount: decodeFromFieldsWithTypes("u64", item.fields.vusd_amount), + fee: decodeFromFieldsWithTypes("u64", item.fields.fee), + }); + } + + static fromBcs(data: Uint8Array): SwappedToVUsdEvent { + return SwappedToVUsdEvent.fromFields(SwappedToVUsdEvent.bcs.parse(data)); + } + + toJSONField() { + return { + token: this.token, + amount: this.amount.toString(), + vusdAmount: this.vusdAmount.toString(), + fee: this.fee.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): SwappedToVUsdEvent { + return SwappedToVUsdEvent.reified().new({ + token: decodeFromJSONField(String.reified(), field.token), + amount: decodeFromJSONField("u64", field.amount), + vusdAmount: decodeFromJSONField("u64", field.vusdAmount), + fee: decodeFromJSONField("u64", field.fee), + }); + } + + static fromJSON(json: Record): SwappedToVUsdEvent { + if (json.$typeName !== SwappedToVUsdEvent.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return SwappedToVUsdEvent.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): SwappedToVUsdEvent { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isSwappedToVUsdEvent(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a SwappedToVUsdEvent object`); + } + return SwappedToVUsdEvent.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): SwappedToVUsdEvent { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isSwappedToVUsdEvent(data.bcs.type)) { + throw new Error(`object at is not a SwappedToVUsdEvent object`); + } + + return SwappedToVUsdEvent.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return SwappedToVUsdEvent.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching SwappedToVUsdEvent object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isSwappedToVUsdEvent(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a SwappedToVUsdEvent object`); + } + + return SwappedToVUsdEvent.fromSuiObjectData(res.data); + } +} + +/* ============================== TokensReceivedEvent =============================== */ + +export function isTokensReceivedEvent(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::events::TokensReceivedEvent`; +} + +export interface TokensReceivedEventFields { + token: ToField; + amount: ToField<"u64">; + extraGasAmount: ToField<"u64">; + recipient: ToField<"address">; + nonce: ToField<"u256">; + messenger: ToField<"u8">; + message: ToField; +} + +export type TokensReceivedEventReified = Reified; + +export class TokensReceivedEvent implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::events::TokensReceivedEvent`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = TokensReceivedEvent.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = TokensReceivedEvent.$isPhantom; + + readonly token: ToField; + readonly amount: ToField<"u64">; + readonly extraGasAmount: ToField<"u64">; + readonly recipient: ToField<"address">; + readonly nonce: ToField<"u256">; + readonly messenger: ToField<"u8">; + readonly message: ToField; + + private constructor(typeArgs: [], fields: TokensReceivedEventFields) { + this.$fullTypeName = composeSuiType(TokensReceivedEvent.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.token = fields.token; + this.amount = fields.amount; + this.extraGasAmount = fields.extraGasAmount; + this.recipient = fields.recipient; + this.nonce = fields.nonce; + this.messenger = fields.messenger; + this.message = fields.message; + } + + static reified(): TokensReceivedEventReified { + return { + typeName: TokensReceivedEvent.$typeName, + fullTypeName: composeSuiType(TokensReceivedEvent.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: TokensReceivedEvent.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => TokensReceivedEvent.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => TokensReceivedEvent.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => TokensReceivedEvent.fromBcs(data), + bcs: TokensReceivedEvent.bcs, + fromJSONField: (field: any) => TokensReceivedEvent.fromJSONField(field), + fromJSON: (json: Record) => TokensReceivedEvent.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => TokensReceivedEvent.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => TokensReceivedEvent.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => TokensReceivedEvent.fetch(client, id), + new: (fields: TokensReceivedEventFields) => { + return new TokensReceivedEvent([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return TokensReceivedEvent.reified(); + } + + static phantom(): PhantomReified> { + return phantom(TokensReceivedEvent.reified()); + } + static get p() { + return TokensReceivedEvent.phantom(); + } + + static get bcs() { + return bcs.struct("TokensReceivedEvent", { + token: String.bcs, + amount: bcs.u64(), + extra_gas_amount: bcs.u64(), + recipient: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + nonce: bcs.u256(), + messenger: bcs.u8(), + message: String.bcs, + }); + } + + static fromFields(fields: Record): TokensReceivedEvent { + return TokensReceivedEvent.reified().new({ + token: decodeFromFields(String.reified(), fields.token), + amount: decodeFromFields("u64", fields.amount), + extraGasAmount: decodeFromFields("u64", fields.extra_gas_amount), + recipient: decodeFromFields("address", fields.recipient), + nonce: decodeFromFields("u256", fields.nonce), + messenger: decodeFromFields("u8", fields.messenger), + message: decodeFromFields(String.reified(), fields.message), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): TokensReceivedEvent { + if (!isTokensReceivedEvent(item.type)) { + throw new Error("not a TokensReceivedEvent type"); + } + + return TokensReceivedEvent.reified().new({ + token: decodeFromFieldsWithTypes(String.reified(), item.fields.token), + amount: decodeFromFieldsWithTypes("u64", item.fields.amount), + extraGasAmount: decodeFromFieldsWithTypes("u64", item.fields.extra_gas_amount), + recipient: decodeFromFieldsWithTypes("address", item.fields.recipient), + nonce: decodeFromFieldsWithTypes("u256", item.fields.nonce), + messenger: decodeFromFieldsWithTypes("u8", item.fields.messenger), + message: decodeFromFieldsWithTypes(String.reified(), item.fields.message), + }); + } + + static fromBcs(data: Uint8Array): TokensReceivedEvent { + return TokensReceivedEvent.fromFields(TokensReceivedEvent.bcs.parse(data)); + } + + toJSONField() { + return { + token: this.token, + amount: this.amount.toString(), + extraGasAmount: this.extraGasAmount.toString(), + recipient: this.recipient, + nonce: this.nonce.toString(), + messenger: this.messenger, + message: this.message, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): TokensReceivedEvent { + return TokensReceivedEvent.reified().new({ + token: decodeFromJSONField(String.reified(), field.token), + amount: decodeFromJSONField("u64", field.amount), + extraGasAmount: decodeFromJSONField("u64", field.extraGasAmount), + recipient: decodeFromJSONField("address", field.recipient), + nonce: decodeFromJSONField("u256", field.nonce), + messenger: decodeFromJSONField("u8", field.messenger), + message: decodeFromJSONField(String.reified(), field.message), + }); + } + + static fromJSON(json: Record): TokensReceivedEvent { + if (json.$typeName !== TokensReceivedEvent.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return TokensReceivedEvent.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): TokensReceivedEvent { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTokensReceivedEvent(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a TokensReceivedEvent object`); + } + return TokensReceivedEvent.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): TokensReceivedEvent { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTokensReceivedEvent(data.bcs.type)) { + throw new Error(`object at is not a TokensReceivedEvent object`); + } + + return TokensReceivedEvent.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return TokensReceivedEvent.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching TokensReceivedEvent object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTokensReceivedEvent(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a TokensReceivedEvent object`); + } + + return TokensReceivedEvent.fromSuiObjectData(res.data); + } +} + +/* ============================== TokensSentEvent =============================== */ + +export function isTokensSentEvent(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::events::TokensSentEvent`; +} + +export interface TokensSentEventFields { + token: ToField; + vusdAmount: ToField<"u64">; + sender: ToField<"address">; + recipient: ToField; + destinationChainId: ToField<"u8">; + receiveToken: ToField; + nonce: ToField<"u256">; + messenger: ToField<"u8">; +} + +export type TokensSentEventReified = Reified; + +export class TokensSentEvent implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::events::TokensSentEvent`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = TokensSentEvent.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = TokensSentEvent.$isPhantom; + + readonly token: ToField; + readonly vusdAmount: ToField<"u64">; + readonly sender: ToField<"address">; + readonly recipient: ToField; + readonly destinationChainId: ToField<"u8">; + readonly receiveToken: ToField; + readonly nonce: ToField<"u256">; + readonly messenger: ToField<"u8">; + + private constructor(typeArgs: [], fields: TokensSentEventFields) { + this.$fullTypeName = composeSuiType(TokensSentEvent.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.token = fields.token; + this.vusdAmount = fields.vusdAmount; + this.sender = fields.sender; + this.recipient = fields.recipient; + this.destinationChainId = fields.destinationChainId; + this.receiveToken = fields.receiveToken; + this.nonce = fields.nonce; + this.messenger = fields.messenger; + } + + static reified(): TokensSentEventReified { + return { + typeName: TokensSentEvent.$typeName, + fullTypeName: composeSuiType(TokensSentEvent.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: TokensSentEvent.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => TokensSentEvent.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => TokensSentEvent.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => TokensSentEvent.fromBcs(data), + bcs: TokensSentEvent.bcs, + fromJSONField: (field: any) => TokensSentEvent.fromJSONField(field), + fromJSON: (json: Record) => TokensSentEvent.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => TokensSentEvent.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => TokensSentEvent.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => TokensSentEvent.fetch(client, id), + new: (fields: TokensSentEventFields) => { + return new TokensSentEvent([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return TokensSentEvent.reified(); + } + + static phantom(): PhantomReified> { + return phantom(TokensSentEvent.reified()); + } + static get p() { + return TokensSentEvent.phantom(); + } + + static get bcs() { + return bcs.struct("TokensSentEvent", { + token: String.bcs, + vusd_amount: bcs.u64(), + sender: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + recipient: String.bcs, + destination_chain_id: bcs.u8(), + receive_token: String.bcs, + nonce: bcs.u256(), + messenger: bcs.u8(), + }); + } + + static fromFields(fields: Record): TokensSentEvent { + return TokensSentEvent.reified().new({ + token: decodeFromFields(String.reified(), fields.token), + vusdAmount: decodeFromFields("u64", fields.vusd_amount), + sender: decodeFromFields("address", fields.sender), + recipient: decodeFromFields(String.reified(), fields.recipient), + destinationChainId: decodeFromFields("u8", fields.destination_chain_id), + receiveToken: decodeFromFields(String.reified(), fields.receive_token), + nonce: decodeFromFields("u256", fields.nonce), + messenger: decodeFromFields("u8", fields.messenger), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): TokensSentEvent { + if (!isTokensSentEvent(item.type)) { + throw new Error("not a TokensSentEvent type"); + } + + return TokensSentEvent.reified().new({ + token: decodeFromFieldsWithTypes(String.reified(), item.fields.token), + vusdAmount: decodeFromFieldsWithTypes("u64", item.fields.vusd_amount), + sender: decodeFromFieldsWithTypes("address", item.fields.sender), + recipient: decodeFromFieldsWithTypes(String.reified(), item.fields.recipient), + destinationChainId: decodeFromFieldsWithTypes("u8", item.fields.destination_chain_id), + receiveToken: decodeFromFieldsWithTypes(String.reified(), item.fields.receive_token), + nonce: decodeFromFieldsWithTypes("u256", item.fields.nonce), + messenger: decodeFromFieldsWithTypes("u8", item.fields.messenger), + }); + } + + static fromBcs(data: Uint8Array): TokensSentEvent { + return TokensSentEvent.fromFields(TokensSentEvent.bcs.parse(data)); + } + + toJSONField() { + return { + token: this.token, + vusdAmount: this.vusdAmount.toString(), + sender: this.sender, + recipient: this.recipient, + destinationChainId: this.destinationChainId, + receiveToken: this.receiveToken, + nonce: this.nonce.toString(), + messenger: this.messenger, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): TokensSentEvent { + return TokensSentEvent.reified().new({ + token: decodeFromJSONField(String.reified(), field.token), + vusdAmount: decodeFromJSONField("u64", field.vusdAmount), + sender: decodeFromJSONField("address", field.sender), + recipient: decodeFromJSONField(String.reified(), field.recipient), + destinationChainId: decodeFromJSONField("u8", field.destinationChainId), + receiveToken: decodeFromJSONField(String.reified(), field.receiveToken), + nonce: decodeFromJSONField("u256", field.nonce), + messenger: decodeFromJSONField("u8", field.messenger), + }); + } + + static fromJSON(json: Record): TokensSentEvent { + if (json.$typeName !== TokensSentEvent.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return TokensSentEvent.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): TokensSentEvent { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTokensSentEvent(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a TokensSentEvent object`); + } + return TokensSentEvent.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): TokensSentEvent { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTokensSentEvent(data.bcs.type)) { + throw new Error(`object at is not a TokensSentEvent object`); + } + + return TokensSentEvent.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return TokensSentEvent.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching TokensSentEvent object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTokensSentEvent(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a TokensSentEvent object`); + } + + return TokensSentEvent.fromSuiObjectData(res.data); + } +} + +/* ============================== WithdrawEvent =============================== */ + +export function isWithdrawEvent(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::events::WithdrawEvent`; +} + +export interface WithdrawEventFields { + token: ToField; + amount: ToField<"u64">; + lpAmount: ToField<"u64">; +} + +export type WithdrawEventReified = Reified; + +export class WithdrawEvent implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::events::WithdrawEvent`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = WithdrawEvent.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = WithdrawEvent.$isPhantom; + + readonly token: ToField; + readonly amount: ToField<"u64">; + readonly lpAmount: ToField<"u64">; + + private constructor(typeArgs: [], fields: WithdrawEventFields) { + this.$fullTypeName = composeSuiType(WithdrawEvent.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.token = fields.token; + this.amount = fields.amount; + this.lpAmount = fields.lpAmount; + } + + static reified(): WithdrawEventReified { + return { + typeName: WithdrawEvent.$typeName, + fullTypeName: composeSuiType(WithdrawEvent.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: WithdrawEvent.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => WithdrawEvent.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => WithdrawEvent.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => WithdrawEvent.fromBcs(data), + bcs: WithdrawEvent.bcs, + fromJSONField: (field: any) => WithdrawEvent.fromJSONField(field), + fromJSON: (json: Record) => WithdrawEvent.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => WithdrawEvent.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => WithdrawEvent.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => WithdrawEvent.fetch(client, id), + new: (fields: WithdrawEventFields) => { + return new WithdrawEvent([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return WithdrawEvent.reified(); + } + + static phantom(): PhantomReified> { + return phantom(WithdrawEvent.reified()); + } + static get p() { + return WithdrawEvent.phantom(); + } + + static get bcs() { + return bcs.struct("WithdrawEvent", { + token: String.bcs, + amount: bcs.u64(), + lp_amount: bcs.u64(), + }); + } + + static fromFields(fields: Record): WithdrawEvent { + return WithdrawEvent.reified().new({ + token: decodeFromFields(String.reified(), fields.token), + amount: decodeFromFields("u64", fields.amount), + lpAmount: decodeFromFields("u64", fields.lp_amount), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): WithdrawEvent { + if (!isWithdrawEvent(item.type)) { + throw new Error("not a WithdrawEvent type"); + } + + return WithdrawEvent.reified().new({ + token: decodeFromFieldsWithTypes(String.reified(), item.fields.token), + amount: decodeFromFieldsWithTypes("u64", item.fields.amount), + lpAmount: decodeFromFieldsWithTypes("u64", item.fields.lp_amount), + }); + } + + static fromBcs(data: Uint8Array): WithdrawEvent { + return WithdrawEvent.fromFields(WithdrawEvent.bcs.parse(data)); + } + + toJSONField() { + return { + token: this.token, + amount: this.amount.toString(), + lpAmount: this.lpAmount.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): WithdrawEvent { + return WithdrawEvent.reified().new({ + token: decodeFromJSONField(String.reified(), field.token), + amount: decodeFromJSONField("u64", field.amount), + lpAmount: decodeFromJSONField("u64", field.lpAmount), + }); + } + + static fromJSON(json: Record): WithdrawEvent { + if (json.$typeName !== WithdrawEvent.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return WithdrawEvent.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): WithdrawEvent { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isWithdrawEvent(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a WithdrawEvent object`); + } + return WithdrawEvent.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): WithdrawEvent { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isWithdrawEvent(data.bcs.type)) { + throw new Error(`object at is not a WithdrawEvent object`); + } + + return WithdrawEvent.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return WithdrawEvent.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching WithdrawEvent object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isWithdrawEvent(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a WithdrawEvent object`); + } + + return WithdrawEvent.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/bridge/index.ts b/src/services/models/sui/bridge/index.ts new file mode 100644 index 00000000..c7a832f2 --- /dev/null +++ b/src/services/models/sui/bridge/index.ts @@ -0,0 +1,41 @@ +// @ts-nocheck +import { compressSuiType } from "../_framework/util"; + +class PackageAddress { + private static $PACKAGE_ID = ""; + private static $PUBLISHED_AT = ""; + private static $PKG_V = []; + + get PACKAGE_ID() { + return compressSuiType(PackageAddress.$PACKAGE_ID); + } + + get PUBLISHED_AT() { + return compressSuiType(PackageAddress.$PUBLISHED_AT); + } + + get PKG_V1() { + return compressSuiType(PackageAddress.$PKG_V[1]); + } + + setPackageId(address: string): void { + PackageAddress.$PACKAGE_ID = address; + } + + setPublishedAt(address: string): void { + PackageAddress.$PUBLISHED_AT = address; + } + + setPkgV(v: number, address: string): void { + PackageAddress.$PKG_V[v] = address; + } + + setAddress(address: string, pkgV1?: string) { + PackageAddress.$PACKAGE_ID = address; + PackageAddress.$PUBLISHED_AT = address; + PackageAddress.$PKG_V[1] = pkgV1 || address; + } +} + +const packageAddress = new PackageAddress(); +export = packageAddress; diff --git a/src/services/models/sui/bridge/init.ts b/src/services/models/sui/bridge/init.ts new file mode 100644 index 00000000..a1596a93 --- /dev/null +++ b/src/services/models/sui/bridge/init.ts @@ -0,0 +1,32 @@ +// @ts-nocheck +import * as anotherBridge from "./another-bridge/structs"; +import * as bridge from "./bridge/structs"; +import * as events from "./events/structs"; +import * as poolRewards from "./pool-rewards/structs"; +import * as poolState from "./pool-state/structs"; +import * as pool from "./pool/structs"; +import * as userDeposit from "./user-deposit/structs"; +import { StructClassLoader } from "../_framework/loader"; + +export function registerClasses(loader: StructClassLoader) { + loader.register(anotherBridge.AnotherBridge); + loader.register(userDeposit.UserDeposit); + loader.register(poolRewards.PoolRewards); + loader.register(poolState.PoolState); + loader.register(events.DepositEvent); + loader.register(events.ReceiveFeeEvent); + loader.register(events.RewardsClaimedEvent); + loader.register(events.SwappedEvent); + loader.register(events.SwappedFromVUsdEvent); + loader.register(events.SwappedToVUsdEvent); + loader.register(events.TokensReceivedEvent); + loader.register(events.TokensSentEvent); + loader.register(events.WithdrawEvent); + loader.register(pool.AdminCap); + loader.register(pool.Pool); + loader.register(pool.StopCap); + loader.register(bridge.AdminCap); + loader.register(bridge.Bridge); + loader.register(bridge.FeeCollectorCap); + loader.register(bridge.StopSwapCap); +} diff --git a/src/services/models/sui/bridge/pool-rewards/functions.ts b/src/services/models/sui/bridge/pool-rewards/functions.ts new file mode 100644 index 00000000..0ac3b077 --- /dev/null +++ b/src/services/models/sui/bridge/pool-rewards/functions.ts @@ -0,0 +1,116 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function new_(tx: Transaction, typeArg: string) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_rewards::new`, + typeArguments: [typeArg], + arguments: [], + }); +} + +export interface AddRewardsArgs { + poolRewards: TransactionObjectInput; + rewards: TransactionObjectInput; +} + +export function addRewards(tx: Transaction, typeArg: string, args: AddRewardsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_rewards::add_rewards`, + typeArguments: [typeArg], + arguments: [obj(tx, args.poolRewards), obj(tx, args.rewards)], + }); +} + +export function claimAdminFee(tx: Transaction, typeArg: string, poolRewards: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_rewards::claim_admin_fee`, + typeArguments: [typeArg], + arguments: [obj(tx, poolRewards)], + }); +} + +export interface ClaimRewardArgs { + poolRewards: TransactionObjectInput; + userDeposit: TransactionObjectInput; +} + +export function claimReward(tx: Transaction, typeArg: string, args: ClaimRewardArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_rewards::claim_reward`, + typeArguments: [typeArg], + arguments: [obj(tx, args.poolRewards), obj(tx, args.userDeposit)], + }); +} + +export interface DepositLpArgs { + poolRewards: TransactionObjectInput; + userDeposit: TransactionObjectInput; + lpAmount: bigint | TransactionArgument; +} + +export function depositLp(tx: Transaction, typeArg: string, args: DepositLpArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_rewards::deposit_lp`, + typeArguments: [typeArg], + arguments: [obj(tx, args.poolRewards), obj(tx, args.userDeposit), pure(tx, args.lpAmount, `u64`)], + }); +} + +export function getAdminFeeShareBp(tx: Transaction, typeArg: string, poolRewards: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_rewards::get_admin_fee_share_bp`, + typeArguments: [typeArg], + arguments: [obj(tx, poolRewards)], + }); +} + +export function lpSupply(tx: Transaction, typeArg: string, poolRewards: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_rewards::lp_supply`, + typeArguments: [typeArg], + arguments: [obj(tx, poolRewards)], + }); +} + +export interface PendingRewardsArgs { + poolRewards: TransactionObjectInput; + userDeposit: TransactionObjectInput; +} + +export function pendingRewards(tx: Transaction, typeArg: string, args: PendingRewardsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_rewards::pending_rewards`, + typeArguments: [typeArg], + arguments: [obj(tx, args.poolRewards), obj(tx, args.userDeposit)], + }); +} + +export interface SetAdminFeeShareBpArgs { + poolRewards: TransactionObjectInput; + adminFeeShareBp: bigint | TransactionArgument; +} + +export function setAdminFeeShareBp(tx: Transaction, typeArg: string, args: SetAdminFeeShareBpArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_rewards::set_admin_fee_share_bp`, + typeArguments: [typeArg], + arguments: [obj(tx, args.poolRewards), pure(tx, args.adminFeeShareBp, `u64`)], + }); +} + +export interface WithdrawLpArgs { + poolRewards: TransactionObjectInput; + userDeposit: TransactionObjectInput; + lpAmount: bigint | TransactionArgument; +} + +export function withdrawLp(tx: Transaction, typeArg: string, args: WithdrawLpArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_rewards::withdraw_lp`, + typeArguments: [typeArg], + arguments: [obj(tx, args.poolRewards), obj(tx, args.userDeposit), pure(tx, args.lpAmount, `u64`)], + }); +} diff --git a/src/services/models/sui/bridge/pool-rewards/structs.ts b/src/services/models/sui/bridge/pool-rewards/structs.ts new file mode 100644 index 00000000..f5aa1c18 --- /dev/null +++ b/src/services/models/sui/bridge/pool-rewards/structs.ts @@ -0,0 +1,258 @@ +// @ts-nocheck +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { Balance } from "../../sui/balance/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== PoolRewards =============================== */ + +export function isPoolRewards(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V1}::pool_rewards::PoolRewards` + "<"); +} + +export interface PoolRewardsFields { + accRewardPerShareP: ToField<"u128">; + adminFeeShareBp: ToField<"u64">; + adminFee: ToField>; + rewards: ToField>; + lpSupply: ToField<"u64">; +} + +export type PoolRewardsReified = Reified, PoolRewardsFields>; + +export class PoolRewards implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::pool_rewards::PoolRewards`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = PoolRewards.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = PoolRewards.$isPhantom; + + readonly accRewardPerShareP: ToField<"u128">; + readonly adminFeeShareBp: ToField<"u64">; + readonly adminFee: ToField>; + readonly rewards: ToField>; + readonly lpSupply: ToField<"u64">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: PoolRewardsFields) { + this.$fullTypeName = composeSuiType(PoolRewards.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.accRewardPerShareP = fields.accRewardPerShareP; + this.adminFeeShareBp = fields.adminFeeShareBp; + this.adminFee = fields.adminFee; + this.rewards = fields.rewards; + this.lpSupply = fields.lpSupply; + } + + static reified>(T: T): PoolRewardsReified> { + return { + typeName: PoolRewards.$typeName, + fullTypeName: composeSuiType(PoolRewards.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: PoolRewards.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => PoolRewards.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => PoolRewards.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => PoolRewards.fromBcs(T, data), + bcs: PoolRewards.bcs, + fromJSONField: (field: any) => PoolRewards.fromJSONField(T, field), + fromJSON: (json: Record) => PoolRewards.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => PoolRewards.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => PoolRewards.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => PoolRewards.fetch(client, T, id), + new: (fields: PoolRewardsFields>) => { + return new PoolRewards([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return PoolRewards.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(PoolRewards.reified(T)); + } + static get p() { + return PoolRewards.phantom; + } + + static get bcs() { + return bcs.struct("PoolRewards", { + acc_reward_per_share_p: bcs.u128(), + admin_fee_share_bp: bcs.u64(), + admin_fee: Balance.bcs, + rewards: Balance.bcs, + lp_supply: bcs.u64(), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): PoolRewards> { + return PoolRewards.reified(typeArg).new({ + accRewardPerShareP: decodeFromFields("u128", fields.acc_reward_per_share_p), + adminFeeShareBp: decodeFromFields("u64", fields.admin_fee_share_bp), + adminFee: decodeFromFields(Balance.reified(typeArg), fields.admin_fee), + rewards: decodeFromFields(Balance.reified(typeArg), fields.rewards), + lpSupply: decodeFromFields("u64", fields.lp_supply), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): PoolRewards> { + if (!isPoolRewards(item.type)) { + throw new Error("not a PoolRewards type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return PoolRewards.reified(typeArg).new({ + accRewardPerShareP: decodeFromFieldsWithTypes("u128", item.fields.acc_reward_per_share_p), + adminFeeShareBp: decodeFromFieldsWithTypes("u64", item.fields.admin_fee_share_bp), + adminFee: decodeFromFieldsWithTypes(Balance.reified(typeArg), item.fields.admin_fee), + rewards: decodeFromFieldsWithTypes(Balance.reified(typeArg), item.fields.rewards), + lpSupply: decodeFromFieldsWithTypes("u64", item.fields.lp_supply), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): PoolRewards> { + return PoolRewards.fromFields(typeArg, PoolRewards.bcs.parse(data)); + } + + toJSONField() { + return { + accRewardPerShareP: this.accRewardPerShareP.toString(), + adminFeeShareBp: this.adminFeeShareBp.toString(), + adminFee: this.adminFee.toJSONField(), + rewards: this.rewards.toJSONField(), + lpSupply: this.lpSupply.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): PoolRewards> { + return PoolRewards.reified(typeArg).new({ + accRewardPerShareP: decodeFromJSONField("u128", field.accRewardPerShareP), + adminFeeShareBp: decodeFromJSONField("u64", field.adminFeeShareBp), + adminFee: decodeFromJSONField(Balance.reified(typeArg), field.adminFee), + rewards: decodeFromJSONField(Balance.reified(typeArg), field.rewards), + lpSupply: decodeFromJSONField("u64", field.lpSupply), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): PoolRewards> { + if (json.$typeName !== PoolRewards.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(PoolRewards.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return PoolRewards.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): PoolRewards> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isPoolRewards(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a PoolRewards object`); + } + return PoolRewards.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): PoolRewards> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isPoolRewards(data.bcs.type)) { + throw new Error(`object at is not a PoolRewards object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return PoolRewards.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return PoolRewards.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching PoolRewards object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isPoolRewards(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a PoolRewards object`); + } + + return PoolRewards.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/bridge/pool-state/functions.ts b/src/services/models/sui/bridge/pool-state/functions.ts new file mode 100644 index 00000000..dfca539d --- /dev/null +++ b/src/services/models/sui/bridge/pool-state/functions.ts @@ -0,0 +1,215 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function a(tx: Transaction, typeArg: string, poolState: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::a`, + typeArguments: [typeArg], + arguments: [obj(tx, poolState)], + }); +} + +export function new_(tx: Transaction, typeArg: string, a: bigint | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::new`, + typeArguments: [typeArg], + arguments: [pure(tx, a, `u64`)], + }); +} + +export function sqrt(tx: Transaction, n: bigint | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::sqrt`, + arguments: [pure(tx, n, `u256`)], + }); +} + +export function d(tx: Transaction, typeArg: string, poolState: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::d`, + typeArguments: [typeArg], + arguments: [obj(tx, poolState)], + }); +} + +export interface AddTokenBalanceArgs { + poolState: TransactionObjectInput; + amount: bigint | TransactionArgument; +} + +export function addTokenBalance(tx: Transaction, typeArg: string, args: AddTokenBalanceArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::add_token_balance`, + typeArguments: [typeArg], + arguments: [obj(tx, args.poolState), pure(tx, args.amount, `u64`)], + }); +} + +export interface AddVusdBalanceArgs { + poolState: TransactionObjectInput; + amount: bigint | TransactionArgument; +} + +export function addVusdBalance(tx: Transaction, typeArg: string, args: AddVusdBalanceArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::add_vusd_balance`, + typeArguments: [typeArg], + arguments: [obj(tx, args.poolState), pure(tx, args.amount, `u64`)], + }); +} + +export function cbrt(tx: Transaction, n: bigint | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::cbrt`, + arguments: [pure(tx, n, `u256`)], + }); +} + +export function getBalanceRatioMinBp(tx: Transaction, typeArg: string, poolState: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::get_balance_ratio_min_bp`, + typeArguments: [typeArg], + arguments: [obj(tx, poolState)], + }); +} + +export interface GetDArgs { + a: bigint | TransactionArgument; + x: bigint | TransactionArgument; + y: bigint | TransactionArgument; +} + +export function getD(tx: Transaction, args: GetDArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::get_d`, + arguments: [pure(tx, args.a, `u64`), pure(tx, args.x, `u64`), pure(tx, args.y, `u64`)], + }); +} + +export interface GetYArgs { + poolState: TransactionObjectInput; + nativeX: bigint | TransactionArgument; +} + +export function getY(tx: Transaction, typeArg: string, args: GetYArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::get_y`, + typeArguments: [typeArg], + arguments: [obj(tx, args.poolState), pure(tx, args.nativeX, `u64`)], + }); +} + +export interface SetBalanceRatioMinBpArgs { + poolState: TransactionObjectInput; + balanceRatioMinBp: bigint | TransactionArgument; +} + +export function setBalanceRatioMinBp(tx: Transaction, typeArg: string, args: SetBalanceRatioMinBpArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::set_balance_ratio_min_bp`, + typeArguments: [typeArg], + arguments: [obj(tx, args.poolState), pure(tx, args.balanceRatioMinBp, `u64`)], + }); +} + +export interface SetTokenBalanceArgs { + poolState: TransactionObjectInput; + tokenBalance: bigint | TransactionArgument; +} + +export function setTokenBalance(tx: Transaction, typeArg: string, args: SetTokenBalanceArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::set_token_balance`, + typeArguments: [typeArg], + arguments: [obj(tx, args.poolState), pure(tx, args.tokenBalance, `u64`)], + }); +} + +export function tokenBalance(tx: Transaction, typeArg: string, poolState: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::token_balance`, + typeArguments: [typeArg], + arguments: [obj(tx, poolState)], + }); +} + +export interface SetVusdBalanceArgs { + poolState: TransactionObjectInput; + vusdBalance: bigint | TransactionArgument; +} + +export function setVusdBalance(tx: Transaction, typeArg: string, args: SetVusdBalanceArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::set_vusd_balance`, + typeArguments: [typeArg], + arguments: [obj(tx, args.poolState), pure(tx, args.vusdBalance, `u64`)], + }); +} + +export function vusdBalance(tx: Transaction, typeArg: string, poolState: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::vusd_balance`, + typeArguments: [typeArg], + arguments: [obj(tx, poolState)], + }); +} + +export interface SubTokenBalanceArgs { + poolState: TransactionObjectInput; + amount: bigint | TransactionArgument; +} + +export function subTokenBalance(tx: Transaction, typeArg: string, args: SubTokenBalanceArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::sub_token_balance`, + typeArguments: [typeArg], + arguments: [obj(tx, args.poolState), pure(tx, args.amount, `u64`)], + }); +} + +export interface SubVusdBalanceArgs { + poolState: TransactionObjectInput; + amount: bigint | TransactionArgument; +} + +export function subVusdBalance(tx: Transaction, typeArg: string, args: SubVusdBalanceArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::sub_vusd_balance`, + typeArguments: [typeArg], + arguments: [obj(tx, args.poolState), pure(tx, args.amount, `u64`)], + }); +} + +export function updateD(tx: Transaction, typeArg: string, poolState: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::update_d`, + typeArguments: [typeArg], + arguments: [obj(tx, poolState)], + }); +} + +export function updateTokenBalance(tx: Transaction, typeArg: string, poolState: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::update_token_balance`, + typeArguments: [typeArg], + arguments: [obj(tx, poolState)], + }); +} + +export function updateVusdBalance(tx: Transaction, typeArg: string, poolState: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::update_vusd_balance`, + typeArguments: [typeArg], + arguments: [obj(tx, poolState)], + }); +} + +export function validateBalanceRatio(tx: Transaction, typeArg: string, poolState: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool_state::validate_balance_ratio`, + typeArguments: [typeArg], + arguments: [obj(tx, poolState)], + }); +} diff --git a/src/services/models/sui/bridge/pool-state/structs.ts b/src/services/models/sui/bridge/pool-state/structs.ts new file mode 100644 index 00000000..44acf090 --- /dev/null +++ b/src/services/models/sui/bridge/pool-state/structs.ts @@ -0,0 +1,257 @@ +// @ts-nocheck +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== PoolState =============================== */ + +export function isPoolState(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V1}::pool_state::PoolState` + "<"); +} + +export interface PoolStateFields { + tokenBalance: ToField<"u64">; + vusdBalance: ToField<"u64">; + d: ToField<"u64">; + a: ToField<"u64">; + balanceRatioMinBp: ToField<"u64">; +} + +export type PoolStateReified = Reified, PoolStateFields>; + +export class PoolState implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::pool_state::PoolState`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = PoolState.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = PoolState.$isPhantom; + + readonly tokenBalance: ToField<"u64">; + readonly vusdBalance: ToField<"u64">; + readonly d: ToField<"u64">; + readonly a: ToField<"u64">; + readonly balanceRatioMinBp: ToField<"u64">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: PoolStateFields) { + this.$fullTypeName = composeSuiType(PoolState.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.tokenBalance = fields.tokenBalance; + this.vusdBalance = fields.vusdBalance; + this.d = fields.d; + this.a = fields.a; + this.balanceRatioMinBp = fields.balanceRatioMinBp; + } + + static reified>(T: T): PoolStateReified> { + return { + typeName: PoolState.$typeName, + fullTypeName: composeSuiType(PoolState.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: PoolState.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => PoolState.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => PoolState.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => PoolState.fromBcs(T, data), + bcs: PoolState.bcs, + fromJSONField: (field: any) => PoolState.fromJSONField(T, field), + fromJSON: (json: Record) => PoolState.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => PoolState.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => PoolState.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => PoolState.fetch(client, T, id), + new: (fields: PoolStateFields>) => { + return new PoolState([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return PoolState.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(PoolState.reified(T)); + } + static get p() { + return PoolState.phantom; + } + + static get bcs() { + return bcs.struct("PoolState", { + token_balance: bcs.u64(), + vusd_balance: bcs.u64(), + d: bcs.u64(), + a: bcs.u64(), + balance_ratio_min_bp: bcs.u64(), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): PoolState> { + return PoolState.reified(typeArg).new({ + tokenBalance: decodeFromFields("u64", fields.token_balance), + vusdBalance: decodeFromFields("u64", fields.vusd_balance), + d: decodeFromFields("u64", fields.d), + a: decodeFromFields("u64", fields.a), + balanceRatioMinBp: decodeFromFields("u64", fields.balance_ratio_min_bp), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): PoolState> { + if (!isPoolState(item.type)) { + throw new Error("not a PoolState type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return PoolState.reified(typeArg).new({ + tokenBalance: decodeFromFieldsWithTypes("u64", item.fields.token_balance), + vusdBalance: decodeFromFieldsWithTypes("u64", item.fields.vusd_balance), + d: decodeFromFieldsWithTypes("u64", item.fields.d), + a: decodeFromFieldsWithTypes("u64", item.fields.a), + balanceRatioMinBp: decodeFromFieldsWithTypes("u64", item.fields.balance_ratio_min_bp), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): PoolState> { + return PoolState.fromFields(typeArg, PoolState.bcs.parse(data)); + } + + toJSONField() { + return { + tokenBalance: this.tokenBalance.toString(), + vusdBalance: this.vusdBalance.toString(), + d: this.d.toString(), + a: this.a.toString(), + balanceRatioMinBp: this.balanceRatioMinBp.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): PoolState> { + return PoolState.reified(typeArg).new({ + tokenBalance: decodeFromJSONField("u64", field.tokenBalance), + vusdBalance: decodeFromJSONField("u64", field.vusdBalance), + d: decodeFromJSONField("u64", field.d), + a: decodeFromJSONField("u64", field.a), + balanceRatioMinBp: decodeFromJSONField("u64", field.balanceRatioMinBp), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): PoolState> { + if (json.$typeName !== PoolState.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(PoolState.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return PoolState.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): PoolState> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isPoolState(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a PoolState object`); + } + return PoolState.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): PoolState> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isPoolState(data.bcs.type)) { + throw new Error(`object at is not a PoolState object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return PoolState.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return PoolState.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching PoolState object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isPoolState(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a PoolState object`); + } + + return PoolState.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/bridge/pool/functions.ts b/src/services/models/sui/bridge/pool/functions.ts new file mode 100644 index 00000000..372a658a --- /dev/null +++ b/src/services/models/sui/bridge/pool/functions.ts @@ -0,0 +1,285 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface NewArgs { + coinMetadata: TransactionObjectInput; + a: bigint | TransactionArgument; + feeShareBp: bigint | TransactionArgument; +} + +export function new_(tx: Transaction, typeArg: string, args: NewArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::new`, + typeArguments: [typeArg], + arguments: [obj(tx, args.coinMetadata), pure(tx, args.a, `u64`), pure(tx, args.feeShareBp, `u64`)], + }); +} + +export function balance(tx: Transaction, typeArg: string, pool: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::balance`, + typeArguments: [typeArg], + arguments: [obj(tx, pool)], + }); +} + +export function decimals(tx: Transaction, typeArg: string, pool: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::decimals`, + typeArguments: [typeArg], + arguments: [obj(tx, pool)], + }); +} + +export interface DepositArgs { + pool: TransactionObjectInput; + userDeposit: TransactionObjectInput; + coin: TransactionObjectInput; +} + +export function deposit(tx: Transaction, typeArg: string, args: DepositArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::deposit`, + typeArguments: [typeArg], + arguments: [obj(tx, args.pool), obj(tx, args.userDeposit), obj(tx, args.coin)], + }); +} + +export interface WithdrawArgs { + pool: TransactionObjectInput; + userDeposit: TransactionObjectInput; + amountLp: bigint | TransactionArgument; +} + +export function withdraw(tx: Transaction, typeArg: string, args: WithdrawArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::withdraw`, + typeArguments: [typeArg], + arguments: [obj(tx, args.pool), obj(tx, args.userDeposit), pure(tx, args.amountLp, `u64`)], + }); +} + +export function state(tx: Transaction, typeArg: string, pool: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::state`, + typeArguments: [typeArg], + arguments: [obj(tx, pool)], + }); +} + +export function init(tx: Transaction) { + return tx.moveCall({ target: `${PUBLISHED_AT}::pool::init`, arguments: [] }); +} + +export function rewards(tx: Transaction, typeArg: string, pool: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::rewards`, + typeArguments: [typeArg], + arguments: [obj(tx, pool)], + }); +} + +export function claimAdminFee(tx: Transaction, typeArg: string, pool: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::claim_admin_fee`, + typeArguments: [typeArg], + arguments: [obj(tx, pool)], + }); +} + +export interface ClaimRewardArgs { + pool: TransactionObjectInput; + userDeposit: TransactionObjectInput; +} + +export function claimReward(tx: Transaction, typeArg: string, args: ClaimRewardArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::claim_reward`, + typeArguments: [typeArg], + arguments: [obj(tx, args.pool), obj(tx, args.userDeposit)], + }); +} + +export interface SetAdminFeeShareBpArgs { + pool: TransactionObjectInput; + adminFeeShareBp: bigint | TransactionArgument; +} + +export function setAdminFeeShareBp(tx: Transaction, typeArg: string, args: SetAdminFeeShareBpArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::set_admin_fee_share_bp`, + typeArguments: [typeArg], + arguments: [obj(tx, args.pool), pure(tx, args.adminFeeShareBp, `u64`)], + }); +} + +export interface SetBalanceRatioMinBpArgs { + pool: TransactionObjectInput; + balanceRatioMinBp: bigint | TransactionArgument; +} + +export function setBalanceRatioMinBp(tx: Transaction, typeArg: string, args: SetBalanceRatioMinBpArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::set_balance_ratio_min_bp`, + typeArguments: [typeArg], + arguments: [obj(tx, args.pool), pure(tx, args.balanceRatioMinBp, `u64`)], + }); +} + +export interface AdjustTotalLpAmountArgs { + pool: TransactionObjectInput; + userDeposit: TransactionObjectInput; +} + +export function adjustTotalLpAmount(tx: Transaction, typeArg: string, args: AdjustTotalLpAmountArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::adjust_total_lp_amount`, + typeArguments: [typeArg], + arguments: [obj(tx, args.pool), obj(tx, args.userDeposit)], + }); +} + +export function canDeposit(tx: Transaction, typeArg: string, pool: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::can_deposit`, + typeArguments: [typeArg], + arguments: [obj(tx, pool)], + }); +} + +export function canWithdraw(tx: Transaction, typeArg: string, pool: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::can_withdraw`, + typeArguments: [typeArg], + arguments: [obj(tx, pool)], + }); +} + +export function feeShare(tx: Transaction, typeArg: string, pool: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::fee_share`, + typeArguments: [typeArg], + arguments: [obj(tx, pool)], + }); +} + +export interface FromSystemPrecisionArgs { + pool: TransactionObjectInput; + amount: bigint | TransactionArgument; +} + +export function fromSystemPrecision(tx: Transaction, typeArg: string, args: FromSystemPrecisionArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::from_system_precision`, + typeArguments: [typeArg], + arguments: [obj(tx, args.pool), pure(tx, args.amount, `u64`)], + }); +} + +export interface GetFeeArgs { + pool: TransactionObjectInput; + coin: TransactionObjectInput; + zeroFee: boolean | TransactionArgument; +} + +export function getFee(tx: Transaction, typeArg: string, args: GetFeeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::get_fee`, + typeArguments: [typeArg], + arguments: [obj(tx, args.pool), obj(tx, args.coin), pure(tx, args.zeroFee, `bool`)], + }); +} + +export interface SetFeeShareArgs { + pool: TransactionObjectInput; + feeShareBp: bigint | TransactionArgument; +} + +export function setFeeShare(tx: Transaction, typeArg: string, args: SetFeeShareArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::set_fee_share`, + typeArguments: [typeArg], + arguments: [obj(tx, args.pool), pure(tx, args.feeShareBp, `u64`)], + }); +} + +export function startDeposit(tx: Transaction, typeArg: string, pool: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::start_deposit`, + typeArguments: [typeArg], + arguments: [obj(tx, pool)], + }); +} + +export function startWithdraw(tx: Transaction, typeArg: string, pool: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::start_withdraw`, + typeArguments: [typeArg], + arguments: [obj(tx, pool)], + }); +} + +export function stopDeposit(tx: Transaction, typeArg: string, pool: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::stop_deposit`, + typeArguments: [typeArg], + arguments: [obj(tx, pool)], + }); +} + +export function stopWithdraw(tx: Transaction, typeArg: string, pool: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::stop_withdraw`, + typeArguments: [typeArg], + arguments: [obj(tx, pool)], + }); +} + +export interface SwapFromVusdArgs { + pool: TransactionObjectInput; + vusdAmount: bigint | TransactionArgument; + receiveAmountMin: bigint | TransactionArgument; + zeroFee: boolean | TransactionArgument; +} + +export function swapFromVusd(tx: Transaction, typeArg: string, args: SwapFromVusdArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::swap_from_vusd`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.pool), + pure(tx, args.vusdAmount, `u64`), + pure(tx, args.receiveAmountMin, `u64`), + pure(tx, args.zeroFee, `bool`), + ], + }); +} + +export interface SwapToVusdArgs { + pool: TransactionObjectInput; + coin: TransactionObjectInput; + zeroFee: boolean | TransactionArgument; +} + +export function swapToVusd(tx: Transaction, typeArg: string, args: SwapToVusdArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::swap_to_vusd`, + typeArguments: [typeArg], + arguments: [obj(tx, args.pool), obj(tx, args.coin), pure(tx, args.zeroFee, `bool`)], + }); +} + +export interface ToSystemPrecisionArgs { + pool: TransactionObjectInput; + amount: bigint | TransactionArgument; +} + +export function toSystemPrecision(tx: Transaction, typeArg: string, args: ToSystemPrecisionArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pool::to_system_precision`, + typeArguments: [typeArg], + arguments: [obj(tx, args.pool), pure(tx, args.amount, `u64`)], + }); +} diff --git a/src/services/models/sui/bridge/pool/structs.ts b/src/services/models/sui/bridge/pool/structs.ts new file mode 100644 index 00000000..bab58db9 --- /dev/null +++ b/src/services/models/sui/bridge/pool/structs.ts @@ -0,0 +1,611 @@ +// @ts-nocheck +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { Balance } from "../../sui/balance/structs"; +import { UID } from "../../sui/object/structs"; +import { PKG_V1 } from "../index"; +import { PoolRewards } from "../pool-rewards/structs"; +import { PoolState } from "../pool-state/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== AdminCap =============================== */ + +export function isAdminCap(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::pool::AdminCap`; +} + +export interface AdminCapFields { + id: ToField; +} + +export type AdminCapReified = Reified; + +export class AdminCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::pool::AdminCap`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = AdminCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = AdminCap.$isPhantom; + + readonly id: ToField; + + private constructor(typeArgs: [], fields: AdminCapFields) { + this.$fullTypeName = composeSuiType(AdminCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified(): AdminCapReified { + return { + typeName: AdminCap.$typeName, + fullTypeName: composeSuiType(AdminCap.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: AdminCap.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => AdminCap.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => AdminCap.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => AdminCap.fromBcs(data), + bcs: AdminCap.bcs, + fromJSONField: (field: any) => AdminCap.fromJSONField(field), + fromJSON: (json: Record) => AdminCap.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => AdminCap.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => AdminCap.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => AdminCap.fetch(client, id), + new: (fields: AdminCapFields) => { + return new AdminCap([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return AdminCap.reified(); + } + + static phantom(): PhantomReified> { + return phantom(AdminCap.reified()); + } + static get p() { + return AdminCap.phantom(); + } + + static get bcs() { + return bcs.struct("AdminCap", { + id: UID.bcs, + }); + } + + static fromFields(fields: Record): AdminCap { + return AdminCap.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): AdminCap { + if (!isAdminCap(item.type)) { + throw new Error("not a AdminCap type"); + } + + return AdminCap.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + }); + } + + static fromBcs(data: Uint8Array): AdminCap { + return AdminCap.fromFields(AdminCap.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): AdminCap { + return AdminCap.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + }); + } + + static fromJSON(json: Record): AdminCap { + if (json.$typeName !== AdminCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return AdminCap.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): AdminCap { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isAdminCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a AdminCap object`); + } + return AdminCap.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): AdminCap { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isAdminCap(data.bcs.type)) { + throw new Error(`object at is not a AdminCap object`); + } + + return AdminCap.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return AdminCap.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching AdminCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isAdminCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a AdminCap object`); + } + + return AdminCap.fromSuiObjectData(res.data); + } +} + +/* ============================== Pool =============================== */ + +export function isPool(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V1}::pool::Pool` + "<"); +} + +export interface PoolFields { + id: ToField; + state: ToField>; + rewards: ToField>; + feeShareBp: ToField<"u64">; + canDeposit: ToField<"bool">; + canWithdraw: ToField<"bool">; + decimals: ToField<"u8">; + balance: ToField>; +} + +export type PoolReified = Reified, PoolFields>; + +export class Pool implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::pool::Pool`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = Pool.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = Pool.$isPhantom; + + readonly id: ToField; + readonly state: ToField>; + readonly rewards: ToField>; + readonly feeShareBp: ToField<"u64">; + readonly canDeposit: ToField<"bool">; + readonly canWithdraw: ToField<"bool">; + readonly decimals: ToField<"u8">; + readonly balance: ToField>; + + private constructor(typeArgs: [PhantomToTypeStr], fields: PoolFields) { + this.$fullTypeName = composeSuiType(Pool.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.state = fields.state; + this.rewards = fields.rewards; + this.feeShareBp = fields.feeShareBp; + this.canDeposit = fields.canDeposit; + this.canWithdraw = fields.canWithdraw; + this.decimals = fields.decimals; + this.balance = fields.balance; + } + + static reified>(T: T): PoolReified> { + return { + typeName: Pool.$typeName, + fullTypeName: composeSuiType(Pool.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: Pool.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => Pool.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Pool.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => Pool.fromBcs(T, data), + bcs: Pool.bcs, + fromJSONField: (field: any) => Pool.fromJSONField(T, field), + fromJSON: (json: Record) => Pool.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => Pool.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => Pool.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => Pool.fetch(client, T, id), + new: (fields: PoolFields>) => { + return new Pool([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Pool.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(Pool.reified(T)); + } + static get p() { + return Pool.phantom; + } + + static get bcs() { + return bcs.struct("Pool", { + id: UID.bcs, + state: PoolState.bcs, + rewards: PoolRewards.bcs, + fee_share_bp: bcs.u64(), + can_deposit: bcs.bool(), + can_withdraw: bcs.bool(), + decimals: bcs.u8(), + balance: Balance.bcs, + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): Pool> { + return Pool.reified(typeArg).new({ + id: decodeFromFields(UID.reified(), fields.id), + state: decodeFromFields(PoolState.reified(typeArg), fields.state), + rewards: decodeFromFields(PoolRewards.reified(typeArg), fields.rewards), + feeShareBp: decodeFromFields("u64", fields.fee_share_bp), + canDeposit: decodeFromFields("bool", fields.can_deposit), + canWithdraw: decodeFromFields("bool", fields.can_withdraw), + decimals: decodeFromFields("u8", fields.decimals), + balance: decodeFromFields(Balance.reified(typeArg), fields.balance), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): Pool> { + if (!isPool(item.type)) { + throw new Error("not a Pool type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Pool.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + state: decodeFromFieldsWithTypes(PoolState.reified(typeArg), item.fields.state), + rewards: decodeFromFieldsWithTypes(PoolRewards.reified(typeArg), item.fields.rewards), + feeShareBp: decodeFromFieldsWithTypes("u64", item.fields.fee_share_bp), + canDeposit: decodeFromFieldsWithTypes("bool", item.fields.can_deposit), + canWithdraw: decodeFromFieldsWithTypes("bool", item.fields.can_withdraw), + decimals: decodeFromFieldsWithTypes("u8", item.fields.decimals), + balance: decodeFromFieldsWithTypes(Balance.reified(typeArg), item.fields.balance), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): Pool> { + return Pool.fromFields(typeArg, Pool.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + state: this.state.toJSONField(), + rewards: this.rewards.toJSONField(), + feeShareBp: this.feeShareBp.toString(), + canDeposit: this.canDeposit, + canWithdraw: this.canWithdraw, + decimals: this.decimals, + balance: this.balance.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): Pool> { + return Pool.reified(typeArg).new({ + id: decodeFromJSONField(UID.reified(), field.id), + state: decodeFromJSONField(PoolState.reified(typeArg), field.state), + rewards: decodeFromJSONField(PoolRewards.reified(typeArg), field.rewards), + feeShareBp: decodeFromJSONField("u64", field.feeShareBp), + canDeposit: decodeFromJSONField("bool", field.canDeposit), + canWithdraw: decodeFromJSONField("bool", field.canWithdraw), + decimals: decodeFromJSONField("u8", field.decimals), + balance: decodeFromJSONField(Balance.reified(typeArg), field.balance), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): Pool> { + if (json.$typeName !== Pool.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Pool.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Pool.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): Pool> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isPool(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Pool object`); + } + return Pool.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): Pool> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isPool(data.bcs.type)) { + throw new Error(`object at is not a Pool object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Pool.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Pool.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Pool object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isPool(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Pool object`); + } + + return Pool.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== StopCap =============================== */ + +export function isStopCap(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::pool::StopCap`; +} + +export interface StopCapFields { + id: ToField; +} + +export type StopCapReified = Reified; + +export class StopCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::pool::StopCap`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = StopCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = StopCap.$isPhantom; + + readonly id: ToField; + + private constructor(typeArgs: [], fields: StopCapFields) { + this.$fullTypeName = composeSuiType(StopCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified(): StopCapReified { + return { + typeName: StopCap.$typeName, + fullTypeName: composeSuiType(StopCap.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: StopCap.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => StopCap.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => StopCap.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => StopCap.fromBcs(data), + bcs: StopCap.bcs, + fromJSONField: (field: any) => StopCap.fromJSONField(field), + fromJSON: (json: Record) => StopCap.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => StopCap.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => StopCap.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => StopCap.fetch(client, id), + new: (fields: StopCapFields) => { + return new StopCap([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return StopCap.reified(); + } + + static phantom(): PhantomReified> { + return phantom(StopCap.reified()); + } + static get p() { + return StopCap.phantom(); + } + + static get bcs() { + return bcs.struct("StopCap", { + id: UID.bcs, + }); + } + + static fromFields(fields: Record): StopCap { + return StopCap.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): StopCap { + if (!isStopCap(item.type)) { + throw new Error("not a StopCap type"); + } + + return StopCap.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + }); + } + + static fromBcs(data: Uint8Array): StopCap { + return StopCap.fromFields(StopCap.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): StopCap { + return StopCap.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + }); + } + + static fromJSON(json: Record): StopCap { + if (json.$typeName !== StopCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return StopCap.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): StopCap { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isStopCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a StopCap object`); + } + return StopCap.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): StopCap { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isStopCap(data.bcs.type)) { + throw new Error(`object at is not a StopCap object`); + } + + return StopCap.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return StopCap.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching StopCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isStopCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a StopCap object`); + } + + return StopCap.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/bridge/user-deposit/functions.ts b/src/services/models/sui/bridge/user-deposit/functions.ts new file mode 100644 index 00000000..43247357 --- /dev/null +++ b/src/services/models/sui/bridge/user-deposit/functions.ts @@ -0,0 +1,77 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface AddArgs { + userDeposit: TransactionObjectInput; + lpAmount: bigint | TransactionArgument; + accRewardPerShareP: bigint | TransactionArgument; +} + +export function add(tx: Transaction, typeArg: string, args: AddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::user_deposit::add`, + typeArguments: [typeArg], + arguments: [obj(tx, args.userDeposit), pure(tx, args.lpAmount, `u64`), pure(tx, args.accRewardPerShareP, `u128`)], + }); +} + +export function destroyEmpty(tx: Transaction, typeArg: string, userDeposit: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::user_deposit::destroy_empty`, + typeArguments: [typeArg], + arguments: [obj(tx, userDeposit)], + }); +} + +export interface RemoveArgs { + userDeposit: TransactionObjectInput; + lpAmount: bigint | TransactionArgument; + accRewardPerShareP: bigint | TransactionArgument; +} + +export function remove(tx: Transaction, typeArg: string, args: RemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::user_deposit::remove`, + typeArguments: [typeArg], + arguments: [obj(tx, args.userDeposit), pure(tx, args.lpAmount, `u64`), pure(tx, args.accRewardPerShareP, `u128`)], + }); +} + +export function new_(tx: Transaction, typeArg: string) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::user_deposit::new`, + typeArguments: [typeArg], + arguments: [], + }); +} + +export function lpAmount(tx: Transaction, typeArg: string, userDeposit: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::user_deposit::lp_amount`, + typeArguments: [typeArg], + arguments: [obj(tx, userDeposit)], + }); +} + +export function rewardDebt(tx: Transaction, typeArg: string, userDeposit: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::user_deposit::reward_debt`, + typeArguments: [typeArg], + arguments: [obj(tx, userDeposit)], + }); +} + +export interface UpdateRewardDebtArgs { + userDeposit: TransactionObjectInput; + accRewardPerShareP: bigint | TransactionArgument; +} + +export function updateRewardDebt(tx: Transaction, typeArg: string, args: UpdateRewardDebtArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::user_deposit::update_reward_debt`, + typeArguments: [typeArg], + arguments: [obj(tx, args.userDeposit), pure(tx, args.accRewardPerShareP, `u128`)], + }); +} diff --git a/src/services/models/sui/bridge/user-deposit/structs.ts b/src/services/models/sui/bridge/user-deposit/structs.ts new file mode 100644 index 00000000..dc68ec2c --- /dev/null +++ b/src/services/models/sui/bridge/user-deposit/structs.ts @@ -0,0 +1,242 @@ +// @ts-nocheck +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { UID } from "../../sui/object/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== UserDeposit =============================== */ + +export function isUserDeposit(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V1}::user_deposit::UserDeposit` + "<"); +} + +export interface UserDepositFields { + id: ToField; + lpAmount: ToField<"u64">; + rewardDebt: ToField<"u64">; +} + +export type UserDepositReified = Reified, UserDepositFields>; + +export class UserDeposit implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::user_deposit::UserDeposit`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = UserDeposit.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = UserDeposit.$isPhantom; + + readonly id: ToField; + readonly lpAmount: ToField<"u64">; + readonly rewardDebt: ToField<"u64">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: UserDepositFields) { + this.$fullTypeName = composeSuiType(UserDeposit.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.lpAmount = fields.lpAmount; + this.rewardDebt = fields.rewardDebt; + } + + static reified>(T: T): UserDepositReified> { + return { + typeName: UserDeposit.$typeName, + fullTypeName: composeSuiType(UserDeposit.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: UserDeposit.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => UserDeposit.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => UserDeposit.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => UserDeposit.fromBcs(T, data), + bcs: UserDeposit.bcs, + fromJSONField: (field: any) => UserDeposit.fromJSONField(T, field), + fromJSON: (json: Record) => UserDeposit.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => UserDeposit.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => UserDeposit.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => UserDeposit.fetch(client, T, id), + new: (fields: UserDepositFields>) => { + return new UserDeposit([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return UserDeposit.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(UserDeposit.reified(T)); + } + static get p() { + return UserDeposit.phantom; + } + + static get bcs() { + return bcs.struct("UserDeposit", { + id: UID.bcs, + lp_amount: bcs.u64(), + reward_debt: bcs.u64(), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): UserDeposit> { + return UserDeposit.reified(typeArg).new({ + id: decodeFromFields(UID.reified(), fields.id), + lpAmount: decodeFromFields("u64", fields.lp_amount), + rewardDebt: decodeFromFields("u64", fields.reward_debt), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): UserDeposit> { + if (!isUserDeposit(item.type)) { + throw new Error("not a UserDeposit type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return UserDeposit.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + lpAmount: decodeFromFieldsWithTypes("u64", item.fields.lp_amount), + rewardDebt: decodeFromFieldsWithTypes("u64", item.fields.reward_debt), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): UserDeposit> { + return UserDeposit.fromFields(typeArg, UserDeposit.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + lpAmount: this.lpAmount.toString(), + rewardDebt: this.rewardDebt.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): UserDeposit> { + return UserDeposit.reified(typeArg).new({ + id: decodeFromJSONField(UID.reified(), field.id), + lpAmount: decodeFromJSONField("u64", field.lpAmount), + rewardDebt: decodeFromJSONField("u64", field.rewardDebt), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): UserDeposit> { + if (json.$typeName !== UserDeposit.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(UserDeposit.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return UserDeposit.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): UserDeposit> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isUserDeposit(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a UserDeposit object`); + } + return UserDeposit.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): UserDeposit> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isUserDeposit(data.bcs.type)) { + throw new Error(`object at is not a UserDeposit object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return UserDeposit.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return UserDeposit.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching UserDeposit object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isUserDeposit(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a UserDeposit object`); + } + + return UserDeposit.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/cctp-bridge/cctp-bridge-interface/functions.ts b/src/services/models/sui/cctp-bridge/cctp-bridge-interface/functions.ts new file mode 100644 index 00000000..991446ce --- /dev/null +++ b/src/services/models/sui/cctp-bridge/cctp-bridge-interface/functions.ts @@ -0,0 +1,259 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface BridgeArgs { + cctpBridge: TransactionObjectInput; + gasOracle: TransactionObjectInput; + tokenMessengerMinterState: TransactionObjectInput; + messageTransmitterState: TransactionObjectInput; + treasury: TransactionObjectInput; + denyList: TransactionObjectInput; + amount: TransactionObjectInput; + feeSuiCoin: TransactionObjectInput; + feeTokenCoin: TransactionObjectInput; + destinationChainId: number | TransactionArgument; + recipient: TransactionObjectInput; + recipientWalletAddress: TransactionObjectInput; +} + +export function bridge(tx: Transaction, typeArg: string, args: BridgeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge_interface::bridge`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.cctpBridge), + obj(tx, args.gasOracle), + obj(tx, args.tokenMessengerMinterState), + obj(tx, args.messageTransmitterState), + obj(tx, args.treasury), + obj(tx, args.denyList), + obj(tx, args.amount), + obj(tx, args.feeSuiCoin), + obj(tx, args.feeTokenCoin), + pure(tx, args.destinationChainId, `u8`), + obj(tx, args.recipient), + obj(tx, args.recipientWalletAddress), + ], + }); +} + +export interface MigrateArgs { + admin: TransactionObjectInput; + messenger: TransactionObjectInput; +} + +export function migrate(tx: Transaction, args: MigrateArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge_interface::migrate`, + arguments: [obj(tx, args.admin), obj(tx, args.messenger)], + }); +} + +export interface GetTransactionCostArgs { + cctpBridge: TransactionObjectInput; + gasOracle: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getTransactionCost(tx: Transaction, args: GetTransactionCostArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge_interface::get_transaction_cost`, + arguments: [obj(tx, args.cctpBridge), obj(tx, args.gasOracle), pure(tx, args.chainId, `u8`)], + }); +} + +export interface SetGasUsageArgs { + adminCap: TransactionObjectInput; + cctpBridge: TransactionObjectInput; + chainId: number | TransactionArgument; + value: bigint | TransactionArgument; +} + +export function setGasUsage(tx: Transaction, args: SetGasUsageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge_interface::set_gas_usage`, + arguments: [ + obj(tx, args.adminCap), + obj(tx, args.cctpBridge), + pure(tx, args.chainId, `u8`), + pure(tx, args.value, `u64`), + ], + }); +} + +export interface WithdrawFeeArgs { + adminCap: TransactionObjectInput; + cctpBridge: TransactionObjectInput; + amount: bigint | TransactionArgument; +} + +export function withdrawFee(tx: Transaction, typeArg: string, args: WithdrawFeeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge_interface::withdraw_fee`, + typeArguments: [typeArg], + arguments: [obj(tx, args.adminCap), obj(tx, args.cctpBridge), pure(tx, args.amount, `u64`)], + }); +} + +export interface GasUsageArgs { + cctpBridge: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function gasUsage(tx: Transaction, args: GasUsageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge_interface::gas_usage`, + arguments: [obj(tx, args.cctpBridge), pure(tx, args.chainId, `u8`)], + }); +} + +export function feeValue(tx: Transaction, typeArg: string, cctpBridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge_interface::fee_value`, + typeArguments: [typeArg], + arguments: [obj(tx, cctpBridge)], + }); +} + +export interface ReceiveTokensArgs { + tokenMessengerMinterState: TransactionObjectInput; + messageTransmitterState: TransactionObjectInput; + denyList: TransactionObjectInput; + treasury: TransactionObjectInput; + recipient: string | TransactionArgument; + message: Array | TransactionArgument; + signature: Array | TransactionArgument; + extraGasCoin: TransactionObjectInput; +} + +export function receiveTokens(tx: Transaction, typeArg: string, args: ReceiveTokensArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge_interface::receive_tokens`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.tokenMessengerMinterState), + obj(tx, args.messageTransmitterState), + obj(tx, args.denyList), + obj(tx, args.treasury), + pure(tx, args.recipient, `address`), + pure(tx, args.message, `vector`), + pure(tx, args.signature, `vector`), + obj(tx, args.extraGasCoin), + ], + }); +} + +export interface ChangeRecipientArgs { + cctpBridge: TransactionObjectInput; + originalMessage: Array | TransactionArgument; + originalAttestation: Array | TransactionArgument; + newRecipient: TransactionObjectInput; + tokenMessengerMinterState: TransactionObjectInput; + messageTransmitterState: TransactionObjectInput; +} + +export function changeRecipient(tx: Transaction, typeArg: string, args: ChangeRecipientArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge_interface::change_recipient`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.cctpBridge), + pure(tx, args.originalMessage, `vector`), + pure(tx, args.originalAttestation, `vector`), + obj(tx, args.newRecipient), + obj(tx, args.tokenMessengerMinterState), + obj(tx, args.messageTransmitterState), + ], + }); +} + +export interface GetBridgingCostInTokensArgs { + cctpBridge: TransactionObjectInput; + gasOracle: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getBridgingCostInTokens(tx: Transaction, args: GetBridgingCostInTokensArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge_interface::get_bridging_cost_in_tokens`, + arguments: [obj(tx, args.cctpBridge), obj(tx, args.gasOracle), pure(tx, args.chainId, `u8`)], + }); +} + +export interface GetDomainByChainIdArgs { + cctpBridge: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getDomainByChainId(tx: Transaction, args: GetDomainByChainIdArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge_interface::get_domain_by_chain_id`, + arguments: [obj(tx, args.cctpBridge), pure(tx, args.chainId, `u8`)], + }); +} + +export interface IsMessageProcessedArgs { + cctpBridge: TransactionObjectInput; + messageTransmitterState: TransactionObjectInput; + sourceChainId: number | TransactionArgument; + nonce: bigint | TransactionArgument; +} + +export function isMessageProcessed(tx: Transaction, args: IsMessageProcessedArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge_interface::is_message_processed`, + arguments: [ + obj(tx, args.cctpBridge), + obj(tx, args.messageTransmitterState), + pure(tx, args.sourceChainId, `u8`), + pure(tx, args.nonce, `u64`), + ], + }); +} + +export interface RegisterBridgeDestinationArgs { + adminCap: TransactionObjectInput; + cctpBridge: TransactionObjectInput; + chainId: number | TransactionArgument; + domain: number | TransactionArgument; +} + +export function registerBridgeDestination(tx: Transaction, args: RegisterBridgeDestinationArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge_interface::register_bridge_destination`, + arguments: [ + obj(tx, args.adminCap), + obj(tx, args.cctpBridge), + pure(tx, args.chainId, `u8`), + pure(tx, args.domain, `u32`), + ], + }); +} + +export interface SetAdminFeeShareArgs { + adminCap: TransactionObjectInput; + cctpBridge: TransactionObjectInput; + adminFeeShareBp: bigint | TransactionArgument; +} + +export function setAdminFeeShare(tx: Transaction, args: SetAdminFeeShareArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge_interface::set_admin_fee_share`, + arguments: [obj(tx, args.adminCap), obj(tx, args.cctpBridge), pure(tx, args.adminFeeShareBp, `u64`)], + }); +} + +export interface UnregisterBridgeDestinationArgs { + adminCap: TransactionObjectInput; + cctpBridge: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function unregisterBridgeDestination(tx: Transaction, args: UnregisterBridgeDestinationArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge_interface::unregister_bridge_destination`, + arguments: [obj(tx, args.adminCap), obj(tx, args.cctpBridge), pure(tx, args.chainId, `u8`)], + }); +} diff --git a/src/services/models/sui/cctp-bridge/cctp-bridge/functions.ts b/src/services/models/sui/cctp-bridge/cctp-bridge/functions.ts new file mode 100644 index 00000000..cc0a54d5 --- /dev/null +++ b/src/services/models/sui/cctp-bridge/cctp-bridge/functions.ts @@ -0,0 +1,272 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface BridgeArgs { + cctpBridge: TransactionObjectInput; + gasOracle: TransactionObjectInput; + tokenMessengerMinterState: TransactionObjectInput; + messageTransmitterState: TransactionObjectInput; + treasury: TransactionObjectInput; + denyList: TransactionObjectInput; + amount: TransactionObjectInput; + feeSuiCoin: TransactionObjectInput; + feeTokenCoin: TransactionObjectInput; + destinationChainId: number | TransactionArgument; + recipient: TransactionObjectInput; + recipientWalletAddress: TransactionObjectInput; +} + +export function bridge(tx: Transaction, typeArg: string, args: BridgeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::bridge`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.cctpBridge), + obj(tx, args.gasOracle), + obj(tx, args.tokenMessengerMinterState), + obj(tx, args.messageTransmitterState), + obj(tx, args.treasury), + obj(tx, args.denyList), + obj(tx, args.amount), + obj(tx, args.feeSuiCoin), + obj(tx, args.feeTokenCoin), + pure(tx, args.destinationChainId, `u8`), + obj(tx, args.recipient), + obj(tx, args.recipientWalletAddress), + ], + }); +} + +export function getId(tx: Transaction, cctpBridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::get_id`, + arguments: [obj(tx, cctpBridge)], + }); +} + +export function getVersion(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::get_version`, + arguments: [], + }); +} + +export function init(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::init`, + arguments: [], + }); +} + +export interface MigrateArgs { + admin: TransactionObjectInput; + cctpBridge: TransactionObjectInput; +} + +export function migrate(tx: Transaction, args: MigrateArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::migrate`, + arguments: [obj(tx, args.admin), obj(tx, args.cctpBridge)], + }); +} + +export interface GetTransactionCostArgs { + cctpBridge: TransactionObjectInput; + gasOracle: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getTransactionCost(tx: Transaction, args: GetTransactionCostArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::get_transaction_cost`, + arguments: [obj(tx, args.cctpBridge), obj(tx, args.gasOracle), pure(tx, args.chainId, `u8`)], + }); +} + +export interface SetGasUsageArgs { + cctpBridge: TransactionObjectInput; + chainId: number | TransactionArgument; + value: bigint | TransactionArgument; +} + +export function setGasUsage(tx: Transaction, args: SetGasUsageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::set_gas_usage`, + arguments: [obj(tx, args.cctpBridge), pure(tx, args.chainId, `u8`), pure(tx, args.value, `u64`)], + }); +} + +export interface WithdrawFeeArgs { + cctpBridge: TransactionObjectInput; + amount: bigint | TransactionArgument; +} + +export function withdrawFee(tx: Transaction, typeArg: string, args: WithdrawFeeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::withdraw_fee`, + typeArguments: [typeArg], + arguments: [obj(tx, args.cctpBridge), pure(tx, args.amount, `u64`)], + }); +} + +export interface GasUsageArgs { + cctpBridge: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function gasUsage(tx: Transaction, args: GasUsageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::gas_usage`, + arguments: [obj(tx, args.cctpBridge), pure(tx, args.chainId, `u8`)], + }); +} + +export function feeValue(tx: Transaction, typeArg: string, cctpBridge: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::fee_value`, + typeArguments: [typeArg], + arguments: [obj(tx, cctpBridge)], + }); +} + +export interface ReceiveTokensArgs { + tokenMessengerMinterState: TransactionObjectInput; + messageTransmitterState: TransactionObjectInput; + denyList: TransactionObjectInput; + treasury: TransactionObjectInput; + recipient: string | TransactionArgument; + message: Array | TransactionArgument; + signature: Array | TransactionArgument; + extraGasCoin: TransactionObjectInput; +} + +export function receiveTokens(tx: Transaction, typeArg: string, args: ReceiveTokensArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::receive_tokens`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.tokenMessengerMinterState), + obj(tx, args.messageTransmitterState), + obj(tx, args.denyList), + obj(tx, args.treasury), + pure(tx, args.recipient, `address`), + pure(tx, args.message, `vector`), + pure(tx, args.signature, `vector`), + obj(tx, args.extraGasCoin), + ], + }); +} + +export interface ChangeRecipientArgs { + cctpBridge: TransactionObjectInput; + originalMessage: Array | TransactionArgument; + originalAttestation: Array | TransactionArgument; + newRecipient: TransactionObjectInput; + tokenMessengerMinterState: TransactionObjectInput; + messageTransmitterState: TransactionObjectInput; +} + +export function changeRecipient(tx: Transaction, typeArg: string, args: ChangeRecipientArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::change_recipient`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.cctpBridge), + pure(tx, args.originalMessage, `vector`), + pure(tx, args.originalAttestation, `vector`), + obj(tx, args.newRecipient), + obj(tx, args.tokenMessengerMinterState), + obj(tx, args.messageTransmitterState), + ], + }); +} + +export function deserializeNonce(tx: Transaction, data: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::deserialize_nonce`, + arguments: [pure(tx, data, `vector`)], + }); +} + +export interface GetBridgingCostInTokensArgs { + cctpBridge: TransactionObjectInput; + gasOracle: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getBridgingCostInTokens(tx: Transaction, args: GetBridgingCostInTokensArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::get_bridging_cost_in_tokens`, + arguments: [obj(tx, args.cctpBridge), obj(tx, args.gasOracle), pure(tx, args.chainId, `u8`)], + }); +} + +export interface GetDomainByChainIdArgs { + cctpBridge: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getDomainByChainId(tx: Transaction, args: GetDomainByChainIdArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::get_domain_by_chain_id`, + arguments: [obj(tx, args.cctpBridge), pure(tx, args.chainId, `u8`)], + }); +} + +export interface IsMessageProcessedArgs { + cctpBridge: TransactionObjectInput; + messageTransmitterState: TransactionObjectInput; + sourceChainId: number | TransactionArgument; + nonce: bigint | TransactionArgument; +} + +export function isMessageProcessed(tx: Transaction, args: IsMessageProcessedArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::is_message_processed`, + arguments: [ + obj(tx, args.cctpBridge), + obj(tx, args.messageTransmitterState), + pure(tx, args.sourceChainId, `u8`), + pure(tx, args.nonce, `u64`), + ], + }); +} + +export interface RegisterBridgeDestinationArgs { + cctpBridge: TransactionObjectInput; + chainId: number | TransactionArgument; + domain: number | TransactionArgument; +} + +export function registerBridgeDestination(tx: Transaction, args: RegisterBridgeDestinationArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::register_bridge_destination`, + arguments: [obj(tx, args.cctpBridge), pure(tx, args.chainId, `u8`), pure(tx, args.domain, `u32`)], + }); +} + +export interface SetAdminFeeShareArgs { + cctpBridge: TransactionObjectInput; + adminFeeShareBp: bigint | TransactionArgument; +} + +export function setAdminFeeShare(tx: Transaction, args: SetAdminFeeShareArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::set_admin_fee_share`, + arguments: [obj(tx, args.cctpBridge), pure(tx, args.adminFeeShareBp, `u64`)], + }); +} + +export interface UnregisterBridgeDestinationArgs { + cctpBridge: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function unregisterBridgeDestination(tx: Transaction, args: UnregisterBridgeDestinationArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::cctp_bridge::unregister_bridge_destination`, + arguments: [obj(tx, args.cctpBridge), pure(tx, args.chainId, `u8`)], + }); +} diff --git a/src/services/models/sui/cctp-bridge/cctp-bridge/structs.ts b/src/services/models/sui/cctp-bridge/cctp-bridge/structs.ts new file mode 100644 index 00000000..3bffe30c --- /dev/null +++ b/src/services/models/sui/cctp-bridge/cctp-bridge/structs.ts @@ -0,0 +1,583 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, + ToTypeStr as ToPhantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { UID } from "../../sui/object/structs"; +import { Table } from "../../sui/table/structs"; +import { FeeCollector } from "../../utils/fee-collector/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== AdminCap =============================== */ + +export function isAdminCap(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::cctp_bridge::AdminCap`; +} + +export interface AdminCapFields { + id: ToField; +} + +export type AdminCapReified = Reified; + +export class AdminCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::cctp_bridge::AdminCap`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = AdminCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = AdminCap.$isPhantom; + + readonly id: ToField; + + private constructor(typeArgs: [], fields: AdminCapFields) { + this.$fullTypeName = composeSuiType(AdminCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified(): AdminCapReified { + return { + typeName: AdminCap.$typeName, + fullTypeName: composeSuiType(AdminCap.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: AdminCap.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => AdminCap.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => AdminCap.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => AdminCap.fromBcs(data), + bcs: AdminCap.bcs, + fromJSONField: (field: any) => AdminCap.fromJSONField(field), + fromJSON: (json: Record) => AdminCap.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => AdminCap.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => AdminCap.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => AdminCap.fetch(client, id), + new: (fields: AdminCapFields) => { + return new AdminCap([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return AdminCap.reified(); + } + + static phantom(): PhantomReified> { + return phantom(AdminCap.reified()); + } + static get p() { + return AdminCap.phantom(); + } + + static get bcs() { + return bcs.struct("AdminCap", { + id: UID.bcs, + }); + } + + static fromFields(fields: Record): AdminCap { + return AdminCap.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): AdminCap { + if (!isAdminCap(item.type)) { + throw new Error("not a AdminCap type"); + } + + return AdminCap.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + }); + } + + static fromBcs(data: Uint8Array): AdminCap { + return AdminCap.fromFields(AdminCap.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): AdminCap { + return AdminCap.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + }); + } + + static fromJSON(json: Record): AdminCap { + if (json.$typeName !== AdminCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return AdminCap.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): AdminCap { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isAdminCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a AdminCap object`); + } + return AdminCap.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): AdminCap { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isAdminCap(data.bcs.type)) { + throw new Error(`object at is not a AdminCap object`); + } + + return AdminCap.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return AdminCap.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching AdminCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isAdminCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a AdminCap object`); + } + + return AdminCap.fromSuiObjectData(res.data); + } +} + +/* ============================== FeeCollectorCap =============================== */ + +export function isFeeCollectorCap(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::cctp_bridge::FeeCollectorCap`; +} + +export interface FeeCollectorCapFields { + dummyField: ToField<"bool">; +} + +export type FeeCollectorCapReified = Reified; + +export class FeeCollectorCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::cctp_bridge::FeeCollectorCap`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = FeeCollectorCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = FeeCollectorCap.$isPhantom; + + readonly dummyField: ToField<"bool">; + + private constructor(typeArgs: [], fields: FeeCollectorCapFields) { + this.$fullTypeName = composeSuiType(FeeCollectorCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.dummyField = fields.dummyField; + } + + static reified(): FeeCollectorCapReified { + return { + typeName: FeeCollectorCap.$typeName, + fullTypeName: composeSuiType(FeeCollectorCap.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: FeeCollectorCap.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => FeeCollectorCap.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => FeeCollectorCap.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => FeeCollectorCap.fromBcs(data), + bcs: FeeCollectorCap.bcs, + fromJSONField: (field: any) => FeeCollectorCap.fromJSONField(field), + fromJSON: (json: Record) => FeeCollectorCap.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => FeeCollectorCap.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => FeeCollectorCap.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => FeeCollectorCap.fetch(client, id), + new: (fields: FeeCollectorCapFields) => { + return new FeeCollectorCap([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return FeeCollectorCap.reified(); + } + + static phantom(): PhantomReified> { + return phantom(FeeCollectorCap.reified()); + } + static get p() { + return FeeCollectorCap.phantom(); + } + + static get bcs() { + return bcs.struct("FeeCollectorCap", { + dummy_field: bcs.bool(), + }); + } + + static fromFields(fields: Record): FeeCollectorCap { + return FeeCollectorCap.reified().new({ + dummyField: decodeFromFields("bool", fields.dummy_field), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): FeeCollectorCap { + if (!isFeeCollectorCap(item.type)) { + throw new Error("not a FeeCollectorCap type"); + } + + return FeeCollectorCap.reified().new({ + dummyField: decodeFromFieldsWithTypes("bool", item.fields.dummy_field), + }); + } + + static fromBcs(data: Uint8Array): FeeCollectorCap { + return FeeCollectorCap.fromFields(FeeCollectorCap.bcs.parse(data)); + } + + toJSONField() { + return { + dummyField: this.dummyField, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): FeeCollectorCap { + return FeeCollectorCap.reified().new({ + dummyField: decodeFromJSONField("bool", field.dummyField), + }); + } + + static fromJSON(json: Record): FeeCollectorCap { + if (json.$typeName !== FeeCollectorCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return FeeCollectorCap.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): FeeCollectorCap { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isFeeCollectorCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a FeeCollectorCap object`); + } + return FeeCollectorCap.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): FeeCollectorCap { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isFeeCollectorCap(data.bcs.type)) { + throw new Error(`object at is not a FeeCollectorCap object`); + } + + return FeeCollectorCap.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return FeeCollectorCap.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching FeeCollectorCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isFeeCollectorCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a FeeCollectorCap object`); + } + + return FeeCollectorCap.fromSuiObjectData(res.data); + } +} + +/* ============================== CctpBridge =============================== */ + +export function isCctpBridge(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::cctp_bridge::CctpBridge`; +} + +export interface CctpBridgeFields { + id: ToField; + chainIdDomainMap: ToField>; + senders: ToField>; + feeCollector: ToField>>; + feeCollectorCap: ToField; + adminFeeShareBp: ToField<"u64">; + gasUsage: ToField>; +} + +export type CctpBridgeReified = Reified; + +export class CctpBridge implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::cctp_bridge::CctpBridge`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = CctpBridge.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = CctpBridge.$isPhantom; + + readonly id: ToField; + readonly chainIdDomainMap: ToField>; + readonly senders: ToField>; + readonly feeCollector: ToField>>; + readonly feeCollectorCap: ToField; + readonly adminFeeShareBp: ToField<"u64">; + readonly gasUsage: ToField>; + + private constructor(typeArgs: [], fields: CctpBridgeFields) { + this.$fullTypeName = composeSuiType(CctpBridge.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.chainIdDomainMap = fields.chainIdDomainMap; + this.senders = fields.senders; + this.feeCollector = fields.feeCollector; + this.feeCollectorCap = fields.feeCollectorCap; + this.adminFeeShareBp = fields.adminFeeShareBp; + this.gasUsage = fields.gasUsage; + } + + static reified(): CctpBridgeReified { + return { + typeName: CctpBridge.$typeName, + fullTypeName: composeSuiType(CctpBridge.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: CctpBridge.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => CctpBridge.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => CctpBridge.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => CctpBridge.fromBcs(data), + bcs: CctpBridge.bcs, + fromJSONField: (field: any) => CctpBridge.fromJSONField(field), + fromJSON: (json: Record) => CctpBridge.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => CctpBridge.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => CctpBridge.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => CctpBridge.fetch(client, id), + new: (fields: CctpBridgeFields) => { + return new CctpBridge([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return CctpBridge.reified(); + } + + static phantom(): PhantomReified> { + return phantom(CctpBridge.reified()); + } + static get p() { + return CctpBridge.phantom(); + } + + static get bcs() { + return bcs.struct("CctpBridge", { + id: UID.bcs, + chain_id_domain_map: Table.bcs, + senders: Table.bcs, + fee_collector: FeeCollector.bcs, + fee_collector_cap: FeeCollectorCap.bcs, + admin_fee_share_bp: bcs.u64(), + gas_usage: Table.bcs, + }); + } + + static fromFields(fields: Record): CctpBridge { + return CctpBridge.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + chainIdDomainMap: decodeFromFields( + Table.reified(reified.phantom("u8"), reified.phantom("u32")), + fields.chain_id_domain_map + ), + senders: decodeFromFields(Table.reified(reified.phantom("u64"), reified.phantom("address")), fields.senders), + feeCollector: decodeFromFields( + FeeCollector.reified(reified.phantom(FeeCollectorCap.reified())), + fields.fee_collector + ), + feeCollectorCap: decodeFromFields(FeeCollectorCap.reified(), fields.fee_collector_cap), + adminFeeShareBp: decodeFromFields("u64", fields.admin_fee_share_bp), + gasUsage: decodeFromFields(Table.reified(reified.phantom("u8"), reified.phantom("u64")), fields.gas_usage), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): CctpBridge { + if (!isCctpBridge(item.type)) { + throw new Error("not a CctpBridge type"); + } + + return CctpBridge.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + chainIdDomainMap: decodeFromFieldsWithTypes( + Table.reified(reified.phantom("u8"), reified.phantom("u32")), + item.fields.chain_id_domain_map + ), + senders: decodeFromFieldsWithTypes( + Table.reified(reified.phantom("u64"), reified.phantom("address")), + item.fields.senders + ), + feeCollector: decodeFromFieldsWithTypes( + FeeCollector.reified(reified.phantom(FeeCollectorCap.reified())), + item.fields.fee_collector + ), + feeCollectorCap: decodeFromFieldsWithTypes(FeeCollectorCap.reified(), item.fields.fee_collector_cap), + adminFeeShareBp: decodeFromFieldsWithTypes("u64", item.fields.admin_fee_share_bp), + gasUsage: decodeFromFieldsWithTypes( + Table.reified(reified.phantom("u8"), reified.phantom("u64")), + item.fields.gas_usage + ), + }); + } + + static fromBcs(data: Uint8Array): CctpBridge { + return CctpBridge.fromFields(CctpBridge.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + chainIdDomainMap: this.chainIdDomainMap.toJSONField(), + senders: this.senders.toJSONField(), + feeCollector: this.feeCollector.toJSONField(), + feeCollectorCap: this.feeCollectorCap.toJSONField(), + adminFeeShareBp: this.adminFeeShareBp.toString(), + gasUsage: this.gasUsage.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): CctpBridge { + return CctpBridge.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + chainIdDomainMap: decodeFromJSONField( + Table.reified(reified.phantom("u8"), reified.phantom("u32")), + field.chainIdDomainMap + ), + senders: decodeFromJSONField(Table.reified(reified.phantom("u64"), reified.phantom("address")), field.senders), + feeCollector: decodeFromJSONField( + FeeCollector.reified(reified.phantom(FeeCollectorCap.reified())), + field.feeCollector + ), + feeCollectorCap: decodeFromJSONField(FeeCollectorCap.reified(), field.feeCollectorCap), + adminFeeShareBp: decodeFromJSONField("u64", field.adminFeeShareBp), + gasUsage: decodeFromJSONField(Table.reified(reified.phantom("u8"), reified.phantom("u64")), field.gasUsage), + }); + } + + static fromJSON(json: Record): CctpBridge { + if (json.$typeName !== CctpBridge.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return CctpBridge.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): CctpBridge { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isCctpBridge(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a CctpBridge object`); + } + return CctpBridge.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): CctpBridge { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isCctpBridge(data.bcs.type)) { + throw new Error(`object at is not a CctpBridge object`); + } + + return CctpBridge.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return CctpBridge.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching CctpBridge object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isCctpBridge(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a CctpBridge object`); + } + + return CctpBridge.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/cctp-bridge/events/functions.ts b/src/services/models/sui/cctp-bridge/events/functions.ts new file mode 100644 index 00000000..97cb79b2 --- /dev/null +++ b/src/services/models/sui/cctp-bridge/events/functions.ts @@ -0,0 +1,81 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface ReceiveFeeEventArgs { + userPaySui: bigint | TransactionArgument; + userPayStable: bigint | TransactionArgument; + totalPaySui: bigint | TransactionArgument; + totalFeeSui: bigint | TransactionArgument; +} + +export function receiveFeeEvent(tx: Transaction, args: ReceiveFeeEventArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::events::receive_fee_event`, + arguments: [ + pure(tx, args.userPaySui, `u64`), + pure(tx, args.userPayStable, `u64`), + pure(tx, args.totalPaySui, `u64`), + pure(tx, args.totalFeeSui, `u64`), + ], + }); +} + +export interface TokensReceivedEventArgs { + recipient: string | TransactionArgument; + message: Array | TransactionArgument; + extraGasValue: bigint | TransactionArgument; +} + +export function tokensReceivedEvent(tx: Transaction, typeArg: string, args: TokensReceivedEventArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::events::tokens_received_event`, + typeArguments: [typeArg], + arguments: [ + pure(tx, args.recipient, `address`), + pure(tx, args.message, `vector`), + pure(tx, args.extraGasValue, `u64`), + ], + }); +} + +export interface TokensSentEventArgs { + amount: bigint | TransactionArgument; + adminFee: bigint | TransactionArgument; + sender: string | TransactionArgument; + recipient: TransactionObjectInput; + recipientWalletAddress: TransactionObjectInput; + destinationChainId: number | TransactionArgument; + nonce: bigint | TransactionArgument; +} + +export function tokensSentEvent(tx: Transaction, typeArg: string, args: TokensSentEventArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::events::tokens_sent_event`, + typeArguments: [typeArg], + arguments: [ + pure(tx, args.amount, `u64`), + pure(tx, args.adminFee, `u64`), + pure(tx, args.sender, `address`), + obj(tx, args.recipient), + obj(tx, args.recipientWalletAddress), + pure(tx, args.destinationChainId, `u8`), + pure(tx, args.nonce, `u64`), + ], + }); +} + +export interface RecipientReplacedArgs { + sender: string | TransactionArgument; + nonce: bigint | TransactionArgument; + newRecipitne: TransactionObjectInput; +} + +export function recipientReplaced(tx: Transaction, typeArg: string, args: RecipientReplacedArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::events::recipient_replaced`, + typeArguments: [typeArg], + arguments: [pure(tx, args.sender, `address`), pure(tx, args.nonce, `u64`), obj(tx, args.newRecipitne)], + }); +} diff --git a/src/services/models/sui/cctp-bridge/events/structs.ts b/src/services/models/sui/cctp-bridge/events/structs.ts new file mode 100644 index 00000000..dc8c713b --- /dev/null +++ b/src/services/models/sui/cctp-bridge/events/structs.ts @@ -0,0 +1,807 @@ +// @ts-nocheck +import { String } from "../../_dependencies/source/0x1/ascii/structs"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64, fromHEX, toHEX } from "@mysten/sui/utils"; + +/* ============================== ReceiveFeeEvent =============================== */ + +export function isReceiveFeeEvent(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::events::ReceiveFeeEvent`; +} + +export interface ReceiveFeeEventFields { + userPaySui: ToField<"u64">; + userPayStable: ToField<"u64">; + totalPaySui: ToField<"u64">; + totalFeeSui: ToField<"u64">; +} + +export type ReceiveFeeEventReified = Reified; + +export class ReceiveFeeEvent implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::events::ReceiveFeeEvent`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = ReceiveFeeEvent.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = ReceiveFeeEvent.$isPhantom; + + readonly userPaySui: ToField<"u64">; + readonly userPayStable: ToField<"u64">; + readonly totalPaySui: ToField<"u64">; + readonly totalFeeSui: ToField<"u64">; + + private constructor(typeArgs: [], fields: ReceiveFeeEventFields) { + this.$fullTypeName = composeSuiType(ReceiveFeeEvent.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.userPaySui = fields.userPaySui; + this.userPayStable = fields.userPayStable; + this.totalPaySui = fields.totalPaySui; + this.totalFeeSui = fields.totalFeeSui; + } + + static reified(): ReceiveFeeEventReified { + return { + typeName: ReceiveFeeEvent.$typeName, + fullTypeName: composeSuiType(ReceiveFeeEvent.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: ReceiveFeeEvent.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => ReceiveFeeEvent.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => ReceiveFeeEvent.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => ReceiveFeeEvent.fromBcs(data), + bcs: ReceiveFeeEvent.bcs, + fromJSONField: (field: any) => ReceiveFeeEvent.fromJSONField(field), + fromJSON: (json: Record) => ReceiveFeeEvent.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => ReceiveFeeEvent.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => ReceiveFeeEvent.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => ReceiveFeeEvent.fetch(client, id), + new: (fields: ReceiveFeeEventFields) => { + return new ReceiveFeeEvent([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return ReceiveFeeEvent.reified(); + } + + static phantom(): PhantomReified> { + return phantom(ReceiveFeeEvent.reified()); + } + static get p() { + return ReceiveFeeEvent.phantom(); + } + + static get bcs() { + return bcs.struct("ReceiveFeeEvent", { + user_pay_sui: bcs.u64(), + user_pay_stable: bcs.u64(), + total_pay_sui: bcs.u64(), + total_fee_sui: bcs.u64(), + }); + } + + static fromFields(fields: Record): ReceiveFeeEvent { + return ReceiveFeeEvent.reified().new({ + userPaySui: decodeFromFields("u64", fields.user_pay_sui), + userPayStable: decodeFromFields("u64", fields.user_pay_stable), + totalPaySui: decodeFromFields("u64", fields.total_pay_sui), + totalFeeSui: decodeFromFields("u64", fields.total_fee_sui), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): ReceiveFeeEvent { + if (!isReceiveFeeEvent(item.type)) { + throw new Error("not a ReceiveFeeEvent type"); + } + + return ReceiveFeeEvent.reified().new({ + userPaySui: decodeFromFieldsWithTypes("u64", item.fields.user_pay_sui), + userPayStable: decodeFromFieldsWithTypes("u64", item.fields.user_pay_stable), + totalPaySui: decodeFromFieldsWithTypes("u64", item.fields.total_pay_sui), + totalFeeSui: decodeFromFieldsWithTypes("u64", item.fields.total_fee_sui), + }); + } + + static fromBcs(data: Uint8Array): ReceiveFeeEvent { + return ReceiveFeeEvent.fromFields(ReceiveFeeEvent.bcs.parse(data)); + } + + toJSONField() { + return { + userPaySui: this.userPaySui.toString(), + userPayStable: this.userPayStable.toString(), + totalPaySui: this.totalPaySui.toString(), + totalFeeSui: this.totalFeeSui.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): ReceiveFeeEvent { + return ReceiveFeeEvent.reified().new({ + userPaySui: decodeFromJSONField("u64", field.userPaySui), + userPayStable: decodeFromJSONField("u64", field.userPayStable), + totalPaySui: decodeFromJSONField("u64", field.totalPaySui), + totalFeeSui: decodeFromJSONField("u64", field.totalFeeSui), + }); + } + + static fromJSON(json: Record): ReceiveFeeEvent { + if (json.$typeName !== ReceiveFeeEvent.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return ReceiveFeeEvent.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): ReceiveFeeEvent { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isReceiveFeeEvent(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a ReceiveFeeEvent object`); + } + return ReceiveFeeEvent.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): ReceiveFeeEvent { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isReceiveFeeEvent(data.bcs.type)) { + throw new Error(`object at is not a ReceiveFeeEvent object`); + } + + return ReceiveFeeEvent.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return ReceiveFeeEvent.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching ReceiveFeeEvent object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isReceiveFeeEvent(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a ReceiveFeeEvent object`); + } + + return ReceiveFeeEvent.fromSuiObjectData(res.data); + } +} + +/* ============================== TokensReceivedEvent =============================== */ + +export function isTokensReceivedEvent(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::events::TokensReceivedEvent`; +} + +export interface TokensReceivedEventFields { + token: ToField; + message: ToField; + recipient: ToField<"address">; + extraGasValue: ToField<"u64">; +} + +export type TokensReceivedEventReified = Reified; + +export class TokensReceivedEvent implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::events::TokensReceivedEvent`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = TokensReceivedEvent.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = TokensReceivedEvent.$isPhantom; + + readonly token: ToField; + readonly message: ToField; + readonly recipient: ToField<"address">; + readonly extraGasValue: ToField<"u64">; + + private constructor(typeArgs: [], fields: TokensReceivedEventFields) { + this.$fullTypeName = composeSuiType(TokensReceivedEvent.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.token = fields.token; + this.message = fields.message; + this.recipient = fields.recipient; + this.extraGasValue = fields.extraGasValue; + } + + static reified(): TokensReceivedEventReified { + return { + typeName: TokensReceivedEvent.$typeName, + fullTypeName: composeSuiType(TokensReceivedEvent.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: TokensReceivedEvent.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => TokensReceivedEvent.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => TokensReceivedEvent.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => TokensReceivedEvent.fromBcs(data), + bcs: TokensReceivedEvent.bcs, + fromJSONField: (field: any) => TokensReceivedEvent.fromJSONField(field), + fromJSON: (json: Record) => TokensReceivedEvent.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => TokensReceivedEvent.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => TokensReceivedEvent.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => TokensReceivedEvent.fetch(client, id), + new: (fields: TokensReceivedEventFields) => { + return new TokensReceivedEvent([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return TokensReceivedEvent.reified(); + } + + static phantom(): PhantomReified> { + return phantom(TokensReceivedEvent.reified()); + } + static get p() { + return TokensReceivedEvent.phantom(); + } + + static get bcs() { + return bcs.struct("TokensReceivedEvent", { + token: String.bcs, + message: String.bcs, + recipient: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + extra_gas_value: bcs.u64(), + }); + } + + static fromFields(fields: Record): TokensReceivedEvent { + return TokensReceivedEvent.reified().new({ + token: decodeFromFields(String.reified(), fields.token), + message: decodeFromFields(String.reified(), fields.message), + recipient: decodeFromFields("address", fields.recipient), + extraGasValue: decodeFromFields("u64", fields.extra_gas_value), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): TokensReceivedEvent { + if (!isTokensReceivedEvent(item.type)) { + throw new Error("not a TokensReceivedEvent type"); + } + + return TokensReceivedEvent.reified().new({ + token: decodeFromFieldsWithTypes(String.reified(), item.fields.token), + message: decodeFromFieldsWithTypes(String.reified(), item.fields.message), + recipient: decodeFromFieldsWithTypes("address", item.fields.recipient), + extraGasValue: decodeFromFieldsWithTypes("u64", item.fields.extra_gas_value), + }); + } + + static fromBcs(data: Uint8Array): TokensReceivedEvent { + return TokensReceivedEvent.fromFields(TokensReceivedEvent.bcs.parse(data)); + } + + toJSONField() { + return { + token: this.token, + message: this.message, + recipient: this.recipient, + extraGasValue: this.extraGasValue.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): TokensReceivedEvent { + return TokensReceivedEvent.reified().new({ + token: decodeFromJSONField(String.reified(), field.token), + message: decodeFromJSONField(String.reified(), field.message), + recipient: decodeFromJSONField("address", field.recipient), + extraGasValue: decodeFromJSONField("u64", field.extraGasValue), + }); + } + + static fromJSON(json: Record): TokensReceivedEvent { + if (json.$typeName !== TokensReceivedEvent.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return TokensReceivedEvent.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): TokensReceivedEvent { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTokensReceivedEvent(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a TokensReceivedEvent object`); + } + return TokensReceivedEvent.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): TokensReceivedEvent { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTokensReceivedEvent(data.bcs.type)) { + throw new Error(`object at is not a TokensReceivedEvent object`); + } + + return TokensReceivedEvent.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return TokensReceivedEvent.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching TokensReceivedEvent object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTokensReceivedEvent(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a TokensReceivedEvent object`); + } + + return TokensReceivedEvent.fromSuiObjectData(res.data); + } +} + +/* ============================== TokensSentEvent =============================== */ + +export function isTokensSentEvent(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::events::TokensSentEvent`; +} + +export interface TokensSentEventFields { + token: ToField; + amount: ToField<"u64">; + adminFee: ToField<"u64">; + sender: ToField<"address">; + recipient: ToField; + recipientWalletAddress: ToField; + destinationChainId: ToField<"u8">; + nonce: ToField<"u64">; +} + +export type TokensSentEventReified = Reified; + +export class TokensSentEvent implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::events::TokensSentEvent`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = TokensSentEvent.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = TokensSentEvent.$isPhantom; + + readonly token: ToField; + readonly amount: ToField<"u64">; + readonly adminFee: ToField<"u64">; + readonly sender: ToField<"address">; + readonly recipient: ToField; + readonly recipientWalletAddress: ToField; + readonly destinationChainId: ToField<"u8">; + readonly nonce: ToField<"u64">; + + private constructor(typeArgs: [], fields: TokensSentEventFields) { + this.$fullTypeName = composeSuiType(TokensSentEvent.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.token = fields.token; + this.amount = fields.amount; + this.adminFee = fields.adminFee; + this.sender = fields.sender; + this.recipient = fields.recipient; + this.recipientWalletAddress = fields.recipientWalletAddress; + this.destinationChainId = fields.destinationChainId; + this.nonce = fields.nonce; + } + + static reified(): TokensSentEventReified { + return { + typeName: TokensSentEvent.$typeName, + fullTypeName: composeSuiType(TokensSentEvent.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: TokensSentEvent.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => TokensSentEvent.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => TokensSentEvent.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => TokensSentEvent.fromBcs(data), + bcs: TokensSentEvent.bcs, + fromJSONField: (field: any) => TokensSentEvent.fromJSONField(field), + fromJSON: (json: Record) => TokensSentEvent.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => TokensSentEvent.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => TokensSentEvent.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => TokensSentEvent.fetch(client, id), + new: (fields: TokensSentEventFields) => { + return new TokensSentEvent([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return TokensSentEvent.reified(); + } + + static phantom(): PhantomReified> { + return phantom(TokensSentEvent.reified()); + } + static get p() { + return TokensSentEvent.phantom(); + } + + static get bcs() { + return bcs.struct("TokensSentEvent", { + token: String.bcs, + amount: bcs.u64(), + admin_fee: bcs.u64(), + sender: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + recipient: String.bcs, + recipient_wallet_address: String.bcs, + destination_chain_id: bcs.u8(), + nonce: bcs.u64(), + }); + } + + static fromFields(fields: Record): TokensSentEvent { + return TokensSentEvent.reified().new({ + token: decodeFromFields(String.reified(), fields.token), + amount: decodeFromFields("u64", fields.amount), + adminFee: decodeFromFields("u64", fields.admin_fee), + sender: decodeFromFields("address", fields.sender), + recipient: decodeFromFields(String.reified(), fields.recipient), + recipientWalletAddress: decodeFromFields(String.reified(), fields.recipient_wallet_address), + destinationChainId: decodeFromFields("u8", fields.destination_chain_id), + nonce: decodeFromFields("u64", fields.nonce), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): TokensSentEvent { + if (!isTokensSentEvent(item.type)) { + throw new Error("not a TokensSentEvent type"); + } + + return TokensSentEvent.reified().new({ + token: decodeFromFieldsWithTypes(String.reified(), item.fields.token), + amount: decodeFromFieldsWithTypes("u64", item.fields.amount), + adminFee: decodeFromFieldsWithTypes("u64", item.fields.admin_fee), + sender: decodeFromFieldsWithTypes("address", item.fields.sender), + recipient: decodeFromFieldsWithTypes(String.reified(), item.fields.recipient), + recipientWalletAddress: decodeFromFieldsWithTypes(String.reified(), item.fields.recipient_wallet_address), + destinationChainId: decodeFromFieldsWithTypes("u8", item.fields.destination_chain_id), + nonce: decodeFromFieldsWithTypes("u64", item.fields.nonce), + }); + } + + static fromBcs(data: Uint8Array): TokensSentEvent { + return TokensSentEvent.fromFields(TokensSentEvent.bcs.parse(data)); + } + + toJSONField() { + return { + token: this.token, + amount: this.amount.toString(), + adminFee: this.adminFee.toString(), + sender: this.sender, + recipient: this.recipient, + recipientWalletAddress: this.recipientWalletAddress, + destinationChainId: this.destinationChainId, + nonce: this.nonce.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): TokensSentEvent { + return TokensSentEvent.reified().new({ + token: decodeFromJSONField(String.reified(), field.token), + amount: decodeFromJSONField("u64", field.amount), + adminFee: decodeFromJSONField("u64", field.adminFee), + sender: decodeFromJSONField("address", field.sender), + recipient: decodeFromJSONField(String.reified(), field.recipient), + recipientWalletAddress: decodeFromJSONField(String.reified(), field.recipientWalletAddress), + destinationChainId: decodeFromJSONField("u8", field.destinationChainId), + nonce: decodeFromJSONField("u64", field.nonce), + }); + } + + static fromJSON(json: Record): TokensSentEvent { + if (json.$typeName !== TokensSentEvent.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return TokensSentEvent.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): TokensSentEvent { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTokensSentEvent(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a TokensSentEvent object`); + } + return TokensSentEvent.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): TokensSentEvent { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTokensSentEvent(data.bcs.type)) { + throw new Error(`object at is not a TokensSentEvent object`); + } + + return TokensSentEvent.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return TokensSentEvent.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching TokensSentEvent object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTokensSentEvent(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a TokensSentEvent object`); + } + + return TokensSentEvent.fromSuiObjectData(res.data); + } +} + +/* ============================== RecipientReplaced =============================== */ + +export function isRecipientReplaced(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::events::RecipientReplaced`; +} + +export interface RecipientReplacedFields { + token: ToField; + sender: ToField<"address">; + nonce: ToField<"u64">; + newRecipitne: ToField; +} + +export type RecipientReplacedReified = Reified; + +export class RecipientReplaced implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::events::RecipientReplaced`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = RecipientReplaced.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = RecipientReplaced.$isPhantom; + + readonly token: ToField; + readonly sender: ToField<"address">; + readonly nonce: ToField<"u64">; + readonly newRecipitne: ToField; + + private constructor(typeArgs: [], fields: RecipientReplacedFields) { + this.$fullTypeName = composeSuiType(RecipientReplaced.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.token = fields.token; + this.sender = fields.sender; + this.nonce = fields.nonce; + this.newRecipitne = fields.newRecipitne; + } + + static reified(): RecipientReplacedReified { + return { + typeName: RecipientReplaced.$typeName, + fullTypeName: composeSuiType(RecipientReplaced.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: RecipientReplaced.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => RecipientReplaced.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => RecipientReplaced.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => RecipientReplaced.fromBcs(data), + bcs: RecipientReplaced.bcs, + fromJSONField: (field: any) => RecipientReplaced.fromJSONField(field), + fromJSON: (json: Record) => RecipientReplaced.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => RecipientReplaced.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => RecipientReplaced.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => RecipientReplaced.fetch(client, id), + new: (fields: RecipientReplacedFields) => { + return new RecipientReplaced([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return RecipientReplaced.reified(); + } + + static phantom(): PhantomReified> { + return phantom(RecipientReplaced.reified()); + } + static get p() { + return RecipientReplaced.phantom(); + } + + static get bcs() { + return bcs.struct("RecipientReplaced", { + token: String.bcs, + sender: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + nonce: bcs.u64(), + new_recipitne: String.bcs, + }); + } + + static fromFields(fields: Record): RecipientReplaced { + return RecipientReplaced.reified().new({ + token: decodeFromFields(String.reified(), fields.token), + sender: decodeFromFields("address", fields.sender), + nonce: decodeFromFields("u64", fields.nonce), + newRecipitne: decodeFromFields(String.reified(), fields.new_recipitne), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): RecipientReplaced { + if (!isRecipientReplaced(item.type)) { + throw new Error("not a RecipientReplaced type"); + } + + return RecipientReplaced.reified().new({ + token: decodeFromFieldsWithTypes(String.reified(), item.fields.token), + sender: decodeFromFieldsWithTypes("address", item.fields.sender), + nonce: decodeFromFieldsWithTypes("u64", item.fields.nonce), + newRecipitne: decodeFromFieldsWithTypes(String.reified(), item.fields.new_recipitne), + }); + } + + static fromBcs(data: Uint8Array): RecipientReplaced { + return RecipientReplaced.fromFields(RecipientReplaced.bcs.parse(data)); + } + + toJSONField() { + return { + token: this.token, + sender: this.sender, + nonce: this.nonce.toString(), + newRecipitne: this.newRecipitne, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): RecipientReplaced { + return RecipientReplaced.reified().new({ + token: decodeFromJSONField(String.reified(), field.token), + sender: decodeFromJSONField("address", field.sender), + nonce: decodeFromJSONField("u64", field.nonce), + newRecipitne: decodeFromJSONField(String.reified(), field.newRecipitne), + }); + } + + static fromJSON(json: Record): RecipientReplaced { + if (json.$typeName !== RecipientReplaced.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return RecipientReplaced.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): RecipientReplaced { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isRecipientReplaced(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a RecipientReplaced object`); + } + return RecipientReplaced.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): RecipientReplaced { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isRecipientReplaced(data.bcs.type)) { + throw new Error(`object at is not a RecipientReplaced object`); + } + + return RecipientReplaced.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return RecipientReplaced.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching RecipientReplaced object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isRecipientReplaced(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a RecipientReplaced object`); + } + + return RecipientReplaced.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/cctp-bridge/index.ts b/src/services/models/sui/cctp-bridge/index.ts new file mode 100644 index 00000000..12959240 --- /dev/null +++ b/src/services/models/sui/cctp-bridge/index.ts @@ -0,0 +1,33 @@ +// @ts-nocheck +import { compressSuiType } from "../_framework/util"; + +class PackageAddress { + private static $PACKAGE_ID = ""; + private static $PUBLISHED_AT = ""; + private static $PKG_V = []; + get PACKAGE_ID() { + return compressSuiType(PackageAddress.$PACKAGE_ID); + } + get PUBLISHED_AT() { + return compressSuiType(PackageAddress.$PUBLISHED_AT); + } + get PKG_V1() { + return compressSuiType(PackageAddress.$PKG_V[1]); + } + setPackageId(address: string): void { + PackageAddress.$PACKAGE_ID = address; + } + setPublishedAt(address: string): void { + PackageAddress.$PUBLISHED_AT = address; + } + setPkgV(v: number, address: string): void { + PackageAddress.$PKG_V[v] = address; + } + setAddress(address: string, pkgV1?: string) { + PackageAddress.$PACKAGE_ID = address; + PackageAddress.$PUBLISHED_AT = address; + PackageAddress.$PKG_V[1] = pkgV1 || address; + } +} +const packageAddress = new PackageAddress(); +export = packageAddress; diff --git a/src/services/models/sui/cctp-bridge/init.ts b/src/services/models/sui/cctp-bridge/init.ts new file mode 100644 index 00000000..f7145f93 --- /dev/null +++ b/src/services/models/sui/cctp-bridge/init.ts @@ -0,0 +1,16 @@ +// @ts-nocheck +import * as cctpBridge from "./cctp-bridge/structs"; +import * as events from "./events/structs"; +import * as messageTransmitterAuthenticator from "./message-transmitter-authenticator/structs"; +import { StructClassLoader } from "../_framework/loader"; + +export function registerClasses(loader: StructClassLoader) { + loader.register(messageTransmitterAuthenticator.MessageTransmitterAuthenticator); + loader.register(events.ReceiveFeeEvent); + loader.register(events.TokensReceivedEvent); + loader.register(events.TokensSentEvent); + loader.register(events.RecipientReplaced); + loader.register(cctpBridge.AdminCap); + loader.register(cctpBridge.FeeCollectorCap); + loader.register(cctpBridge.CctpBridge); +} diff --git a/src/services/models/sui/cctp-bridge/message-transmitter-authenticator/functions.ts b/src/services/models/sui/cctp-bridge/message-transmitter-authenticator/functions.ts new file mode 100644 index 00000000..db2d3861 --- /dev/null +++ b/src/services/models/sui/cctp-bridge/message-transmitter-authenticator/functions.ts @@ -0,0 +1,10 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { Transaction } from "@mysten/sui/transactions"; + +export function new_(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::message_transmitter_authenticator::new`, + arguments: [], + }); +} diff --git a/src/services/models/sui/cctp-bridge/message-transmitter-authenticator/structs.ts b/src/services/models/sui/cctp-bridge/message-transmitter-authenticator/structs.ts new file mode 100644 index 00000000..31473fb7 --- /dev/null +++ b/src/services/models/sui/cctp-bridge/message-transmitter-authenticator/structs.ts @@ -0,0 +1,183 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== MessageTransmitterAuthenticator =============================== */ + +export function isMessageTransmitterAuthenticator(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::message_transmitter_authenticator::MessageTransmitterAuthenticator`; +} + +export interface MessageTransmitterAuthenticatorFields { + dummyField: ToField<"bool">; +} + +export type MessageTransmitterAuthenticatorReified = Reified< + MessageTransmitterAuthenticator, + MessageTransmitterAuthenticatorFields +>; + +export class MessageTransmitterAuthenticator implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::message_transmitter_authenticator::MessageTransmitterAuthenticator`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = MessageTransmitterAuthenticator.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = MessageTransmitterAuthenticator.$isPhantom; + + readonly dummyField: ToField<"bool">; + + private constructor(typeArgs: [], fields: MessageTransmitterAuthenticatorFields) { + this.$fullTypeName = composeSuiType(MessageTransmitterAuthenticator.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.dummyField = fields.dummyField; + } + + static reified(): MessageTransmitterAuthenticatorReified { + return { + typeName: MessageTransmitterAuthenticator.$typeName, + fullTypeName: composeSuiType(MessageTransmitterAuthenticator.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: MessageTransmitterAuthenticator.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => MessageTransmitterAuthenticator.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => MessageTransmitterAuthenticator.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => MessageTransmitterAuthenticator.fromBcs(data), + bcs: MessageTransmitterAuthenticator.bcs, + fromJSONField: (field: any) => MessageTransmitterAuthenticator.fromJSONField(field), + fromJSON: (json: Record) => MessageTransmitterAuthenticator.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => MessageTransmitterAuthenticator.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => MessageTransmitterAuthenticator.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => MessageTransmitterAuthenticator.fetch(client, id), + new: (fields: MessageTransmitterAuthenticatorFields) => { + return new MessageTransmitterAuthenticator([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return MessageTransmitterAuthenticator.reified(); + } + + static phantom(): PhantomReified> { + return phantom(MessageTransmitterAuthenticator.reified()); + } + static get p() { + return MessageTransmitterAuthenticator.phantom(); + } + + static get bcs() { + return bcs.struct("MessageTransmitterAuthenticator", { + dummy_field: bcs.bool(), + }); + } + + static fromFields(fields: Record): MessageTransmitterAuthenticator { + return MessageTransmitterAuthenticator.reified().new({ + dummyField: decodeFromFields("bool", fields.dummy_field), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): MessageTransmitterAuthenticator { + if (!isMessageTransmitterAuthenticator(item.type)) { + throw new Error("not a MessageTransmitterAuthenticator type"); + } + + return MessageTransmitterAuthenticator.reified().new({ + dummyField: decodeFromFieldsWithTypes("bool", item.fields.dummy_field), + }); + } + + static fromBcs(data: Uint8Array): MessageTransmitterAuthenticator { + return MessageTransmitterAuthenticator.fromFields(MessageTransmitterAuthenticator.bcs.parse(data)); + } + + toJSONField() { + return { + dummyField: this.dummyField, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): MessageTransmitterAuthenticator { + return MessageTransmitterAuthenticator.reified().new({ + dummyField: decodeFromJSONField("bool", field.dummyField), + }); + } + + static fromJSON(json: Record): MessageTransmitterAuthenticator { + if (json.$typeName !== MessageTransmitterAuthenticator.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return MessageTransmitterAuthenticator.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): MessageTransmitterAuthenticator { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isMessageTransmitterAuthenticator(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a MessageTransmitterAuthenticator object`); + } + return MessageTransmitterAuthenticator.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): MessageTransmitterAuthenticator { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isMessageTransmitterAuthenticator(data.bcs.type)) { + throw new Error(`object at is not a MessageTransmitterAuthenticator object`); + } + + return MessageTransmitterAuthenticator.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return MessageTransmitterAuthenticator.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching MessageTransmitterAuthenticator object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isMessageTransmitterAuthenticator(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a MessageTransmitterAuthenticator object`); + } + + return MessageTransmitterAuthenticator.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/gas-oracle/gas-oracle-interface/functions.ts b/src/services/models/sui/gas-oracle/gas-oracle-interface/functions.ts new file mode 100644 index 00000000..632b4e26 --- /dev/null +++ b/src/services/models/sui/gas-oracle/gas-oracle-interface/functions.ts @@ -0,0 +1,182 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface CrossRateArgs { + oracle: TransactionObjectInput; + otherChainId: number | TransactionArgument; +} + +export function crossRate(tx: Transaction, args: CrossRateArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle_interface::cross_rate`, + arguments: [obj(tx, args.oracle), pure(tx, args.otherChainId, `u8`)], + }); +} + +export interface GasPriceArgs { + gasOracle: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function gasPrice(tx: Transaction, args: GasPriceArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle_interface::gas_price`, + arguments: [obj(tx, args.gasOracle), pure(tx, args.chainId, `u8`)], + }); +} + +export interface GetChainDataArgs { + oracle: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getChainData(tx: Transaction, args: GetChainDataArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle_interface::get_chain_data`, + arguments: [obj(tx, args.oracle), pure(tx, args.chainId, `u8`)], + }); +} + +export interface GetTransactionGasCostInNativeTokenArgs { + oracle: TransactionObjectInput; + otherChainId: number | TransactionArgument; + gasAmount: bigint | TransactionArgument; +} + +export function getTransactionGasCostInNativeToken(tx: Transaction, args: GetTransactionGasCostInNativeTokenArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle_interface::get_transaction_gas_cost_in_native_token`, + arguments: [obj(tx, args.oracle), pure(tx, args.otherChainId, `u8`), pure(tx, args.gasAmount, `u64`)], + }); +} + +export interface GetTransactionGasCostInStableArgs { + oracle: TransactionObjectInput; + otherChainId: number | TransactionArgument; + gasAmount: bigint | TransactionArgument; + stableTokenDecimals: number | TransactionArgument; +} + +export function getTransactionGasCostInStable(tx: Transaction, args: GetTransactionGasCostInStableArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle_interface::get_transaction_gas_cost_in_stable`, + arguments: [ + obj(tx, args.oracle), + pure(tx, args.otherChainId, `u8`), + pure(tx, args.gasAmount, `u64`), + pure(tx, args.stableTokenDecimals, `u8`), + ], + }); +} + +export interface MigrateArgs { + adminCap: TransactionObjectInput; + gasOracle: TransactionObjectInput; +} + +export function migrate(tx: Transaction, args: MigrateArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle_interface::migrate`, + arguments: [obj(tx, args.adminCap), obj(tx, args.gasOracle)], + }); +} + +export interface PriceArgs { + gasOracle: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function price(tx: Transaction, args: PriceArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle_interface::price`, + arguments: [obj(tx, args.gasOracle), pure(tx, args.chainId, `u8`)], + }); +} + +export interface SetChainDataArgs { + adminCap: TransactionObjectInput; + oracle: TransactionObjectInput; + chainId: number | TransactionArgument; + gasPrice: bigint | TransactionArgument; + price: bigint | TransactionArgument; +} + +export function setChainData(tx: Transaction, args: SetChainDataArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle_interface::set_chain_data`, + arguments: [ + obj(tx, args.adminCap), + obj(tx, args.oracle), + pure(tx, args.chainId, `u8`), + pure(tx, args.gasPrice, `u128`), + pure(tx, args.price, `u128`), + ], + }); +} + +export interface SetGasPriceArgs { + adminCap: TransactionObjectInput; + oracle: TransactionObjectInput; + chainId: number | TransactionArgument; + gasPrice: bigint | TransactionArgument; +} + +export function setGasPrice(tx: Transaction, args: SetGasPriceArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle_interface::set_gas_price`, + arguments: [ + obj(tx, args.adminCap), + obj(tx, args.oracle), + pure(tx, args.chainId, `u8`), + pure(tx, args.gasPrice, `u128`), + ], + }); +} + +export interface SetPriceArgs { + adminCap: TransactionObjectInput; + oracle: TransactionObjectInput; + chainId: number | TransactionArgument; + price: bigint | TransactionArgument; +} + +export function setPrice(tx: Transaction, args: SetPriceArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle_interface::set_price`, + arguments: [ + obj(tx, args.adminCap), + obj(tx, args.oracle), + pure(tx, args.chainId, `u8`), + pure(tx, args.price, `u128`), + ], + }); +} + +export interface StableToSuiAmountArgs { + gasOracle: TransactionObjectInput; + amount: bigint | TransactionArgument; + stableTokenDecimals: number | TransactionArgument; +} + +export function stableToSuiAmount(tx: Transaction, args: StableToSuiAmountArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle_interface::stable_to_sui_amount`, + arguments: [obj(tx, args.gasOracle), pure(tx, args.amount, `u64`), pure(tx, args.stableTokenDecimals, `u8`)], + }); +} + +export function chainDataGasPrice(tx: Transaction, chainData: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle_interface::chain_data_gas_price`, + arguments: [obj(tx, chainData)], + }); +} + +export function chainDataPrice(tx: Transaction, chainData: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle_interface::chain_data_price`, + arguments: [obj(tx, chainData)], + }); +} diff --git a/src/services/models/sui/gas-oracle/gas-oracle/functions.ts b/src/services/models/sui/gas-oracle/gas-oracle/functions.ts new file mode 100644 index 00000000..a9c85490 --- /dev/null +++ b/src/services/models/sui/gas-oracle/gas-oracle/functions.ts @@ -0,0 +1,179 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function new_(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle::new`, + arguments: [], + }); +} + +export interface CrossRateArgs { + oracle: TransactionObjectInput; + otherChainId: number | TransactionArgument; +} + +export function crossRate(tx: Transaction, args: CrossRateArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle::cross_rate`, + arguments: [obj(tx, args.oracle), pure(tx, args.otherChainId, `u8`)], + }); +} + +export function gasPrice(tx: Transaction, chainData: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle::gas_price`, + arguments: [obj(tx, chainData)], + }); +} + +export interface GetChainDataArgs { + oracle: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getChainData(tx: Transaction, args: GetChainDataArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle::get_chain_data`, + arguments: [obj(tx, args.oracle), pure(tx, args.chainId, `u8`)], + }); +} + +export function getId(tx: Transaction, oracle: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle::get_id`, + arguments: [obj(tx, oracle)], + }); +} + +export function getOwnChainData(tx: Transaction, oracle: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle::get_own_chain_data`, + arguments: [obj(tx, oracle)], + }); +} + +export interface GetTransactionGasCostInNativeTokenArgs { + oracle: TransactionObjectInput; + otherChainId: number | TransactionArgument; + gasAmount: bigint | TransactionArgument; +} + +export function getTransactionGasCostInNativeToken(tx: Transaction, args: GetTransactionGasCostInNativeTokenArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle::get_transaction_gas_cost_in_native_token`, + arguments: [obj(tx, args.oracle), pure(tx, args.otherChainId, `u8`), pure(tx, args.gasAmount, `u64`)], + }); +} + +export interface GetTransactionGasCostInStableArgs { + oracle: TransactionObjectInput; + otherChainId: number | TransactionArgument; + gasAmount: bigint | TransactionArgument; + stableTokenDecimals: number | TransactionArgument; +} + +export function getTransactionGasCostInStable(tx: Transaction, args: GetTransactionGasCostInStableArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle::get_transaction_gas_cost_in_stable`, + arguments: [ + obj(tx, args.oracle), + pure(tx, args.otherChainId, `u8`), + pure(tx, args.gasAmount, `u64`), + pure(tx, args.stableTokenDecimals, `u8`), + ], + }); +} + +export function getVersion(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle::get_version`, + arguments: [], + }); +} + +export function init(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle::init`, + arguments: [], + }); +} + +export interface MigrateArgs { + adminCap: TransactionObjectInput; + gasOracle: TransactionObjectInput; +} + +export function migrate(tx: Transaction, args: MigrateArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle::migrate`, + arguments: [obj(tx, args.adminCap), obj(tx, args.gasOracle)], + }); +} + +export function price(tx: Transaction, chainData: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle::price`, + arguments: [obj(tx, chainData)], + }); +} + +export interface SetChainDataArgs { + oracle: TransactionObjectInput; + chainId: number | TransactionArgument; + gasPrice: bigint | TransactionArgument; + price: bigint | TransactionArgument; +} + +export function setChainData(tx: Transaction, args: SetChainDataArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle::set_chain_data`, + arguments: [ + obj(tx, args.oracle), + pure(tx, args.chainId, `u8`), + pure(tx, args.gasPrice, `u128`), + pure(tx, args.price, `u128`), + ], + }); +} + +export interface SetGasPriceArgs { + oracle: TransactionObjectInput; + chainId: number | TransactionArgument; + gasPrice: bigint | TransactionArgument; +} + +export function setGasPrice(tx: Transaction, args: SetGasPriceArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle::set_gas_price`, + arguments: [obj(tx, args.oracle), pure(tx, args.chainId, `u8`), pure(tx, args.gasPrice, `u128`)], + }); +} + +export interface SetPriceArgs { + oracle: TransactionObjectInput; + chainId: number | TransactionArgument; + price: bigint | TransactionArgument; +} + +export function setPrice(tx: Transaction, args: SetPriceArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle::set_price`, + arguments: [obj(tx, args.oracle), pure(tx, args.chainId, `u8`), pure(tx, args.price, `u128`)], + }); +} + +export interface StableToSuiAmountArgs { + gasOracle: TransactionObjectInput; + amount: bigint | TransactionArgument; + stableTokenDecimals: number | TransactionArgument; +} + +export function stableToSuiAmount(tx: Transaction, args: StableToSuiAmountArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::gas_oracle::stable_to_sui_amount`, + arguments: [obj(tx, args.gasOracle), pure(tx, args.amount, `u64`), pure(tx, args.stableTokenDecimals, `u8`)], + }); +} diff --git a/src/services/models/sui/gas-oracle/gas-oracle/structs.ts b/src/services/models/sui/gas-oracle/gas-oracle/structs.ts new file mode 100644 index 00000000..948e3f9d --- /dev/null +++ b/src/services/models/sui/gas-oracle/gas-oracle/structs.ts @@ -0,0 +1,529 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, + ToTypeStr as ToPhantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { UID } from "../../sui/object/structs"; +import { Table } from "../../sui/table/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== AdminCap =============================== */ + +export function isAdminCap(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::gas_oracle::AdminCap`; +} + +export interface AdminCapFields { + id: ToField; +} + +export type AdminCapReified = Reified; + +export class AdminCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::gas_oracle::AdminCap`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = AdminCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = AdminCap.$isPhantom; + + readonly id: ToField; + + private constructor(typeArgs: [], fields: AdminCapFields) { + this.$fullTypeName = composeSuiType(AdminCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified(): AdminCapReified { + return { + typeName: AdminCap.$typeName, + fullTypeName: composeSuiType(AdminCap.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: AdminCap.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => AdminCap.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => AdminCap.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => AdminCap.fromBcs(data), + bcs: AdminCap.bcs, + fromJSONField: (field: any) => AdminCap.fromJSONField(field), + fromJSON: (json: Record) => AdminCap.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => AdminCap.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => AdminCap.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => AdminCap.fetch(client, id), + new: (fields: AdminCapFields) => { + return new AdminCap([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return AdminCap.reified(); + } + + static phantom(): PhantomReified> { + return phantom(AdminCap.reified()); + } + static get p() { + return AdminCap.phantom(); + } + + static get bcs() { + return bcs.struct("AdminCap", { + id: UID.bcs, + }); + } + + static fromFields(fields: Record): AdminCap { + return AdminCap.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): AdminCap { + if (!isAdminCap(item.type)) { + throw new Error("not a AdminCap type"); + } + + return AdminCap.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + }); + } + + static fromBcs(data: Uint8Array): AdminCap { + return AdminCap.fromFields(AdminCap.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): AdminCap { + return AdminCap.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + }); + } + + static fromJSON(json: Record): AdminCap { + if (json.$typeName !== AdminCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return AdminCap.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): AdminCap { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isAdminCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a AdminCap object`); + } + return AdminCap.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): AdminCap { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isAdminCap(data.bcs.type)) { + throw new Error(`object at is not a AdminCap object`); + } + + return AdminCap.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return AdminCap.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching AdminCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isAdminCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a AdminCap object`); + } + + return AdminCap.fromSuiObjectData(res.data); + } +} + +/* ============================== ChainData =============================== */ + +export function isChainData(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::gas_oracle::ChainData`; +} + +export interface ChainDataFields { + gasPrice: ToField<"u128">; + price: ToField<"u128">; +} + +export type ChainDataReified = Reified; + +export class ChainData implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::gas_oracle::ChainData`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = ChainData.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = ChainData.$isPhantom; + + readonly gasPrice: ToField<"u128">; + readonly price: ToField<"u128">; + + private constructor(typeArgs: [], fields: ChainDataFields) { + this.$fullTypeName = composeSuiType(ChainData.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.gasPrice = fields.gasPrice; + this.price = fields.price; + } + + static reified(): ChainDataReified { + return { + typeName: ChainData.$typeName, + fullTypeName: composeSuiType(ChainData.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: ChainData.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => ChainData.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => ChainData.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => ChainData.fromBcs(data), + bcs: ChainData.bcs, + fromJSONField: (field: any) => ChainData.fromJSONField(field), + fromJSON: (json: Record) => ChainData.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => ChainData.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => ChainData.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => ChainData.fetch(client, id), + new: (fields: ChainDataFields) => { + return new ChainData([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return ChainData.reified(); + } + + static phantom(): PhantomReified> { + return phantom(ChainData.reified()); + } + static get p() { + return ChainData.phantom(); + } + + static get bcs() { + return bcs.struct("ChainData", { + gas_price: bcs.u128(), + price: bcs.u128(), + }); + } + + static fromFields(fields: Record): ChainData { + return ChainData.reified().new({ + gasPrice: decodeFromFields("u128", fields.gas_price), + price: decodeFromFields("u128", fields.price), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): ChainData { + if (!isChainData(item.type)) { + throw new Error("not a ChainData type"); + } + + return ChainData.reified().new({ + gasPrice: decodeFromFieldsWithTypes("u128", item.fields.gas_price), + price: decodeFromFieldsWithTypes("u128", item.fields.price), + }); + } + + static fromBcs(data: Uint8Array): ChainData { + return ChainData.fromFields(ChainData.bcs.parse(data)); + } + + toJSONField() { + return { + gasPrice: this.gasPrice.toString(), + price: this.price.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): ChainData { + return ChainData.reified().new({ + gasPrice: decodeFromJSONField("u128", field.gasPrice), + price: decodeFromJSONField("u128", field.price), + }); + } + + static fromJSON(json: Record): ChainData { + if (json.$typeName !== ChainData.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return ChainData.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): ChainData { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isChainData(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a ChainData object`); + } + return ChainData.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): ChainData { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isChainData(data.bcs.type)) { + throw new Error(`object at is not a ChainData object`); + } + + return ChainData.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return ChainData.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching ChainData object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isChainData(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a ChainData object`); + } + + return ChainData.fromSuiObjectData(res.data); + } +} + +/* ============================== GasOracle =============================== */ + +export function isGasOracle(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::gas_oracle::GasOracle`; +} + +export interface GasOracleFields { + id: ToField; + data: ToField>>; +} + +export type GasOracleReified = Reified; + +export class GasOracle implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::gas_oracle::GasOracle`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = GasOracle.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = GasOracle.$isPhantom; + + readonly id: ToField; + readonly data: ToField>>; + + private constructor(typeArgs: [], fields: GasOracleFields) { + this.$fullTypeName = composeSuiType(GasOracle.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.data = fields.data; + } + + static reified(): GasOracleReified { + return { + typeName: GasOracle.$typeName, + fullTypeName: composeSuiType(GasOracle.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: GasOracle.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => GasOracle.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => GasOracle.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => GasOracle.fromBcs(data), + bcs: GasOracle.bcs, + fromJSONField: (field: any) => GasOracle.fromJSONField(field), + fromJSON: (json: Record) => GasOracle.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => GasOracle.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => GasOracle.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => GasOracle.fetch(client, id), + new: (fields: GasOracleFields) => { + return new GasOracle([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return GasOracle.reified(); + } + + static phantom(): PhantomReified> { + return phantom(GasOracle.reified()); + } + static get p() { + return GasOracle.phantom(); + } + + static get bcs() { + return bcs.struct("GasOracle", { + id: UID.bcs, + data: Table.bcs, + }); + } + + static fromFields(fields: Record): GasOracle { + return GasOracle.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + data: decodeFromFields(Table.reified(reified.phantom("u8"), reified.phantom(ChainData.reified())), fields.data), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): GasOracle { + if (!isGasOracle(item.type)) { + throw new Error("not a GasOracle type"); + } + + return GasOracle.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + data: decodeFromFieldsWithTypes( + Table.reified(reified.phantom("u8"), reified.phantom(ChainData.reified())), + item.fields.data + ), + }); + } + + static fromBcs(data: Uint8Array): GasOracle { + return GasOracle.fromFields(GasOracle.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + data: this.data.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): GasOracle { + return GasOracle.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + data: decodeFromJSONField(Table.reified(reified.phantom("u8"), reified.phantom(ChainData.reified())), field.data), + }); + } + + static fromJSON(json: Record): GasOracle { + if (json.$typeName !== GasOracle.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return GasOracle.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): GasOracle { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isGasOracle(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a GasOracle object`); + } + return GasOracle.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): GasOracle { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isGasOracle(data.bcs.type)) { + throw new Error(`object at is not a GasOracle object`); + } + + return GasOracle.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return GasOracle.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching GasOracle object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isGasOracle(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a GasOracle object`); + } + + return GasOracle.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/gas-oracle/index.ts b/src/services/models/sui/gas-oracle/index.ts new file mode 100644 index 00000000..12959240 --- /dev/null +++ b/src/services/models/sui/gas-oracle/index.ts @@ -0,0 +1,33 @@ +// @ts-nocheck +import { compressSuiType } from "../_framework/util"; + +class PackageAddress { + private static $PACKAGE_ID = ""; + private static $PUBLISHED_AT = ""; + private static $PKG_V = []; + get PACKAGE_ID() { + return compressSuiType(PackageAddress.$PACKAGE_ID); + } + get PUBLISHED_AT() { + return compressSuiType(PackageAddress.$PUBLISHED_AT); + } + get PKG_V1() { + return compressSuiType(PackageAddress.$PKG_V[1]); + } + setPackageId(address: string): void { + PackageAddress.$PACKAGE_ID = address; + } + setPublishedAt(address: string): void { + PackageAddress.$PUBLISHED_AT = address; + } + setPkgV(v: number, address: string): void { + PackageAddress.$PKG_V[v] = address; + } + setAddress(address: string, pkgV1?: string) { + PackageAddress.$PACKAGE_ID = address; + PackageAddress.$PUBLISHED_AT = address; + PackageAddress.$PKG_V[1] = pkgV1 || address; + } +} +const packageAddress = new PackageAddress(); +export = packageAddress; diff --git a/src/services/models/sui/gas-oracle/init.ts b/src/services/models/sui/gas-oracle/init.ts new file mode 100644 index 00000000..962dc7af --- /dev/null +++ b/src/services/models/sui/gas-oracle/init.ts @@ -0,0 +1,9 @@ +// @ts-nocheck +import * as gasOracle from "./gas-oracle/structs"; +import { StructClassLoader } from "../_framework/loader"; + +export function registerClasses(loader: StructClassLoader) { + loader.register(gasOracle.AdminCap); + loader.register(gasOracle.ChainData); + loader.register(gasOracle.GasOracle); +} diff --git a/src/services/models/sui/messenger/events/functions.ts b/src/services/models/sui/messenger/events/functions.ts new file mode 100644 index 00000000..7db8131e --- /dev/null +++ b/src/services/models/sui/messenger/events/functions.ts @@ -0,0 +1,18 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj } from "../../_framework/util"; +import { Transaction, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function messageReceivedEvent(tx: Transaction, message: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::events::message_received_event`, + arguments: [obj(tx, message)], + }); +} + +export function messageSentEvent(tx: Transaction, message: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::events::message_sent_event`, + arguments: [obj(tx, message)], + }); +} diff --git a/src/services/models/sui/messenger/events/structs.ts b/src/services/models/sui/messenger/events/structs.ts new file mode 100644 index 00000000..8c0ebd20 --- /dev/null +++ b/src/services/models/sui/messenger/events/structs.ts @@ -0,0 +1,344 @@ +// @ts-nocheck +import { String } from "../../_dependencies/source/0x1/ascii/structs"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== MessageReceivedEvent =============================== */ + +export function isMessageReceivedEvent(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::events::MessageReceivedEvent`; +} + +export interface MessageReceivedEventFields { + message: ToField; +} + +export type MessageReceivedEventReified = Reified; + +export class MessageReceivedEvent implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::events::MessageReceivedEvent`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = MessageReceivedEvent.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = MessageReceivedEvent.$isPhantom; + + readonly message: ToField; + + private constructor(typeArgs: [], fields: MessageReceivedEventFields) { + this.$fullTypeName = composeSuiType(MessageReceivedEvent.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.message = fields.message; + } + + static reified(): MessageReceivedEventReified { + return { + typeName: MessageReceivedEvent.$typeName, + fullTypeName: composeSuiType(MessageReceivedEvent.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: MessageReceivedEvent.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => MessageReceivedEvent.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => MessageReceivedEvent.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => MessageReceivedEvent.fromBcs(data), + bcs: MessageReceivedEvent.bcs, + fromJSONField: (field: any) => MessageReceivedEvent.fromJSONField(field), + fromJSON: (json: Record) => MessageReceivedEvent.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => MessageReceivedEvent.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => MessageReceivedEvent.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => MessageReceivedEvent.fetch(client, id), + new: (fields: MessageReceivedEventFields) => { + return new MessageReceivedEvent([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return MessageReceivedEvent.reified(); + } + + static phantom(): PhantomReified> { + return phantom(MessageReceivedEvent.reified()); + } + static get p() { + return MessageReceivedEvent.phantom(); + } + + static get bcs() { + return bcs.struct("MessageReceivedEvent", { + message: String.bcs, + }); + } + + static fromFields(fields: Record): MessageReceivedEvent { + return MessageReceivedEvent.reified().new({ + message: decodeFromFields(String.reified(), fields.message), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): MessageReceivedEvent { + if (!isMessageReceivedEvent(item.type)) { + throw new Error("not a MessageReceivedEvent type"); + } + + return MessageReceivedEvent.reified().new({ + message: decodeFromFieldsWithTypes(String.reified(), item.fields.message), + }); + } + + static fromBcs(data: Uint8Array): MessageReceivedEvent { + return MessageReceivedEvent.fromFields(MessageReceivedEvent.bcs.parse(data)); + } + + toJSONField() { + return { + message: this.message, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): MessageReceivedEvent { + return MessageReceivedEvent.reified().new({ + message: decodeFromJSONField(String.reified(), field.message), + }); + } + + static fromJSON(json: Record): MessageReceivedEvent { + if (json.$typeName !== MessageReceivedEvent.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return MessageReceivedEvent.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): MessageReceivedEvent { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isMessageReceivedEvent(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a MessageReceivedEvent object`); + } + return MessageReceivedEvent.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): MessageReceivedEvent { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isMessageReceivedEvent(data.bcs.type)) { + throw new Error(`object at is not a MessageReceivedEvent object`); + } + + return MessageReceivedEvent.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return MessageReceivedEvent.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching MessageReceivedEvent object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isMessageReceivedEvent(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a MessageReceivedEvent object`); + } + + return MessageReceivedEvent.fromSuiObjectData(res.data); + } +} + +/* ============================== MessageSentEvent =============================== */ + +export function isMessageSentEvent(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::events::MessageSentEvent`; +} + +export interface MessageSentEventFields { + message: ToField; +} + +export type MessageSentEventReified = Reified; + +export class MessageSentEvent implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::events::MessageSentEvent`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = MessageSentEvent.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = MessageSentEvent.$isPhantom; + + readonly message: ToField; + + private constructor(typeArgs: [], fields: MessageSentEventFields) { + this.$fullTypeName = composeSuiType(MessageSentEvent.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.message = fields.message; + } + + static reified(): MessageSentEventReified { + return { + typeName: MessageSentEvent.$typeName, + fullTypeName: composeSuiType(MessageSentEvent.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: MessageSentEvent.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => MessageSentEvent.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => MessageSentEvent.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => MessageSentEvent.fromBcs(data), + bcs: MessageSentEvent.bcs, + fromJSONField: (field: any) => MessageSentEvent.fromJSONField(field), + fromJSON: (json: Record) => MessageSentEvent.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => MessageSentEvent.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => MessageSentEvent.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => MessageSentEvent.fetch(client, id), + new: (fields: MessageSentEventFields) => { + return new MessageSentEvent([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return MessageSentEvent.reified(); + } + + static phantom(): PhantomReified> { + return phantom(MessageSentEvent.reified()); + } + static get p() { + return MessageSentEvent.phantom(); + } + + static get bcs() { + return bcs.struct("MessageSentEvent", { + message: String.bcs, + }); + } + + static fromFields(fields: Record): MessageSentEvent { + return MessageSentEvent.reified().new({ + message: decodeFromFields(String.reified(), fields.message), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): MessageSentEvent { + if (!isMessageSentEvent(item.type)) { + throw new Error("not a MessageSentEvent type"); + } + + return MessageSentEvent.reified().new({ + message: decodeFromFieldsWithTypes(String.reified(), item.fields.message), + }); + } + + static fromBcs(data: Uint8Array): MessageSentEvent { + return MessageSentEvent.fromFields(MessageSentEvent.bcs.parse(data)); + } + + toJSONField() { + return { + message: this.message, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): MessageSentEvent { + return MessageSentEvent.reified().new({ + message: decodeFromJSONField(String.reified(), field.message), + }); + } + + static fromJSON(json: Record): MessageSentEvent { + if (json.$typeName !== MessageSentEvent.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return MessageSentEvent.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): MessageSentEvent { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isMessageSentEvent(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a MessageSentEvent object`); + } + return MessageSentEvent.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): MessageSentEvent { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isMessageSentEvent(data.bcs.type)) { + throw new Error(`object at is not a MessageSentEvent object`); + } + + return MessageSentEvent.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return MessageSentEvent.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching MessageSentEvent object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isMessageSentEvent(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a MessageSentEvent object`); + } + + return MessageSentEvent.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/messenger/index.ts b/src/services/models/sui/messenger/index.ts new file mode 100644 index 00000000..12959240 --- /dev/null +++ b/src/services/models/sui/messenger/index.ts @@ -0,0 +1,33 @@ +// @ts-nocheck +import { compressSuiType } from "../_framework/util"; + +class PackageAddress { + private static $PACKAGE_ID = ""; + private static $PUBLISHED_AT = ""; + private static $PKG_V = []; + get PACKAGE_ID() { + return compressSuiType(PackageAddress.$PACKAGE_ID); + } + get PUBLISHED_AT() { + return compressSuiType(PackageAddress.$PUBLISHED_AT); + } + get PKG_V1() { + return compressSuiType(PackageAddress.$PKG_V[1]); + } + setPackageId(address: string): void { + PackageAddress.$PACKAGE_ID = address; + } + setPublishedAt(address: string): void { + PackageAddress.$PUBLISHED_AT = address; + } + setPkgV(v: number, address: string): void { + PackageAddress.$PKG_V[v] = address; + } + setAddress(address: string, pkgV1?: string) { + PackageAddress.$PACKAGE_ID = address; + PackageAddress.$PUBLISHED_AT = address; + PackageAddress.$PKG_V[1] = pkgV1 || address; + } +} +const packageAddress = new PackageAddress(); +export = packageAddress; diff --git a/src/services/models/sui/messenger/init.ts b/src/services/models/sui/messenger/init.ts new file mode 100644 index 00000000..99b356a1 --- /dev/null +++ b/src/services/models/sui/messenger/init.ts @@ -0,0 +1,11 @@ +// @ts-nocheck +import * as events from "./events/structs"; +import * as messenger from "./messenger/structs"; +import { StructClassLoader } from "../_framework/loader"; + +export function registerClasses(loader: StructClassLoader) { + loader.register(events.MessageReceivedEvent); + loader.register(events.MessageSentEvent); + loader.register(messenger.AdminCap); + loader.register(messenger.Messenger); +} diff --git a/src/services/models/sui/messenger/messenger-interface/functions.ts b/src/services/models/sui/messenger/messenger-interface/functions.ts new file mode 100644 index 00000000..8bc63e0d --- /dev/null +++ b/src/services/models/sui/messenger/messenger-interface/functions.ts @@ -0,0 +1,203 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface MigrateArgs { + admin: TransactionObjectInput; + messenger: TransactionObjectInput; +} + +export function migrate(tx: Transaction, args: MigrateArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger_interface::migrate`, + arguments: [obj(tx, args.admin), obj(tx, args.messenger)], + }); +} + +export function gasBalanceValue(tx: Transaction, messenger: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger_interface::gas_balance_value`, + arguments: [obj(tx, messenger)], + }); +} + +export interface GetGasUsageArgs { + messenger: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getGasUsage(tx: Transaction, args: GetGasUsageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger_interface::get_gas_usage`, + arguments: [obj(tx, args.messenger), pure(tx, args.chainId, `u8`)], + }); +} + +export function getOtherChainIds(tx: Transaction, messenger: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger_interface::get_other_chain_ids`, + arguments: [obj(tx, messenger)], + }); +} + +export interface GetTransactionCostArgs { + messenger: TransactionObjectInput; + gasOracle: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getTransactionCost(tx: Transaction, args: GetTransactionCostArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger_interface::get_transaction_cost`, + arguments: [obj(tx, args.messenger), obj(tx, args.gasOracle), pure(tx, args.chainId, `u8`)], + }); +} + +export interface ReceiveMessageArgs { + messenger: TransactionObjectInput; + message: TransactionObjectInput; + signaturePrimary: Array | TransactionArgument; + signatureSecondary: Array | TransactionArgument; +} + +export function receiveMessage(tx: Transaction, args: ReceiveMessageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger_interface::receive_message`, + arguments: [ + obj(tx, args.messenger), + obj(tx, args.message), + pure(tx, args.signaturePrimary, `vector`), + pure(tx, args.signatureSecondary, `vector`), + ], + }); +} + +export interface SendMessageArgs { + messenger: TransactionObjectInput; + gasOracle: TransactionObjectInput; + coin: TransactionObjectInput; + message: TransactionObjectInput; + sender: TransactionObjectInput; +} + +export function sendMessage(tx: Transaction, args: SendMessageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger_interface::send_message`, + arguments: [ + obj(tx, args.messenger), + obj(tx, args.gasOracle), + obj(tx, args.coin), + obj(tx, args.message), + obj(tx, args.sender), + ], + }); +} + +export interface SetGasUsageArgs { + adminCap: TransactionObjectInput; + messenger: TransactionObjectInput; + chainId: number | TransactionArgument; + gasAmount: bigint | TransactionArgument; +} + +export function setGasUsage(tx: Transaction, args: SetGasUsageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger_interface::set_gas_usage`, + arguments: [ + obj(tx, args.adminCap), + obj(tx, args.messenger), + pure(tx, args.chainId, `u8`), + pure(tx, args.gasAmount, `u64`), + ], + }); +} + +export interface SetOtherChainsArgs { + adminCap: TransactionObjectInput; + messenger: TransactionObjectInput; + otherChainIds: Array | TransactionArgument; +} + +export function setOtherChains(tx: Transaction, args: SetOtherChainsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger_interface::set_other_chains`, + arguments: [obj(tx, args.adminCap), obj(tx, args.messenger), pure(tx, args.otherChainIds, `vector`)], + }); +} + +export interface WithdrawFeeArgs { + adminCap: TransactionObjectInput; + messenger: TransactionObjectInput; + amount: bigint | TransactionArgument; +} + +export function withdrawFee(tx: Transaction, args: WithdrawFeeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger_interface::withdraw_fee`, + arguments: [obj(tx, args.adminCap), obj(tx, args.messenger), pure(tx, args.amount, `u64`)], + }); +} + +export interface HasReceivedMessageArgs { + messenger: TransactionObjectInput; + message: TransactionObjectInput; +} + +export function hasReceivedMessage(tx: Transaction, args: HasReceivedMessageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger_interface::has_received_message`, + arguments: [obj(tx, args.messenger), obj(tx, args.message)], + }); +} + +export interface HasSentMessagesArgs { + messenger: TransactionObjectInput; + message: TransactionObjectInput; +} + +export function hasSentMessages(tx: Transaction, args: HasSentMessagesArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger_interface::has_sent_messages`, + arguments: [obj(tx, args.messenger), obj(tx, args.message)], + }); +} + +export interface AddSecondaryValidatorArgs { + adminCap: TransactionObjectInput; + messenger: TransactionObjectInput; + secondaryValidator: Array | TransactionArgument; +} + +export function addSecondaryValidator(tx: Transaction, args: AddSecondaryValidatorArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger_interface::add_secondary_validator`, + arguments: [obj(tx, args.adminCap), obj(tx, args.messenger), pure(tx, args.secondaryValidator, `vector`)], + }); +} + +export interface RemoveSecondaryValidatorArgs { + adminCap: TransactionObjectInput; + messenger: TransactionObjectInput; + secondaryValidator: Array | TransactionArgument; +} + +export function removeSecondaryValidator(tx: Transaction, args: RemoveSecondaryValidatorArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger_interface::remove_secondary_validator`, + arguments: [obj(tx, args.adminCap), obj(tx, args.messenger), pure(tx, args.secondaryValidator, `vector`)], + }); +} + +export interface SetPrimaryValidatorArgs { + adminCap: TransactionObjectInput; + messenger: TransactionObjectInput; + primaryValidator: Array | TransactionArgument; +} + +export function setPrimaryValidator(tx: Transaction, args: SetPrimaryValidatorArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger_interface::set_primary_validator`, + arguments: [obj(tx, args.adminCap), obj(tx, args.messenger), pure(tx, args.primaryValidator, `vector`)], + }); +} diff --git a/src/services/models/sui/messenger/messenger/functions.ts b/src/services/models/sui/messenger/messenger/functions.ts new file mode 100644 index 00000000..8e8b602b --- /dev/null +++ b/src/services/models/sui/messenger/messenger/functions.ts @@ -0,0 +1,198 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function getId(tx: Transaction, messenger: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger::get_id`, + arguments: [obj(tx, messenger)], + }); +} + +export function getVersion(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger::get_version`, + arguments: [], + }); +} + +export function init(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger::init`, + arguments: [], + }); +} + +export interface MigrateArgs { + admin: TransactionObjectInput; + messenger: TransactionObjectInput; +} + +export function migrate(tx: Transaction, args: MigrateArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger::migrate`, + arguments: [obj(tx, args.admin), obj(tx, args.messenger)], + }); +} + +export function gasBalanceValue(tx: Transaction, messenger: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger::gas_balance_value`, + arguments: [obj(tx, messenger)], + }); +} + +export function getGasUsage(tx: Transaction, messenger: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger::get_gas_usage`, + arguments: [obj(tx, messenger)], + }); +} + +export function getOtherChainIds(tx: Transaction, messenger: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger::get_other_chain_ids`, + arguments: [obj(tx, messenger)], + }); +} + +export function getReceivedMessages(tx: Transaction, messenger: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger::get_received_messages`, + arguments: [obj(tx, messenger)], + }); +} + +export function getSentMessages(tx: Transaction, messenger: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger::get_sent_messages`, + arguments: [obj(tx, messenger)], + }); +} + +export interface GetTransactionCostArgs { + messenger: TransactionObjectInput; + gasOracle: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getTransactionCost(tx: Transaction, args: GetTransactionCostArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger::get_transaction_cost`, + arguments: [obj(tx, args.messenger), obj(tx, args.gasOracle), pure(tx, args.chainId, `u8`)], + }); +} + +export interface ReceiveMessageArgs { + messenger: TransactionObjectInput; + message: TransactionObjectInput; + signaturePrimary: Array | TransactionArgument; + signatureSecondary: Array | TransactionArgument; +} + +export function receiveMessage(tx: Transaction, args: ReceiveMessageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger::receive_message`, + arguments: [ + obj(tx, args.messenger), + obj(tx, args.message), + pure(tx, args.signaturePrimary, `vector`), + pure(tx, args.signatureSecondary, `vector`), + ], + }); +} + +export interface SendMessageArgs { + messenger: TransactionObjectInput; + gasOracle: TransactionObjectInput; + coin: TransactionObjectInput; + message: TransactionObjectInput; + sender: TransactionObjectInput; +} + +export function sendMessage(tx: Transaction, args: SendMessageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger::send_message`, + arguments: [ + obj(tx, args.messenger), + obj(tx, args.gasOracle), + obj(tx, args.coin), + obj(tx, args.message), + obj(tx, args.sender), + ], + }); +} + +export interface SetGasUsageArgs { + messenger: TransactionObjectInput; + chainId: number | TransactionArgument; + gasAmount: bigint | TransactionArgument; +} + +export function setGasUsage(tx: Transaction, args: SetGasUsageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger::set_gas_usage`, + arguments: [obj(tx, args.messenger), pure(tx, args.chainId, `u8`), pure(tx, args.gasAmount, `u64`)], + }); +} + +export interface SetOtherChainsArgs { + messenger: TransactionObjectInput; + otherChainIds: Array | TransactionArgument; +} + +export function setOtherChains(tx: Transaction, args: SetOtherChainsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger::set_other_chains`, + arguments: [obj(tx, args.messenger), pure(tx, args.otherChainIds, `vector`)], + }); +} + +export interface WithdrawFeeArgs { + messenger: TransactionObjectInput; + amount: bigint | TransactionArgument; +} + +export function withdrawFee(tx: Transaction, args: WithdrawFeeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger::withdraw_fee`, + arguments: [obj(tx, args.messenger), pure(tx, args.amount, `u64`)], + }); +} + +export interface AddSecondaryValidatorArgs { + messenger: TransactionObjectInput; + secondaryValidator: Array | TransactionArgument; +} + +export function addSecondaryValidator(tx: Transaction, args: AddSecondaryValidatorArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger::add_secondary_validator`, + arguments: [obj(tx, args.messenger), pure(tx, args.secondaryValidator, `vector`)], + }); +} + +export interface RemoveSecondaryValidatorArgs { + messenger: TransactionObjectInput; + secondaryValidator: Array | TransactionArgument; +} + +export function removeSecondaryValidator(tx: Transaction, args: RemoveSecondaryValidatorArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger::remove_secondary_validator`, + arguments: [obj(tx, args.messenger), pure(tx, args.secondaryValidator, `vector`)], + }); +} + +export interface SetPrimaryValidatorArgs { + messenger: TransactionObjectInput; + primaryValidator: Array | TransactionArgument; +} + +export function setPrimaryValidator(tx: Transaction, args: SetPrimaryValidatorArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger::set_primary_validator`, + arguments: [obj(tx, args.messenger), pure(tx, args.primaryValidator, `vector`)], + }); +} diff --git a/src/services/models/sui/messenger/messenger/structs.ts b/src/services/models/sui/messenger/messenger/structs.ts new file mode 100644 index 00000000..d2d7525a --- /dev/null +++ b/src/services/models/sui/messenger/messenger/structs.ts @@ -0,0 +1,427 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, + ToTypeStr as ToPhantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { Vector } from "../../_framework/vector"; +import { Balance } from "../../sui/balance/structs"; +import { UID } from "../../sui/object/structs"; +import { SUI } from "../../sui/sui/structs"; +import { Table } from "../../sui/table/structs"; +import { Message } from "../../utils/message/structs"; +import { Set } from "../../utils/set/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== AdminCap =============================== */ + +export function isAdminCap(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::messenger::AdminCap`; +} + +export interface AdminCapFields { + id: ToField; +} + +export type AdminCapReified = Reified; + +export class AdminCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::messenger::AdminCap`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = AdminCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = AdminCap.$isPhantom; + + readonly id: ToField; + + private constructor(typeArgs: [], fields: AdminCapFields) { + this.$fullTypeName = composeSuiType(AdminCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified(): AdminCapReified { + return { + typeName: AdminCap.$typeName, + fullTypeName: composeSuiType(AdminCap.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: AdminCap.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => AdminCap.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => AdminCap.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => AdminCap.fromBcs(data), + bcs: AdminCap.bcs, + fromJSONField: (field: any) => AdminCap.fromJSONField(field), + fromJSON: (json: Record) => AdminCap.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => AdminCap.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => AdminCap.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => AdminCap.fetch(client, id), + new: (fields: AdminCapFields) => { + return new AdminCap([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return AdminCap.reified(); + } + + static phantom(): PhantomReified> { + return phantom(AdminCap.reified()); + } + static get p() { + return AdminCap.phantom(); + } + + static get bcs() { + return bcs.struct("AdminCap", { + id: UID.bcs, + }); + } + + static fromFields(fields: Record): AdminCap { + return AdminCap.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): AdminCap { + if (!isAdminCap(item.type)) { + throw new Error("not a AdminCap type"); + } + + return AdminCap.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + }); + } + + static fromBcs(data: Uint8Array): AdminCap { + return AdminCap.fromFields(AdminCap.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): AdminCap { + return AdminCap.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + }); + } + + static fromJSON(json: Record): AdminCap { + if (json.$typeName !== AdminCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return AdminCap.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): AdminCap { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isAdminCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a AdminCap object`); + } + return AdminCap.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): AdminCap { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isAdminCap(data.bcs.type)) { + throw new Error(`object at is not a AdminCap object`); + } + + return AdminCap.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return AdminCap.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching AdminCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isAdminCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a AdminCap object`); + } + + return AdminCap.fromSuiObjectData(res.data); + } +} + +/* ============================== Messenger =============================== */ + +export function isMessenger(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::messenger::Messenger`; +} + +export interface MessengerFields { + id: ToField; + primaryValidator: ToField>; + secondaryValidators: ToField>>>; + receivedMessages: ToField>>; + sentMessages: ToField>>; + otherChainIds: ToField>; + gasUsage: ToField>; + gasBalance: ToField>>; +} + +export type MessengerReified = Reified; + +export class Messenger implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::messenger::Messenger`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Messenger.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Messenger.$isPhantom; + + readonly id: ToField; + readonly primaryValidator: ToField>; + readonly secondaryValidators: ToField>>>; + readonly receivedMessages: ToField>>; + readonly sentMessages: ToField>>; + readonly otherChainIds: ToField>; + readonly gasUsage: ToField>; + readonly gasBalance: ToField>>; + + private constructor(typeArgs: [], fields: MessengerFields) { + this.$fullTypeName = composeSuiType(Messenger.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.primaryValidator = fields.primaryValidator; + this.secondaryValidators = fields.secondaryValidators; + this.receivedMessages = fields.receivedMessages; + this.sentMessages = fields.sentMessages; + this.otherChainIds = fields.otherChainIds; + this.gasUsage = fields.gasUsage; + this.gasBalance = fields.gasBalance; + } + + static reified(): MessengerReified { + return { + typeName: Messenger.$typeName, + fullTypeName: composeSuiType(Messenger.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Messenger.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Messenger.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Messenger.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Messenger.fromBcs(data), + bcs: Messenger.bcs, + fromJSONField: (field: any) => Messenger.fromJSONField(field), + fromJSON: (json: Record) => Messenger.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Messenger.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Messenger.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Messenger.fetch(client, id), + new: (fields: MessengerFields) => { + return new Messenger([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Messenger.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Messenger.reified()); + } + static get p() { + return Messenger.phantom(); + } + + static get bcs() { + return bcs.struct("Messenger", { + id: UID.bcs, + primary_validator: bcs.vector(bcs.u8()), + secondary_validators: Set.bcs, + received_messages: Set.bcs, + sent_messages: Set.bcs, + other_chain_ids: bcs.vector(bcs.bool()), + gas_usage: Table.bcs, + gas_balance: Balance.bcs, + }); + } + + static fromFields(fields: Record): Messenger { + return Messenger.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + primaryValidator: decodeFromFields(reified.vector("u8"), fields.primary_validator), + secondaryValidators: decodeFromFields( + Set.reified(reified.phantom(reified.vector("u8"))), + fields.secondary_validators + ), + receivedMessages: decodeFromFields(Set.reified(reified.phantom(Message.reified())), fields.received_messages), + sentMessages: decodeFromFields(Set.reified(reified.phantom(Message.reified())), fields.sent_messages), + otherChainIds: decodeFromFields(reified.vector("bool"), fields.other_chain_ids), + gasUsage: decodeFromFields(Table.reified(reified.phantom("u8"), reified.phantom("u64")), fields.gas_usage), + gasBalance: decodeFromFields(Balance.reified(reified.phantom(SUI.reified())), fields.gas_balance), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Messenger { + if (!isMessenger(item.type)) { + throw new Error("not a Messenger type"); + } + + return Messenger.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + primaryValidator: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.primary_validator), + secondaryValidators: decodeFromFieldsWithTypes( + Set.reified(reified.phantom(reified.vector("u8"))), + item.fields.secondary_validators + ), + receivedMessages: decodeFromFieldsWithTypes( + Set.reified(reified.phantom(Message.reified())), + item.fields.received_messages + ), + sentMessages: decodeFromFieldsWithTypes( + Set.reified(reified.phantom(Message.reified())), + item.fields.sent_messages + ), + otherChainIds: decodeFromFieldsWithTypes(reified.vector("bool"), item.fields.other_chain_ids), + gasUsage: decodeFromFieldsWithTypes( + Table.reified(reified.phantom("u8"), reified.phantom("u64")), + item.fields.gas_usage + ), + gasBalance: decodeFromFieldsWithTypes(Balance.reified(reified.phantom(SUI.reified())), item.fields.gas_balance), + }); + } + + static fromBcs(data: Uint8Array): Messenger { + return Messenger.fromFields(Messenger.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + primaryValidator: fieldToJSON>(`vector`, this.primaryValidator), + secondaryValidators: this.secondaryValidators.toJSONField(), + receivedMessages: this.receivedMessages.toJSONField(), + sentMessages: this.sentMessages.toJSONField(), + otherChainIds: fieldToJSON>(`vector`, this.otherChainIds), + gasUsage: this.gasUsage.toJSONField(), + gasBalance: this.gasBalance.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Messenger { + return Messenger.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + primaryValidator: decodeFromJSONField(reified.vector("u8"), field.primaryValidator), + secondaryValidators: decodeFromJSONField( + Set.reified(reified.phantom(reified.vector("u8"))), + field.secondaryValidators + ), + receivedMessages: decodeFromJSONField(Set.reified(reified.phantom(Message.reified())), field.receivedMessages), + sentMessages: decodeFromJSONField(Set.reified(reified.phantom(Message.reified())), field.sentMessages), + otherChainIds: decodeFromJSONField(reified.vector("bool"), field.otherChainIds), + gasUsage: decodeFromJSONField(Table.reified(reified.phantom("u8"), reified.phantom("u64")), field.gasUsage), + gasBalance: decodeFromJSONField(Balance.reified(reified.phantom(SUI.reified())), field.gasBalance), + }); + } + + static fromJSON(json: Record): Messenger { + if (json.$typeName !== Messenger.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Messenger.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Messenger { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isMessenger(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Messenger object`); + } + return Messenger.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Messenger { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isMessenger(data.bcs.type)) { + throw new Error(`object at is not a Messenger object`); + } + + return Messenger.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Messenger.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Messenger object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isMessenger(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Messenger object`); + } + + return Messenger.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/sui/address/functions.ts b/src/services/models/sui/sui/address/functions.ts new file mode 100644 index 00000000..be0dba99 --- /dev/null +++ b/src/services/models/sui/sui/address/functions.ts @@ -0,0 +1,74 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { pure } from "../../_framework/util"; +import { Transaction, TransactionArgument } from "@mysten/sui/transactions"; + +export function length(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::address::length`, + arguments: [], + }); +} + +export function toBytes(tx: Transaction, a: string | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::address::to_bytes`, + arguments: [pure(tx, a, `address`)], + }); +} + +export function fromAsciiBytes(tx: Transaction, bytes: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::address::from_ascii_bytes`, + arguments: [pure(tx, bytes, `vector`)], + }); +} + +export function fromBytes(tx: Transaction, bytes: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::address::from_bytes`, + arguments: [pure(tx, bytes, `vector`)], + }); +} + +export function fromU256(tx: Transaction, n: bigint | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::address::from_u256`, + arguments: [pure(tx, n, `u256`)], + }); +} + +export function hexCharValue(tx: Transaction, c: number | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::address::hex_char_value`, + arguments: [pure(tx, c, `u8`)], + }); +} + +export function max(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::address::max`, + arguments: [], + }); +} + +export function toAsciiString(tx: Transaction, a: string | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::address::to_ascii_string`, + arguments: [pure(tx, a, `address`)], + }); +} + +export function toString(tx: Transaction, a: string | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::address::to_string`, + arguments: [pure(tx, a, `address`)], + }); +} + +export function toU256(tx: Transaction, a: string | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::address::to_u256`, + arguments: [pure(tx, a, `address`)], + }); +} diff --git a/src/services/models/sui/sui/authenticator-state/functions.ts b/src/services/models/sui/sui/authenticator-state/functions.ts new file mode 100644 index 00000000..c9494bf9 --- /dev/null +++ b/src/services/models/sui/sui/authenticator-state/functions.ts @@ -0,0 +1,132 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { String } from "../../_dependencies/source/0x1/string/structs"; +import { obj, pure, vector } from "../../_framework/util"; +import { ActiveJwk } from "./structs"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function create(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::authenticator_state::create`, + arguments: [], + }); +} + +export interface ActiveJwkEqualArgs { + a: TransactionObjectInput; + b: TransactionObjectInput; +} + +export function activeJwkEqual(tx: Transaction, args: ActiveJwkEqualArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::authenticator_state::active_jwk_equal`, + arguments: [obj(tx, args.a), obj(tx, args.b)], + }); +} + +export function checkSorted(tx: Transaction, newActiveJwks: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::authenticator_state::check_sorted`, + arguments: [vector(tx, `${ActiveJwk.$typeName}`, newActiveJwks)], + }); +} + +export function deduplicate(tx: Transaction, jwks: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::authenticator_state::deduplicate`, + arguments: [vector(tx, `${ActiveJwk.$typeName}`, jwks)], + }); +} + +export interface ExpireJwksArgs { + self: TransactionObjectInput; + minEpoch: bigint | TransactionArgument; +} + +export function expireJwks(tx: Transaction, args: ExpireJwksArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::authenticator_state::expire_jwks`, + arguments: [obj(tx, args.self), pure(tx, args.minEpoch, `u64`)], + }); +} + +export function getActiveJwks(tx: Transaction, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::authenticator_state::get_active_jwks`, + arguments: [obj(tx, self)], + }); +} + +export interface JwkEqualArgs { + a: TransactionObjectInput; + b: TransactionObjectInput; +} + +export function jwkEqual(tx: Transaction, args: JwkEqualArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::authenticator_state::jwk_equal`, + arguments: [obj(tx, args.a), obj(tx, args.b)], + }); +} + +export interface JwkIdEqualArgs { + a: TransactionObjectInput; + b: TransactionObjectInput; +} + +export function jwkIdEqual(tx: Transaction, args: JwkIdEqualArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::authenticator_state::jwk_id_equal`, + arguments: [obj(tx, args.a), obj(tx, args.b)], + }); +} + +export interface JwkLtArgs { + a: TransactionObjectInput; + b: TransactionObjectInput; +} + +export function jwkLt(tx: Transaction, args: JwkLtArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::authenticator_state::jwk_lt`, + arguments: [obj(tx, args.a), obj(tx, args.b)], + }); +} + +export function loadInner(tx: Transaction, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::authenticator_state::load_inner`, + arguments: [obj(tx, self)], + }); +} + +export function loadInnerMut(tx: Transaction, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::authenticator_state::load_inner_mut`, + arguments: [obj(tx, self)], + }); +} + +export interface StringBytesLtArgs { + a: string | TransactionArgument; + b: string | TransactionArgument; +} + +export function stringBytesLt(tx: Transaction, args: StringBytesLtArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::authenticator_state::string_bytes_lt`, + arguments: [pure(tx, args.a, `${String.$typeName}`), pure(tx, args.b, `${String.$typeName}`)], + }); +} + +export interface UpdateAuthenticatorStateArgs { + self: TransactionObjectInput; + newActiveJwks: Array | TransactionArgument; +} + +export function updateAuthenticatorState(tx: Transaction, args: UpdateAuthenticatorStateArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::authenticator_state::update_authenticator_state`, + arguments: [obj(tx, args.self), vector(tx, `${ActiveJwk.$typeName}`, args.newActiveJwks)], + }); +} diff --git a/src/services/models/sui/sui/authenticator-state/structs.ts b/src/services/models/sui/sui/authenticator-state/structs.ts new file mode 100644 index 00000000..cdb6e4b4 --- /dev/null +++ b/src/services/models/sui/sui/authenticator-state/structs.ts @@ -0,0 +1,901 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { String } from "../../_dependencies/source/0x1/string/structs"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { Vector } from "../../_framework/vector"; +import { PKG_V26 } from "../index"; +import { UID } from "../object/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== ActiveJwk =============================== */ + +export function isActiveJwk(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::authenticator_state::ActiveJwk`; +} + +export interface ActiveJwkFields { + jwkId: ToField; + jwk: ToField; + epoch: ToField<"u64">; +} + +export type ActiveJwkReified = Reified; + +export class ActiveJwk implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::authenticator_state::ActiveJwk`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = ActiveJwk.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = ActiveJwk.$isPhantom; + + readonly jwkId: ToField; + readonly jwk: ToField; + readonly epoch: ToField<"u64">; + + private constructor(typeArgs: [], fields: ActiveJwkFields) { + this.$fullTypeName = composeSuiType(ActiveJwk.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.jwkId = fields.jwkId; + this.jwk = fields.jwk; + this.epoch = fields.epoch; + } + + static reified(): ActiveJwkReified { + return { + typeName: ActiveJwk.$typeName, + fullTypeName: composeSuiType(ActiveJwk.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: ActiveJwk.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => ActiveJwk.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => ActiveJwk.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => ActiveJwk.fromBcs(data), + bcs: ActiveJwk.bcs, + fromJSONField: (field: any) => ActiveJwk.fromJSONField(field), + fromJSON: (json: Record) => ActiveJwk.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => ActiveJwk.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => ActiveJwk.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => ActiveJwk.fetch(client, id), + new: (fields: ActiveJwkFields) => { + return new ActiveJwk([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return ActiveJwk.reified(); + } + + static phantom(): PhantomReified> { + return phantom(ActiveJwk.reified()); + } + static get p() { + return ActiveJwk.phantom(); + } + + static get bcs() { + return bcs.struct("ActiveJwk", { + jwk_id: JwkId.bcs, + jwk: JWK.bcs, + epoch: bcs.u64(), + }); + } + + static fromFields(fields: Record): ActiveJwk { + return ActiveJwk.reified().new({ + jwkId: decodeFromFields(JwkId.reified(), fields.jwk_id), + jwk: decodeFromFields(JWK.reified(), fields.jwk), + epoch: decodeFromFields("u64", fields.epoch), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): ActiveJwk { + if (!isActiveJwk(item.type)) { + throw new Error("not a ActiveJwk type"); + } + + return ActiveJwk.reified().new({ + jwkId: decodeFromFieldsWithTypes(JwkId.reified(), item.fields.jwk_id), + jwk: decodeFromFieldsWithTypes(JWK.reified(), item.fields.jwk), + epoch: decodeFromFieldsWithTypes("u64", item.fields.epoch), + }); + } + + static fromBcs(data: Uint8Array): ActiveJwk { + return ActiveJwk.fromFields(ActiveJwk.bcs.parse(data)); + } + + toJSONField() { + return { + jwkId: this.jwkId.toJSONField(), + jwk: this.jwk.toJSONField(), + epoch: this.epoch.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): ActiveJwk { + return ActiveJwk.reified().new({ + jwkId: decodeFromJSONField(JwkId.reified(), field.jwkId), + jwk: decodeFromJSONField(JWK.reified(), field.jwk), + epoch: decodeFromJSONField("u64", field.epoch), + }); + } + + static fromJSON(json: Record): ActiveJwk { + if (json.$typeName !== ActiveJwk.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return ActiveJwk.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): ActiveJwk { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isActiveJwk(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a ActiveJwk object`); + } + return ActiveJwk.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): ActiveJwk { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isActiveJwk(data.bcs.type)) { + throw new Error(`object at is not a ActiveJwk object`); + } + + return ActiveJwk.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return ActiveJwk.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching ActiveJwk object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isActiveJwk(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a ActiveJwk object`); + } + + return ActiveJwk.fromSuiObjectData(res.data); + } +} + +/* ============================== AuthenticatorState =============================== */ + +export function isAuthenticatorState(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::authenticator_state::AuthenticatorState`; +} + +export interface AuthenticatorStateFields { + id: ToField; + version: ToField<"u64">; +} + +export type AuthenticatorStateReified = Reified; + +export class AuthenticatorState implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::authenticator_state::AuthenticatorState`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = AuthenticatorState.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = AuthenticatorState.$isPhantom; + + readonly id: ToField; + readonly version: ToField<"u64">; + + private constructor(typeArgs: [], fields: AuthenticatorStateFields) { + this.$fullTypeName = composeSuiType(AuthenticatorState.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.version = fields.version; + } + + static reified(): AuthenticatorStateReified { + return { + typeName: AuthenticatorState.$typeName, + fullTypeName: composeSuiType(AuthenticatorState.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: AuthenticatorState.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => AuthenticatorState.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => AuthenticatorState.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => AuthenticatorState.fromBcs(data), + bcs: AuthenticatorState.bcs, + fromJSONField: (field: any) => AuthenticatorState.fromJSONField(field), + fromJSON: (json: Record) => AuthenticatorState.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => AuthenticatorState.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => AuthenticatorState.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => AuthenticatorState.fetch(client, id), + new: (fields: AuthenticatorStateFields) => { + return new AuthenticatorState([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return AuthenticatorState.reified(); + } + + static phantom(): PhantomReified> { + return phantom(AuthenticatorState.reified()); + } + static get p() { + return AuthenticatorState.phantom(); + } + + static get bcs() { + return bcs.struct("AuthenticatorState", { + id: UID.bcs, + version: bcs.u64(), + }); + } + + static fromFields(fields: Record): AuthenticatorState { + return AuthenticatorState.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + version: decodeFromFields("u64", fields.version), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): AuthenticatorState { + if (!isAuthenticatorState(item.type)) { + throw new Error("not a AuthenticatorState type"); + } + + return AuthenticatorState.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + version: decodeFromFieldsWithTypes("u64", item.fields.version), + }); + } + + static fromBcs(data: Uint8Array): AuthenticatorState { + return AuthenticatorState.fromFields(AuthenticatorState.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + version: this.version.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): AuthenticatorState { + return AuthenticatorState.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + version: decodeFromJSONField("u64", field.version), + }); + } + + static fromJSON(json: Record): AuthenticatorState { + if (json.$typeName !== AuthenticatorState.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return AuthenticatorState.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): AuthenticatorState { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isAuthenticatorState(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a AuthenticatorState object`); + } + return AuthenticatorState.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): AuthenticatorState { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isAuthenticatorState(data.bcs.type)) { + throw new Error(`object at is not a AuthenticatorState object`); + } + + return AuthenticatorState.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return AuthenticatorState.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching AuthenticatorState object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isAuthenticatorState(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a AuthenticatorState object`); + } + + return AuthenticatorState.fromSuiObjectData(res.data); + } +} + +/* ============================== AuthenticatorStateInner =============================== */ + +export function isAuthenticatorStateInner(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::authenticator_state::AuthenticatorStateInner`; +} + +export interface AuthenticatorStateInnerFields { + version: ToField<"u64">; + activeJwks: ToField>; +} + +export type AuthenticatorStateInnerReified = Reified; + +export class AuthenticatorStateInner implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::authenticator_state::AuthenticatorStateInner`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = AuthenticatorStateInner.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = AuthenticatorStateInner.$isPhantom; + + readonly version: ToField<"u64">; + readonly activeJwks: ToField>; + + private constructor(typeArgs: [], fields: AuthenticatorStateInnerFields) { + this.$fullTypeName = composeSuiType(AuthenticatorStateInner.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.version = fields.version; + this.activeJwks = fields.activeJwks; + } + + static reified(): AuthenticatorStateInnerReified { + return { + typeName: AuthenticatorStateInner.$typeName, + fullTypeName: composeSuiType(AuthenticatorStateInner.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: AuthenticatorStateInner.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => AuthenticatorStateInner.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => AuthenticatorStateInner.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => AuthenticatorStateInner.fromBcs(data), + bcs: AuthenticatorStateInner.bcs, + fromJSONField: (field: any) => AuthenticatorStateInner.fromJSONField(field), + fromJSON: (json: Record) => AuthenticatorStateInner.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => AuthenticatorStateInner.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => AuthenticatorStateInner.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => AuthenticatorStateInner.fetch(client, id), + new: (fields: AuthenticatorStateInnerFields) => { + return new AuthenticatorStateInner([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return AuthenticatorStateInner.reified(); + } + + static phantom(): PhantomReified> { + return phantom(AuthenticatorStateInner.reified()); + } + static get p() { + return AuthenticatorStateInner.phantom(); + } + + static get bcs() { + return bcs.struct("AuthenticatorStateInner", { + version: bcs.u64(), + active_jwks: bcs.vector(ActiveJwk.bcs), + }); + } + + static fromFields(fields: Record): AuthenticatorStateInner { + return AuthenticatorStateInner.reified().new({ + version: decodeFromFields("u64", fields.version), + activeJwks: decodeFromFields(reified.vector(ActiveJwk.reified()), fields.active_jwks), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): AuthenticatorStateInner { + if (!isAuthenticatorStateInner(item.type)) { + throw new Error("not a AuthenticatorStateInner type"); + } + + return AuthenticatorStateInner.reified().new({ + version: decodeFromFieldsWithTypes("u64", item.fields.version), + activeJwks: decodeFromFieldsWithTypes(reified.vector(ActiveJwk.reified()), item.fields.active_jwks), + }); + } + + static fromBcs(data: Uint8Array): AuthenticatorStateInner { + return AuthenticatorStateInner.fromFields(AuthenticatorStateInner.bcs.parse(data)); + } + + toJSONField() { + return { + version: this.version.toString(), + activeJwks: fieldToJSON>(`vector<${ActiveJwk.$typeName}>`, this.activeJwks), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): AuthenticatorStateInner { + return AuthenticatorStateInner.reified().new({ + version: decodeFromJSONField("u64", field.version), + activeJwks: decodeFromJSONField(reified.vector(ActiveJwk.reified()), field.activeJwks), + }); + } + + static fromJSON(json: Record): AuthenticatorStateInner { + if (json.$typeName !== AuthenticatorStateInner.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return AuthenticatorStateInner.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): AuthenticatorStateInner { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isAuthenticatorStateInner(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a AuthenticatorStateInner object`); + } + return AuthenticatorStateInner.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): AuthenticatorStateInner { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isAuthenticatorStateInner(data.bcs.type)) { + throw new Error(`object at is not a AuthenticatorStateInner object`); + } + + return AuthenticatorStateInner.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return AuthenticatorStateInner.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching AuthenticatorStateInner object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isAuthenticatorStateInner(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a AuthenticatorStateInner object`); + } + + return AuthenticatorStateInner.fromSuiObjectData(res.data); + } +} + +/* ============================== JWK =============================== */ + +export function isJWK(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::authenticator_state::JWK`; +} + +export interface JWKFields { + kty: ToField; + e: ToField; + n: ToField; + alg: ToField; +} + +export type JWKReified = Reified; + +export class JWK implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::authenticator_state::JWK`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = JWK.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = JWK.$isPhantom; + + readonly kty: ToField; + readonly e: ToField; + readonly n: ToField; + readonly alg: ToField; + + private constructor(typeArgs: [], fields: JWKFields) { + this.$fullTypeName = composeSuiType(JWK.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.kty = fields.kty; + this.e = fields.e; + this.n = fields.n; + this.alg = fields.alg; + } + + static reified(): JWKReified { + return { + typeName: JWK.$typeName, + fullTypeName: composeSuiType(JWK.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: JWK.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => JWK.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => JWK.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => JWK.fromBcs(data), + bcs: JWK.bcs, + fromJSONField: (field: any) => JWK.fromJSONField(field), + fromJSON: (json: Record) => JWK.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => JWK.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => JWK.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => JWK.fetch(client, id), + new: (fields: JWKFields) => { + return new JWK([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return JWK.reified(); + } + + static phantom(): PhantomReified> { + return phantom(JWK.reified()); + } + static get p() { + return JWK.phantom(); + } + + static get bcs() { + return bcs.struct("JWK", { + kty: String.bcs, + e: String.bcs, + n: String.bcs, + alg: String.bcs, + }); + } + + static fromFields(fields: Record): JWK { + return JWK.reified().new({ + kty: decodeFromFields(String.reified(), fields.kty), + e: decodeFromFields(String.reified(), fields.e), + n: decodeFromFields(String.reified(), fields.n), + alg: decodeFromFields(String.reified(), fields.alg), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): JWK { + if (!isJWK(item.type)) { + throw new Error("not a JWK type"); + } + + return JWK.reified().new({ + kty: decodeFromFieldsWithTypes(String.reified(), item.fields.kty), + e: decodeFromFieldsWithTypes(String.reified(), item.fields.e), + n: decodeFromFieldsWithTypes(String.reified(), item.fields.n), + alg: decodeFromFieldsWithTypes(String.reified(), item.fields.alg), + }); + } + + static fromBcs(data: Uint8Array): JWK { + return JWK.fromFields(JWK.bcs.parse(data)); + } + + toJSONField() { + return { + kty: this.kty, + e: this.e, + n: this.n, + alg: this.alg, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): JWK { + return JWK.reified().new({ + kty: decodeFromJSONField(String.reified(), field.kty), + e: decodeFromJSONField(String.reified(), field.e), + n: decodeFromJSONField(String.reified(), field.n), + alg: decodeFromJSONField(String.reified(), field.alg), + }); + } + + static fromJSON(json: Record): JWK { + if (json.$typeName !== JWK.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return JWK.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): JWK { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isJWK(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a JWK object`); + } + return JWK.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): JWK { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isJWK(data.bcs.type)) { + throw new Error(`object at is not a JWK object`); + } + + return JWK.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return JWK.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching JWK object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isJWK(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a JWK object`); + } + + return JWK.fromSuiObjectData(res.data); + } +} + +/* ============================== JwkId =============================== */ + +export function isJwkId(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::authenticator_state::JwkId`; +} + +export interface JwkIdFields { + iss: ToField; + kid: ToField; +} + +export type JwkIdReified = Reified; + +export class JwkId implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::authenticator_state::JwkId`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = JwkId.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = JwkId.$isPhantom; + + readonly iss: ToField; + readonly kid: ToField; + + private constructor(typeArgs: [], fields: JwkIdFields) { + this.$fullTypeName = composeSuiType(JwkId.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.iss = fields.iss; + this.kid = fields.kid; + } + + static reified(): JwkIdReified { + return { + typeName: JwkId.$typeName, + fullTypeName: composeSuiType(JwkId.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: JwkId.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => JwkId.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => JwkId.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => JwkId.fromBcs(data), + bcs: JwkId.bcs, + fromJSONField: (field: any) => JwkId.fromJSONField(field), + fromJSON: (json: Record) => JwkId.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => JwkId.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => JwkId.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => JwkId.fetch(client, id), + new: (fields: JwkIdFields) => { + return new JwkId([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return JwkId.reified(); + } + + static phantom(): PhantomReified> { + return phantom(JwkId.reified()); + } + static get p() { + return JwkId.phantom(); + } + + static get bcs() { + return bcs.struct("JwkId", { + iss: String.bcs, + kid: String.bcs, + }); + } + + static fromFields(fields: Record): JwkId { + return JwkId.reified().new({ + iss: decodeFromFields(String.reified(), fields.iss), + kid: decodeFromFields(String.reified(), fields.kid), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): JwkId { + if (!isJwkId(item.type)) { + throw new Error("not a JwkId type"); + } + + return JwkId.reified().new({ + iss: decodeFromFieldsWithTypes(String.reified(), item.fields.iss), + kid: decodeFromFieldsWithTypes(String.reified(), item.fields.kid), + }); + } + + static fromBcs(data: Uint8Array): JwkId { + return JwkId.fromFields(JwkId.bcs.parse(data)); + } + + toJSONField() { + return { + iss: this.iss, + kid: this.kid, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): JwkId { + return JwkId.reified().new({ + iss: decodeFromJSONField(String.reified(), field.iss), + kid: decodeFromJSONField(String.reified(), field.kid), + }); + } + + static fromJSON(json: Record): JwkId { + if (json.$typeName !== JwkId.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return JwkId.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): JwkId { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isJwkId(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a JwkId object`); + } + return JwkId.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): JwkId { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isJwkId(data.bcs.type)) { + throw new Error(`object at is not a JwkId object`); + } + + return JwkId.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return JwkId.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching JwkId object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isJwkId(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a JwkId object`); + } + + return JwkId.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/sui/bag/functions.ts b/src/services/models/sui/sui/bag/functions.ts new file mode 100644 index 00000000..4c938a95 --- /dev/null +++ b/src/services/models/sui/sui/bag/functions.ts @@ -0,0 +1,108 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj } from "../../_framework/util"; +import { Transaction, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface AddArgs { + bag: TransactionObjectInput; + k: GenericArg; + v: GenericArg; +} + +export function add(tx: Transaction, typeArgs: [string, string], args: AddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bag::add`, + typeArguments: typeArgs, + arguments: [obj(tx, args.bag), generic(tx, `${typeArgs[0]}`, args.k), generic(tx, `${typeArgs[1]}`, args.v)], + }); +} + +export interface BorrowArgs { + bag: TransactionObjectInput; + k: GenericArg; +} + +export function borrow(tx: Transaction, typeArgs: [string, string], args: BorrowArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bag::borrow`, + typeArguments: typeArgs, + arguments: [obj(tx, args.bag), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export interface BorrowMutArgs { + bag: TransactionObjectInput; + k: GenericArg; +} + +export function borrowMut(tx: Transaction, typeArgs: [string, string], args: BorrowMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bag::borrow_mut`, + typeArguments: typeArgs, + arguments: [obj(tx, args.bag), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export interface ContainsArgs { + bag: TransactionObjectInput; + k: GenericArg; +} + +export function contains(tx: Transaction, typeArg: string, args: ContainsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bag::contains`, + typeArguments: [typeArg], + arguments: [obj(tx, args.bag), generic(tx, `${typeArg}`, args.k)], + }); +} + +export function destroyEmpty(tx: Transaction, bag: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bag::destroy_empty`, + arguments: [obj(tx, bag)], + }); +} + +export function isEmpty(tx: Transaction, bag: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bag::is_empty`, + arguments: [obj(tx, bag)], + }); +} + +export function length(tx: Transaction, bag: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bag::length`, + arguments: [obj(tx, bag)], + }); +} + +export interface RemoveArgs { + bag: TransactionObjectInput; + k: GenericArg; +} + +export function remove(tx: Transaction, typeArgs: [string, string], args: RemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bag::remove`, + typeArguments: typeArgs, + arguments: [obj(tx, args.bag), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export function new_(tx: Transaction) { + return tx.moveCall({ target: `${PUBLISHED_AT}::bag::new`, arguments: [] }); +} + +export interface ContainsWithTypeArgs { + bag: TransactionObjectInput; + k: GenericArg; +} + +export function containsWithType(tx: Transaction, typeArgs: [string, string], args: ContainsWithTypeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bag::contains_with_type`, + typeArguments: typeArgs, + arguments: [obj(tx, args.bag), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} diff --git a/src/services/models/sui/sui/bag/structs.ts b/src/services/models/sui/sui/bag/structs.ts new file mode 100644 index 00000000..e0aa0135 --- /dev/null +++ b/src/services/models/sui/sui/bag/structs.ts @@ -0,0 +1,189 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { UID } from "../object/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Bag =============================== */ + +export function isBag(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::bag::Bag`; +} + +export interface BagFields { + id: ToField; + size: ToField<"u64">; +} + +export type BagReified = Reified; + +export class Bag implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::bag::Bag`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Bag.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Bag.$isPhantom; + + readonly id: ToField; + readonly size: ToField<"u64">; + + private constructor(typeArgs: [], fields: BagFields) { + this.$fullTypeName = composeSuiType(Bag.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.size = fields.size; + } + + static reified(): BagReified { + return { + typeName: Bag.$typeName, + fullTypeName: composeSuiType(Bag.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Bag.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Bag.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Bag.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Bag.fromBcs(data), + bcs: Bag.bcs, + fromJSONField: (field: any) => Bag.fromJSONField(field), + fromJSON: (json: Record) => Bag.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Bag.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Bag.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Bag.fetch(client, id), + new: (fields: BagFields) => { + return new Bag([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Bag.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Bag.reified()); + } + static get p() { + return Bag.phantom(); + } + + static get bcs() { + return bcs.struct("Bag", { + id: UID.bcs, + size: bcs.u64(), + }); + } + + static fromFields(fields: Record): Bag { + return Bag.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + size: decodeFromFields("u64", fields.size), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Bag { + if (!isBag(item.type)) { + throw new Error("not a Bag type"); + } + + return Bag.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + size: decodeFromFieldsWithTypes("u64", item.fields.size), + }); + } + + static fromBcs(data: Uint8Array): Bag { + return Bag.fromFields(Bag.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + size: this.size.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Bag { + return Bag.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + size: decodeFromJSONField("u64", field.size), + }); + } + + static fromJSON(json: Record): Bag { + if (json.$typeName !== Bag.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Bag.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Bag { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isBag(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Bag object`); + } + return Bag.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Bag { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isBag(data.bcs.type)) { + throw new Error(`object at is not a Bag object`); + } + + return Bag.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Bag.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Bag object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isBag(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Bag object`); + } + + return Bag.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/sui/balance/functions.ts b/src/services/models/sui/sui/balance/functions.ts new file mode 100644 index 00000000..031ba85a --- /dev/null +++ b/src/services/models/sui/sui/balance/functions.ts @@ -0,0 +1,128 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function value(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::balance::value`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function createStakingRewards(tx: Transaction, typeArg: string, value: bigint | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::balance::create_staking_rewards`, + typeArguments: [typeArg], + arguments: [pure(tx, value, `u64`)], + }); +} + +export function createSupply(tx: Transaction, typeArg: string, t: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::balance::create_supply`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, t)], + }); +} + +export interface DecreaseSupplyArgs { + self: TransactionObjectInput; + balance: TransactionObjectInput; +} + +export function decreaseSupply(tx: Transaction, typeArg: string, args: DecreaseSupplyArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::balance::decrease_supply`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.balance)], + }); +} + +export function destroyStorageRebates(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::balance::destroy_storage_rebates`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function destroySupply(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::balance::destroy_supply`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function destroyZero(tx: Transaction, typeArg: string, balance: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::balance::destroy_zero`, + typeArguments: [typeArg], + arguments: [obj(tx, balance)], + }); +} + +export interface IncreaseSupplyArgs { + self: TransactionObjectInput; + value: bigint | TransactionArgument; +} + +export function increaseSupply(tx: Transaction, typeArg: string, args: IncreaseSupplyArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::balance::increase_supply`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), pure(tx, args.value, `u64`)], + }); +} + +export interface JoinArgs { + self: TransactionObjectInput; + balance: TransactionObjectInput; +} + +export function join(tx: Transaction, typeArg: string, args: JoinArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::balance::join`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.balance)], + }); +} + +export interface SplitArgs { + self: TransactionObjectInput; + value: bigint | TransactionArgument; +} + +export function split(tx: Transaction, typeArg: string, args: SplitArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::balance::split`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), pure(tx, args.value, `u64`)], + }); +} + +export function supplyValue(tx: Transaction, typeArg: string, supply: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::balance::supply_value`, + typeArguments: [typeArg], + arguments: [obj(tx, supply)], + }); +} + +export function withdrawAll(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::balance::withdraw_all`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function zero(tx: Transaction, typeArg: string) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::balance::zero`, + typeArguments: [typeArg], + arguments: [], + }); +} diff --git a/src/services/models/sui/sui/balance/structs.ts b/src/services/models/sui/sui/balance/structs.ts new file mode 100644 index 00000000..29679036 --- /dev/null +++ b/src/services/models/sui/sui/balance/structs.ts @@ -0,0 +1,427 @@ +// @ts-nocheck +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Balance =============================== */ + +export function isBalance(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::balance::Balance` + "<"); +} + +export interface BalanceFields { + value: ToField<"u64">; +} + +export type BalanceReified = Reified, BalanceFields>; + +export class Balance implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::balance::Balance`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = Balance.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = Balance.$isPhantom; + + readonly value: ToField<"u64">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: BalanceFields) { + this.$fullTypeName = composeSuiType(Balance.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.value = fields.value; + } + + static reified>(T: T): BalanceReified> { + return { + typeName: Balance.$typeName, + fullTypeName: composeSuiType(Balance.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: Balance.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => Balance.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Balance.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => Balance.fromBcs(T, data), + bcs: Balance.bcs, + fromJSONField: (field: any) => Balance.fromJSONField(T, field), + fromJSON: (json: Record) => Balance.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => Balance.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => Balance.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => Balance.fetch(client, T, id), + new: (fields: BalanceFields>) => { + return new Balance([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Balance.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(Balance.reified(T)); + } + static get p() { + return Balance.phantom; + } + + static get bcs() { + return bcs.struct("Balance", { + value: bcs.u64(), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): Balance> { + return Balance.reified(typeArg).new({ + value: decodeFromFields("u64", fields.value), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): Balance> { + if (!isBalance(item.type)) { + throw new Error("not a Balance type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Balance.reified(typeArg).new({ + value: decodeFromFieldsWithTypes("u64", item.fields.value), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): Balance> { + return Balance.fromFields(typeArg, Balance.bcs.parse(data)); + } + + toJSONField() { + return { + value: this.value.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): Balance> { + return Balance.reified(typeArg).new({ + value: decodeFromJSONField("u64", field.value), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): Balance> { + if (json.$typeName !== Balance.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Balance.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Balance.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): Balance> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isBalance(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Balance object`); + } + return Balance.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): Balance> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isBalance(data.bcs.type)) { + throw new Error(`object at is not a Balance object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Balance.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Balance.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Balance object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isBalance(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Balance object`); + } + + return Balance.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== Supply =============================== */ + +export function isSupply(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::balance::Supply` + "<"); +} + +export interface SupplyFields { + value: ToField<"u64">; +} + +export type SupplyReified = Reified, SupplyFields>; + +export class Supply implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::balance::Supply`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = Supply.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = Supply.$isPhantom; + + readonly value: ToField<"u64">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: SupplyFields) { + this.$fullTypeName = composeSuiType(Supply.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.value = fields.value; + } + + static reified>(T: T): SupplyReified> { + return { + typeName: Supply.$typeName, + fullTypeName: composeSuiType(Supply.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: Supply.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => Supply.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Supply.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => Supply.fromBcs(T, data), + bcs: Supply.bcs, + fromJSONField: (field: any) => Supply.fromJSONField(T, field), + fromJSON: (json: Record) => Supply.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => Supply.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => Supply.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => Supply.fetch(client, T, id), + new: (fields: SupplyFields>) => { + return new Supply([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Supply.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(Supply.reified(T)); + } + static get p() { + return Supply.phantom; + } + + static get bcs() { + return bcs.struct("Supply", { + value: bcs.u64(), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): Supply> { + return Supply.reified(typeArg).new({ + value: decodeFromFields("u64", fields.value), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): Supply> { + if (!isSupply(item.type)) { + throw new Error("not a Supply type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Supply.reified(typeArg).new({ + value: decodeFromFieldsWithTypes("u64", item.fields.value), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): Supply> { + return Supply.fromFields(typeArg, Supply.bcs.parse(data)); + } + + toJSONField() { + return { + value: this.value.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): Supply> { + return Supply.reified(typeArg).new({ + value: decodeFromJSONField("u64", field.value), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): Supply> { + if (json.$typeName !== Supply.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Supply.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Supply.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): Supply> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isSupply(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Supply object`); + } + return Supply.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): Supply> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isSupply(data.bcs.type)) { + throw new Error(`object at is not a Supply object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Supply.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Supply.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Supply object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isSupply(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Supply object`); + } + + return Supply.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/sui/bcs/functions.ts b/src/services/models/sui/sui/bcs/functions.ts new file mode 100644 index 00000000..353180ed --- /dev/null +++ b/src/services/models/sui/sui/bcs/functions.ts @@ -0,0 +1,208 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function toBytes(tx: Transaction, typeArg: string, value: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::to_bytes`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, value)], + }); +} + +export function new_(tx: Transaction, bytes: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::new`, + arguments: [pure(tx, bytes, `vector`)], + }); +} + +export function intoRemainderBytes(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::into_remainder_bytes`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelAddress(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_address`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelBool(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_bool`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelOptionAddress(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_option_address`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelOptionBool(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_option_bool`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelOptionU128(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_option_u128`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelOptionU16(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_option_u16`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelOptionU256(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_option_u256`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelOptionU32(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_option_u32`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelOptionU64(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_option_u64`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelOptionU8(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_option_u8`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelU128(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_u128`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelU16(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_u16`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelU256(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_u256`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelU32(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_u32`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelU64(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_u64`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelU8(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_u8`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelVecAddress(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_vec_address`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelVecBool(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_vec_bool`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelVecLength(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_vec_length`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelVecU128(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_vec_u128`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelVecU16(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_vec_u16`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelVecU256(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_vec_u256`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelVecU32(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_vec_u32`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelVecU64(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_vec_u64`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelVecU8(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_vec_u8`, + arguments: [obj(tx, bcs)], + }); +} + +export function peelVecVecU8(tx: Transaction, bcs: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bcs::peel_vec_vec_u8`, + arguments: [obj(tx, bcs)], + }); +} diff --git a/src/services/models/sui/sui/bcs/structs.ts b/src/services/models/sui/sui/bcs/structs.ts new file mode 100644 index 00000000..c1225137 --- /dev/null +++ b/src/services/models/sui/sui/bcs/structs.ts @@ -0,0 +1,183 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { Vector } from "../../_framework/vector"; +import { PKG_V26 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== BCS =============================== */ + +export function isBCS(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::bcs::BCS`; +} + +export interface BCSFields { + bytes: ToField>; +} + +export type BCSReified = Reified; + +export class BCS implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::bcs::BCS`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = BCS.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = BCS.$isPhantom; + + readonly bytes: ToField>; + + private constructor(typeArgs: [], fields: BCSFields) { + this.$fullTypeName = composeSuiType(BCS.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.bytes = fields.bytes; + } + + static reified(): BCSReified { + return { + typeName: BCS.$typeName, + fullTypeName: composeSuiType(BCS.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: BCS.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => BCS.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => BCS.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => BCS.fromBcs(data), + bcs: BCS.bcs, + fromJSONField: (field: any) => BCS.fromJSONField(field), + fromJSON: (json: Record) => BCS.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => BCS.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => BCS.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => BCS.fetch(client, id), + new: (fields: BCSFields) => { + return new BCS([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return BCS.reified(); + } + + static phantom(): PhantomReified> { + return phantom(BCS.reified()); + } + static get p() { + return BCS.phantom(); + } + + static get bcs() { + return bcs.struct("BCS", { + bytes: bcs.vector(bcs.u8()), + }); + } + + static fromFields(fields: Record): BCS { + return BCS.reified().new({ + bytes: decodeFromFields(reified.vector("u8"), fields.bytes), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): BCS { + if (!isBCS(item.type)) { + throw new Error("not a BCS type"); + } + + return BCS.reified().new({ + bytes: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.bytes), + }); + } + + static fromBcs(data: Uint8Array): BCS { + return BCS.fromFields(BCS.bcs.parse(data)); + } + + toJSONField() { + return { + bytes: fieldToJSON>(`vector`, this.bytes), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): BCS { + return BCS.reified().new({ + bytes: decodeFromJSONField(reified.vector("u8"), field.bytes), + }); + } + + static fromJSON(json: Record): BCS { + if (json.$typeName !== BCS.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return BCS.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): BCS { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isBCS(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a BCS object`); + } + return BCS.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): BCS { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isBCS(data.bcs.type)) { + throw new Error(`object at is not a BCS object`); + } + + return BCS.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return BCS.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching BCS object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isBCS(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a BCS object`); + } + + return BCS.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/sui/bls12381/functions.ts b/src/services/models/sui/sui/bls12381/functions.ts new file mode 100644 index 00000000..277263b5 --- /dev/null +++ b/src/services/models/sui/sui/bls12381/functions.ts @@ -0,0 +1,428 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure, vector } from "../../_framework/util"; +import { Element } from "../group-ops/structs"; +import { G1, G2, Scalar, UncompressedG1 } from "./structs"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface PairingArgs { + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function pairing(tx: Transaction, args: PairingArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::pairing`, + arguments: [obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export interface Bls12381MinPkVerifyArgs { + signature: Array | TransactionArgument; + publicKey: Array | TransactionArgument; + msg: Array | TransactionArgument; +} + +export function bls12381MinPkVerify(tx: Transaction, args: Bls12381MinPkVerifyArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::bls12381_min_pk_verify`, + arguments: [ + pure(tx, args.signature, `vector`), + pure(tx, args.publicKey, `vector`), + pure(tx, args.msg, `vector`), + ], + }); +} + +export interface Bls12381MinSigVerifyArgs { + signature: Array | TransactionArgument; + publicKey: Array | TransactionArgument; + msg: Array | TransactionArgument; +} + +export function bls12381MinSigVerify(tx: Transaction, args: Bls12381MinSigVerifyArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::bls12381_min_sig_verify`, + arguments: [ + pure(tx, args.signature, `vector`), + pure(tx, args.publicKey, `vector`), + pure(tx, args.msg, `vector`), + ], + }); +} + +export interface G1AddArgs { + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function g1Add(tx: Transaction, args: G1AddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g1_add`, + arguments: [obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export interface G1DivArgs { + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function g1Div(tx: Transaction, args: G1DivArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g1_div`, + arguments: [obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export function g1FromBytes(tx: Transaction, bytes: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g1_from_bytes`, + arguments: [pure(tx, bytes, `vector`)], + }); +} + +export function g1Generator(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g1_generator`, + arguments: [], + }); +} + +export function g1Identity(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g1_identity`, + arguments: [], + }); +} + +export interface G1MulArgs { + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function g1Mul(tx: Transaction, args: G1MulArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g1_mul`, + arguments: [obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export interface G1MultiScalarMultiplicationArgs { + scalars: Array | TransactionArgument; + elements: Array | TransactionArgument; +} + +export function g1MultiScalarMultiplication(tx: Transaction, args: G1MultiScalarMultiplicationArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g1_multi_scalar_multiplication`, + arguments: [ + vector(tx, `${Element.$typeName}<${Scalar.$typeName}>`, args.scalars), + vector(tx, `${Element.$typeName}<${G1.$typeName}>`, args.elements), + ], + }); +} + +export function g1Neg(tx: Transaction, e: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g1_neg`, + arguments: [obj(tx, e)], + }); +} + +export interface G1SubArgs { + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function g1Sub(tx: Transaction, args: G1SubArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g1_sub`, + arguments: [obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export function g1ToUncompressedG1(tx: Transaction, e: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g1_to_uncompressed_g1`, + arguments: [obj(tx, e)], + }); +} + +export interface G2AddArgs { + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function g2Add(tx: Transaction, args: G2AddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g2_add`, + arguments: [obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export interface G2DivArgs { + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function g2Div(tx: Transaction, args: G2DivArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g2_div`, + arguments: [obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export function g2FromBytes(tx: Transaction, bytes: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g2_from_bytes`, + arguments: [pure(tx, bytes, `vector`)], + }); +} + +export function g2Generator(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g2_generator`, + arguments: [], + }); +} + +export function g2Identity(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g2_identity`, + arguments: [], + }); +} + +export interface G2MulArgs { + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function g2Mul(tx: Transaction, args: G2MulArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g2_mul`, + arguments: [obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export interface G2MultiScalarMultiplicationArgs { + scalars: Array | TransactionArgument; + elements: Array | TransactionArgument; +} + +export function g2MultiScalarMultiplication(tx: Transaction, args: G2MultiScalarMultiplicationArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g2_multi_scalar_multiplication`, + arguments: [ + vector(tx, `${Element.$typeName}<${Scalar.$typeName}>`, args.scalars), + vector(tx, `${Element.$typeName}<${G2.$typeName}>`, args.elements), + ], + }); +} + +export function g2Neg(tx: Transaction, e: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g2_neg`, + arguments: [obj(tx, e)], + }); +} + +export interface G2SubArgs { + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function g2Sub(tx: Transaction, args: G2SubArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::g2_sub`, + arguments: [obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export interface GtAddArgs { + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function gtAdd(tx: Transaction, args: GtAddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::gt_add`, + arguments: [obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export interface GtDivArgs { + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function gtDiv(tx: Transaction, args: GtDivArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::gt_div`, + arguments: [obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export function gtGenerator(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::gt_generator`, + arguments: [], + }); +} + +export function gtIdentity(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::gt_identity`, + arguments: [], + }); +} + +export interface GtMulArgs { + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function gtMul(tx: Transaction, args: GtMulArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::gt_mul`, + arguments: [obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export function gtNeg(tx: Transaction, e: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::gt_neg`, + arguments: [obj(tx, e)], + }); +} + +export interface GtSubArgs { + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function gtSub(tx: Transaction, args: GtSubArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::gt_sub`, + arguments: [obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export function hashToG1(tx: Transaction, m: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::hash_to_g1`, + arguments: [pure(tx, m, `vector`)], + }); +} + +export function hashToG2(tx: Transaction, m: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::hash_to_g2`, + arguments: [pure(tx, m, `vector`)], + }); +} + +export interface ScalarAddArgs { + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function scalarAdd(tx: Transaction, args: ScalarAddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::scalar_add`, + arguments: [obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export interface ScalarDivArgs { + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function scalarDiv(tx: Transaction, args: ScalarDivArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::scalar_div`, + arguments: [obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export function scalarFromBytes(tx: Transaction, bytes: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::scalar_from_bytes`, + arguments: [pure(tx, bytes, `vector`)], + }); +} + +export function scalarFromU64(tx: Transaction, x: bigint | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::scalar_from_u64`, + arguments: [pure(tx, x, `u64`)], + }); +} + +export function scalarInv(tx: Transaction, e: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::scalar_inv`, + arguments: [obj(tx, e)], + }); +} + +export interface ScalarMulArgs { + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function scalarMul(tx: Transaction, args: ScalarMulArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::scalar_mul`, + arguments: [obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export function scalarNeg(tx: Transaction, e: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::scalar_neg`, + arguments: [obj(tx, e)], + }); +} + +export function scalarOne(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::scalar_one`, + arguments: [], + }); +} + +export interface ScalarSubArgs { + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function scalarSub(tx: Transaction, args: ScalarSubArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::scalar_sub`, + arguments: [obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export function scalarZero(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::scalar_zero`, + arguments: [], + }); +} + +export function uncompressedG1Sum(tx: Transaction, terms: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::uncompressed_g1_sum`, + arguments: [vector(tx, `${Element.$typeName}<${UncompressedG1.$typeName}>`, terms)], + }); +} + +export function uncompressedG1ToG1(tx: Transaction, e: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bls12381::uncompressed_g1_to_g1`, + arguments: [obj(tx, e)], + }); +} diff --git a/src/services/models/sui/sui/bls12381/structs.ts b/src/services/models/sui/sui/bls12381/structs.ts new file mode 100644 index 00000000..abe8ebb0 --- /dev/null +++ b/src/services/models/sui/sui/bls12381/structs.ts @@ -0,0 +1,832 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== G1 =============================== */ + +export function isG1(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::bls12381::G1`; +} + +export interface G1Fields { + dummyField: ToField<"bool">; +} + +export type G1Reified = Reified; + +export class G1 implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::bls12381::G1`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = G1.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = G1.$isPhantom; + + readonly dummyField: ToField<"bool">; + + private constructor(typeArgs: [], fields: G1Fields) { + this.$fullTypeName = composeSuiType(G1.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.dummyField = fields.dummyField; + } + + static reified(): G1Reified { + return { + typeName: G1.$typeName, + fullTypeName: composeSuiType(G1.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: G1.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => G1.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => G1.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => G1.fromBcs(data), + bcs: G1.bcs, + fromJSONField: (field: any) => G1.fromJSONField(field), + fromJSON: (json: Record) => G1.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => G1.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => G1.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => G1.fetch(client, id), + new: (fields: G1Fields) => { + return new G1([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return G1.reified(); + } + + static phantom(): PhantomReified> { + return phantom(G1.reified()); + } + static get p() { + return G1.phantom(); + } + + static get bcs() { + return bcs.struct("G1", { + dummy_field: bcs.bool(), + }); + } + + static fromFields(fields: Record): G1 { + return G1.reified().new({ + dummyField: decodeFromFields("bool", fields.dummy_field), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): G1 { + if (!isG1(item.type)) { + throw new Error("not a G1 type"); + } + + return G1.reified().new({ + dummyField: decodeFromFieldsWithTypes("bool", item.fields.dummy_field), + }); + } + + static fromBcs(data: Uint8Array): G1 { + return G1.fromFields(G1.bcs.parse(data)); + } + + toJSONField() { + return { + dummyField: this.dummyField, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): G1 { + return G1.reified().new({ + dummyField: decodeFromJSONField("bool", field.dummyField), + }); + } + + static fromJSON(json: Record): G1 { + if (json.$typeName !== G1.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return G1.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): G1 { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isG1(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a G1 object`); + } + return G1.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): G1 { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isG1(data.bcs.type)) { + throw new Error(`object at is not a G1 object`); + } + + return G1.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return G1.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching G1 object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isG1(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a G1 object`); + } + + return G1.fromSuiObjectData(res.data); + } +} + +/* ============================== G2 =============================== */ + +export function isG2(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::bls12381::G2`; +} + +export interface G2Fields { + dummyField: ToField<"bool">; +} + +export type G2Reified = Reified; + +export class G2 implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::bls12381::G2`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = G2.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = G2.$isPhantom; + + readonly dummyField: ToField<"bool">; + + private constructor(typeArgs: [], fields: G2Fields) { + this.$fullTypeName = composeSuiType(G2.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.dummyField = fields.dummyField; + } + + static reified(): G2Reified { + return { + typeName: G2.$typeName, + fullTypeName: composeSuiType(G2.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: G2.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => G2.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => G2.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => G2.fromBcs(data), + bcs: G2.bcs, + fromJSONField: (field: any) => G2.fromJSONField(field), + fromJSON: (json: Record) => G2.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => G2.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => G2.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => G2.fetch(client, id), + new: (fields: G2Fields) => { + return new G2([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return G2.reified(); + } + + static phantom(): PhantomReified> { + return phantom(G2.reified()); + } + static get p() { + return G2.phantom(); + } + + static get bcs() { + return bcs.struct("G2", { + dummy_field: bcs.bool(), + }); + } + + static fromFields(fields: Record): G2 { + return G2.reified().new({ + dummyField: decodeFromFields("bool", fields.dummy_field), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): G2 { + if (!isG2(item.type)) { + throw new Error("not a G2 type"); + } + + return G2.reified().new({ + dummyField: decodeFromFieldsWithTypes("bool", item.fields.dummy_field), + }); + } + + static fromBcs(data: Uint8Array): G2 { + return G2.fromFields(G2.bcs.parse(data)); + } + + toJSONField() { + return { + dummyField: this.dummyField, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): G2 { + return G2.reified().new({ + dummyField: decodeFromJSONField("bool", field.dummyField), + }); + } + + static fromJSON(json: Record): G2 { + if (json.$typeName !== G2.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return G2.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): G2 { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isG2(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a G2 object`); + } + return G2.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): G2 { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isG2(data.bcs.type)) { + throw new Error(`object at is not a G2 object`); + } + + return G2.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return G2.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching G2 object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isG2(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a G2 object`); + } + + return G2.fromSuiObjectData(res.data); + } +} + +/* ============================== GT =============================== */ + +export function isGT(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::bls12381::GT`; +} + +export interface GTFields { + dummyField: ToField<"bool">; +} + +export type GTReified = Reified; + +export class GT implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::bls12381::GT`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = GT.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = GT.$isPhantom; + + readonly dummyField: ToField<"bool">; + + private constructor(typeArgs: [], fields: GTFields) { + this.$fullTypeName = composeSuiType(GT.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.dummyField = fields.dummyField; + } + + static reified(): GTReified { + return { + typeName: GT.$typeName, + fullTypeName: composeSuiType(GT.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: GT.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => GT.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => GT.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => GT.fromBcs(data), + bcs: GT.bcs, + fromJSONField: (field: any) => GT.fromJSONField(field), + fromJSON: (json: Record) => GT.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => GT.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => GT.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => GT.fetch(client, id), + new: (fields: GTFields) => { + return new GT([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return GT.reified(); + } + + static phantom(): PhantomReified> { + return phantom(GT.reified()); + } + static get p() { + return GT.phantom(); + } + + static get bcs() { + return bcs.struct("GT", { + dummy_field: bcs.bool(), + }); + } + + static fromFields(fields: Record): GT { + return GT.reified().new({ + dummyField: decodeFromFields("bool", fields.dummy_field), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): GT { + if (!isGT(item.type)) { + throw new Error("not a GT type"); + } + + return GT.reified().new({ + dummyField: decodeFromFieldsWithTypes("bool", item.fields.dummy_field), + }); + } + + static fromBcs(data: Uint8Array): GT { + return GT.fromFields(GT.bcs.parse(data)); + } + + toJSONField() { + return { + dummyField: this.dummyField, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): GT { + return GT.reified().new({ + dummyField: decodeFromJSONField("bool", field.dummyField), + }); + } + + static fromJSON(json: Record): GT { + if (json.$typeName !== GT.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return GT.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): GT { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isGT(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a GT object`); + } + return GT.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): GT { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isGT(data.bcs.type)) { + throw new Error(`object at is not a GT object`); + } + + return GT.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return GT.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching GT object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isGT(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a GT object`); + } + + return GT.fromSuiObjectData(res.data); + } +} + +/* ============================== Scalar =============================== */ + +export function isScalar(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::bls12381::Scalar`; +} + +export interface ScalarFields { + dummyField: ToField<"bool">; +} + +export type ScalarReified = Reified; + +export class Scalar implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::bls12381::Scalar`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Scalar.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Scalar.$isPhantom; + + readonly dummyField: ToField<"bool">; + + private constructor(typeArgs: [], fields: ScalarFields) { + this.$fullTypeName = composeSuiType(Scalar.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.dummyField = fields.dummyField; + } + + static reified(): ScalarReified { + return { + typeName: Scalar.$typeName, + fullTypeName: composeSuiType(Scalar.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Scalar.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Scalar.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Scalar.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Scalar.fromBcs(data), + bcs: Scalar.bcs, + fromJSONField: (field: any) => Scalar.fromJSONField(field), + fromJSON: (json: Record) => Scalar.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Scalar.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Scalar.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Scalar.fetch(client, id), + new: (fields: ScalarFields) => { + return new Scalar([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Scalar.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Scalar.reified()); + } + static get p() { + return Scalar.phantom(); + } + + static get bcs() { + return bcs.struct("Scalar", { + dummy_field: bcs.bool(), + }); + } + + static fromFields(fields: Record): Scalar { + return Scalar.reified().new({ + dummyField: decodeFromFields("bool", fields.dummy_field), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Scalar { + if (!isScalar(item.type)) { + throw new Error("not a Scalar type"); + } + + return Scalar.reified().new({ + dummyField: decodeFromFieldsWithTypes("bool", item.fields.dummy_field), + }); + } + + static fromBcs(data: Uint8Array): Scalar { + return Scalar.fromFields(Scalar.bcs.parse(data)); + } + + toJSONField() { + return { + dummyField: this.dummyField, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Scalar { + return Scalar.reified().new({ + dummyField: decodeFromJSONField("bool", field.dummyField), + }); + } + + static fromJSON(json: Record): Scalar { + if (json.$typeName !== Scalar.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Scalar.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Scalar { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isScalar(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Scalar object`); + } + return Scalar.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Scalar { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isScalar(data.bcs.type)) { + throw new Error(`object at is not a Scalar object`); + } + + return Scalar.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Scalar.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Scalar object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isScalar(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Scalar object`); + } + + return Scalar.fromSuiObjectData(res.data); + } +} + +/* ============================== UncompressedG1 =============================== */ + +export function isUncompressedG1(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::bls12381::UncompressedG1`; +} + +export interface UncompressedG1Fields { + dummyField: ToField<"bool">; +} + +export type UncompressedG1Reified = Reified; + +export class UncompressedG1 implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::bls12381::UncompressedG1`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = UncompressedG1.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = UncompressedG1.$isPhantom; + + readonly dummyField: ToField<"bool">; + + private constructor(typeArgs: [], fields: UncompressedG1Fields) { + this.$fullTypeName = composeSuiType(UncompressedG1.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.dummyField = fields.dummyField; + } + + static reified(): UncompressedG1Reified { + return { + typeName: UncompressedG1.$typeName, + fullTypeName: composeSuiType(UncompressedG1.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: UncompressedG1.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => UncompressedG1.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => UncompressedG1.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => UncompressedG1.fromBcs(data), + bcs: UncompressedG1.bcs, + fromJSONField: (field: any) => UncompressedG1.fromJSONField(field), + fromJSON: (json: Record) => UncompressedG1.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => UncompressedG1.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => UncompressedG1.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => UncompressedG1.fetch(client, id), + new: (fields: UncompressedG1Fields) => { + return new UncompressedG1([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return UncompressedG1.reified(); + } + + static phantom(): PhantomReified> { + return phantom(UncompressedG1.reified()); + } + static get p() { + return UncompressedG1.phantom(); + } + + static get bcs() { + return bcs.struct("UncompressedG1", { + dummy_field: bcs.bool(), + }); + } + + static fromFields(fields: Record): UncompressedG1 { + return UncompressedG1.reified().new({ + dummyField: decodeFromFields("bool", fields.dummy_field), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): UncompressedG1 { + if (!isUncompressedG1(item.type)) { + throw new Error("not a UncompressedG1 type"); + } + + return UncompressedG1.reified().new({ + dummyField: decodeFromFieldsWithTypes("bool", item.fields.dummy_field), + }); + } + + static fromBcs(data: Uint8Array): UncompressedG1 { + return UncompressedG1.fromFields(UncompressedG1.bcs.parse(data)); + } + + toJSONField() { + return { + dummyField: this.dummyField, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): UncompressedG1 { + return UncompressedG1.reified().new({ + dummyField: decodeFromJSONField("bool", field.dummyField), + }); + } + + static fromJSON(json: Record): UncompressedG1 { + if (json.$typeName !== UncompressedG1.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return UncompressedG1.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): UncompressedG1 { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isUncompressedG1(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a UncompressedG1 object`); + } + return UncompressedG1.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): UncompressedG1 { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isUncompressedG1(data.bcs.type)) { + throw new Error(`object at is not a UncompressedG1 object`); + } + + return UncompressedG1.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return UncompressedG1.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching UncompressedG1 object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isUncompressedG1(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a UncompressedG1 object`); + } + + return UncompressedG1.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/sui/borrow/functions.ts b/src/services/models/sui/sui/borrow/functions.ts new file mode 100644 index 00000000..41c65ad4 --- /dev/null +++ b/src/services/models/sui/sui/borrow/functions.ts @@ -0,0 +1,42 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj } from "../../_framework/util"; +import { Transaction, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function borrow(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::borrow::borrow`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function new_(tx: Transaction, typeArg: string, value: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::borrow::new`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, value)], + }); +} + +export function destroy(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::borrow::destroy`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export interface PutBackArgs { + self: TransactionObjectInput; + value: GenericArg; + borrow: TransactionObjectInput; +} + +export function putBack(tx: Transaction, typeArg: string, args: PutBackArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::borrow::put_back`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), generic(tx, `${typeArg}`, args.value), obj(tx, args.borrow)], + }); +} diff --git a/src/services/models/sui/sui/borrow/structs.ts b/src/services/models/sui/sui/borrow/structs.ts new file mode 100644 index 00000000..486c77cc --- /dev/null +++ b/src/services/models/sui/sui/borrow/structs.ts @@ -0,0 +1,408 @@ +// @ts-nocheck +import { Option } from "../../_dependencies/source/0x1/option/structs"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeArgument, + ToTypeStr, + TypeArgument, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + fieldToJSON, + phantom, + toBcs, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { ID } from "../object/structs"; +import { BcsType, bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64, fromHEX, toHEX } from "@mysten/sui/utils"; + +/* ============================== Borrow =============================== */ + +export function isBorrow(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::borrow::Borrow`; +} + +export interface BorrowFields { + ref: ToField<"address">; + obj: ToField; +} + +export type BorrowReified = Reified; + +export class Borrow implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::borrow::Borrow`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Borrow.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Borrow.$isPhantom; + + readonly ref: ToField<"address">; + readonly obj: ToField; + + private constructor(typeArgs: [], fields: BorrowFields) { + this.$fullTypeName = composeSuiType(Borrow.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.ref = fields.ref; + this.obj = fields.obj; + } + + static reified(): BorrowReified { + return { + typeName: Borrow.$typeName, + fullTypeName: composeSuiType(Borrow.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Borrow.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Borrow.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Borrow.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Borrow.fromBcs(data), + bcs: Borrow.bcs, + fromJSONField: (field: any) => Borrow.fromJSONField(field), + fromJSON: (json: Record) => Borrow.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Borrow.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Borrow.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Borrow.fetch(client, id), + new: (fields: BorrowFields) => { + return new Borrow([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Borrow.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Borrow.reified()); + } + static get p() { + return Borrow.phantom(); + } + + static get bcs() { + return bcs.struct("Borrow", { + ref: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + obj: ID.bcs, + }); + } + + static fromFields(fields: Record): Borrow { + return Borrow.reified().new({ + ref: decodeFromFields("address", fields.ref), + obj: decodeFromFields(ID.reified(), fields.obj), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Borrow { + if (!isBorrow(item.type)) { + throw new Error("not a Borrow type"); + } + + return Borrow.reified().new({ + ref: decodeFromFieldsWithTypes("address", item.fields.ref), + obj: decodeFromFieldsWithTypes(ID.reified(), item.fields.obj), + }); + } + + static fromBcs(data: Uint8Array): Borrow { + return Borrow.fromFields(Borrow.bcs.parse(data)); + } + + toJSONField() { + return { + ref: this.ref, + obj: this.obj, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Borrow { + return Borrow.reified().new({ + ref: decodeFromJSONField("address", field.ref), + obj: decodeFromJSONField(ID.reified(), field.obj), + }); + } + + static fromJSON(json: Record): Borrow { + if (json.$typeName !== Borrow.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Borrow.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Borrow { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isBorrow(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Borrow object`); + } + return Borrow.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Borrow { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isBorrow(data.bcs.type)) { + throw new Error(`object at is not a Borrow object`); + } + + return Borrow.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Borrow.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Borrow object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isBorrow(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Borrow object`); + } + + return Borrow.fromSuiObjectData(res.data); + } +} + +/* ============================== Referent =============================== */ + +export function isReferent(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::borrow::Referent` + "<"); +} + +export interface ReferentFields { + id: ToField<"address">; + value: ToField>; +} + +export type ReferentReified = Reified, ReferentFields>; + +export class Referent implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::borrow::Referent`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [false] as const; + + readonly $typeName = Referent.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [ToTypeStr]; + readonly $isPhantom = Referent.$isPhantom; + + readonly id: ToField<"address">; + readonly value: ToField>; + + private constructor(typeArgs: [ToTypeStr], fields: ReferentFields) { + this.$fullTypeName = composeSuiType(Referent.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.value = fields.value; + } + + static reified>(T: T): ReferentReified> { + return { + typeName: Referent.$typeName, + fullTypeName: composeSuiType(Referent.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [ToTypeStr>], + isPhantom: Referent.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => Referent.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Referent.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => Referent.fromBcs(T, data), + bcs: Referent.bcs(toBcs(T)), + fromJSONField: (field: any) => Referent.fromJSONField(T, field), + fromJSON: (json: Record) => Referent.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => Referent.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => Referent.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => Referent.fetch(client, T, id), + new: (fields: ReferentFields>) => { + return new Referent([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Referent.reified; + } + + static phantom>(T: T): PhantomReified>>> { + return phantom(Referent.reified(T)); + } + static get p() { + return Referent.phantom; + } + + static get bcs() { + return >(T: T) => + bcs.struct(`Referent<${T.name}>`, { + id: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + value: Option.bcs(T), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): Referent> { + return Referent.reified(typeArg).new({ + id: decodeFromFields("address", fields.id), + value: decodeFromFields(Option.reified(typeArg), fields.value), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): Referent> { + if (!isReferent(item.type)) { + throw new Error("not a Referent type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Referent.reified(typeArg).new({ + id: decodeFromFieldsWithTypes("address", item.fields.id), + value: decodeFromFieldsWithTypes(Option.reified(typeArg), item.fields.value), + }); + } + + static fromBcs>(typeArg: T, data: Uint8Array): Referent> { + const typeArgs = [typeArg]; + + return Referent.fromFields(typeArg, Referent.bcs(toBcs(typeArgs[0])).parse(data)); + } + + toJSONField() { + return { + id: this.id, + value: fieldToJSON>(`${Option.$typeName}<${this.$typeArgs[0]}>`, this.value), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>(typeArg: T, field: any): Referent> { + return Referent.reified(typeArg).new({ + id: decodeFromJSONField("address", field.id), + value: decodeFromJSONField(Option.reified(typeArg), field.value), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): Referent> { + if (json.$typeName !== Referent.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Referent.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Referent.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): Referent> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isReferent(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Referent object`); + } + return Referent.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): Referent> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isReferent(data.bcs.type)) { + throw new Error(`object at is not a Referent object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Referent.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Referent.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Referent object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isReferent(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Referent object`); + } + + return Referent.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/sui/clock/functions.ts b/src/services/models/sui/sui/clock/functions.ts new file mode 100644 index 00000000..ecd23ded --- /dev/null +++ b/src/services/models/sui/sui/clock/functions.ts @@ -0,0 +1,30 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function create(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::clock::create`, + arguments: [], + }); +} + +export interface ConsensusCommitPrologueArgs { + clock: TransactionObjectInput; + timestampMs: bigint | TransactionArgument; +} + +export function consensusCommitPrologue(tx: Transaction, args: ConsensusCommitPrologueArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::clock::consensus_commit_prologue`, + arguments: [obj(tx, args.clock), pure(tx, args.timestampMs, `u64`)], + }); +} + +export function timestampMs(tx: Transaction, clock: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::clock::timestamp_ms`, + arguments: [obj(tx, clock)], + }); +} diff --git a/src/services/models/sui/sui/clock/structs.ts b/src/services/models/sui/sui/clock/structs.ts new file mode 100644 index 00000000..88bb70c2 --- /dev/null +++ b/src/services/models/sui/sui/clock/structs.ts @@ -0,0 +1,189 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { UID } from "../object/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Clock =============================== */ + +export function isClock(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::clock::Clock`; +} + +export interface ClockFields { + id: ToField; + timestampMs: ToField<"u64">; +} + +export type ClockReified = Reified; + +export class Clock implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::clock::Clock`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Clock.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Clock.$isPhantom; + + readonly id: ToField; + readonly timestampMs: ToField<"u64">; + + private constructor(typeArgs: [], fields: ClockFields) { + this.$fullTypeName = composeSuiType(Clock.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.timestampMs = fields.timestampMs; + } + + static reified(): ClockReified { + return { + typeName: Clock.$typeName, + fullTypeName: composeSuiType(Clock.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Clock.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Clock.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Clock.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Clock.fromBcs(data), + bcs: Clock.bcs, + fromJSONField: (field: any) => Clock.fromJSONField(field), + fromJSON: (json: Record) => Clock.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Clock.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Clock.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Clock.fetch(client, id), + new: (fields: ClockFields) => { + return new Clock([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Clock.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Clock.reified()); + } + static get p() { + return Clock.phantom(); + } + + static get bcs() { + return bcs.struct("Clock", { + id: UID.bcs, + timestamp_ms: bcs.u64(), + }); + } + + static fromFields(fields: Record): Clock { + return Clock.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + timestampMs: decodeFromFields("u64", fields.timestamp_ms), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Clock { + if (!isClock(item.type)) { + throw new Error("not a Clock type"); + } + + return Clock.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + timestampMs: decodeFromFieldsWithTypes("u64", item.fields.timestamp_ms), + }); + } + + static fromBcs(data: Uint8Array): Clock { + return Clock.fromFields(Clock.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + timestampMs: this.timestampMs.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Clock { + return Clock.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + timestampMs: decodeFromJSONField("u64", field.timestampMs), + }); + } + + static fromJSON(json: Record): Clock { + if (json.$typeName !== Clock.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Clock.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Clock { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isClock(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Clock object`); + } + return Clock.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Clock { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isClock(data.bcs.type)) { + throw new Error(`object at is not a Clock object`); + } + + return Clock.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Clock.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Clock object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isClock(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Clock object`); + } + + return Clock.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/sui/coin/functions.ts b/src/services/models/sui/sui/coin/functions.ts new file mode 100644 index 00000000..b3ccd5b0 --- /dev/null +++ b/src/services/models/sui/sui/coin/functions.ts @@ -0,0 +1,554 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { String as String1 } from "../../_dependencies/source/0x1/ascii/structs"; +import { String } from "../../_dependencies/source/0x1/string/structs"; +import { GenericArg, generic, obj, option, pure } from "../../_framework/util"; +import { Url } from "../url/structs"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function value(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::value`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export interface TakeArgs { + balance: TransactionObjectInput; + value: bigint | TransactionArgument; +} + +export function take(tx: Transaction, typeArg: string, args: TakeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::take`, + typeArguments: [typeArg], + arguments: [obj(tx, args.balance), pure(tx, args.value, `u64`)], + }); +} + +export function balance(tx: Transaction, typeArg: string, coin: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::balance`, + typeArguments: [typeArg], + arguments: [obj(tx, coin)], + }); +} + +export function destroyZero(tx: Transaction, typeArg: string, c: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::destroy_zero`, + typeArguments: [typeArg], + arguments: [obj(tx, c)], + }); +} + +export interface JoinArgs { + self: TransactionObjectInput; + c: TransactionObjectInput; +} + +export function join(tx: Transaction, typeArg: string, args: JoinArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::join`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.c)], + }); +} + +export interface SplitArgs { + self: TransactionObjectInput; + splitAmount: bigint | TransactionArgument; +} + +export function split(tx: Transaction, typeArg: string, args: SplitArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::split`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), pure(tx, args.splitAmount, `u64`)], + }); +} + +export function supply(tx: Transaction, typeArg: string, treasury: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::supply`, + typeArguments: [typeArg], + arguments: [obj(tx, treasury)], + }); +} + +export function zero(tx: Transaction, typeArg: string) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::zero`, + typeArguments: [typeArg], + arguments: [], + }); +} + +export function balanceMut(tx: Transaction, typeArg: string, coin: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::balance_mut`, + typeArguments: [typeArg], + arguments: [obj(tx, coin)], + }); +} + +export interface BurnArgs { + cap: TransactionObjectInput; + c: TransactionObjectInput; +} + +export function burn(tx: Transaction, typeArg: string, args: BurnArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::burn`, + typeArguments: [typeArg], + arguments: [obj(tx, args.cap), obj(tx, args.c)], + }); +} + +export interface CreateCurrencyArgs { + witness: GenericArg; + decimals: number | TransactionArgument; + symbol: Array | TransactionArgument; + name: Array | TransactionArgument; + description: Array | TransactionArgument; + iconUrl: TransactionObjectInput | TransactionArgument | null; +} + +export function createCurrency(tx: Transaction, typeArg: string, args: CreateCurrencyArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::create_currency`, + typeArguments: [typeArg], + arguments: [ + generic(tx, `${typeArg}`, args.witness), + pure(tx, args.decimals, `u8`), + pure(tx, args.symbol, `vector`), + pure(tx, args.name, `vector`), + pure(tx, args.description, `vector`), + option(tx, `${Url.$typeName}`, args.iconUrl), + ], + }); +} + +export interface CreateRegulatedCurrencyArgs { + witness: GenericArg; + decimals: number | TransactionArgument; + symbol: Array | TransactionArgument; + name: Array | TransactionArgument; + description: Array | TransactionArgument; + iconUrl: TransactionObjectInput | TransactionArgument | null; +} + +export function createRegulatedCurrency(tx: Transaction, typeArg: string, args: CreateRegulatedCurrencyArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::create_regulated_currency`, + typeArguments: [typeArg], + arguments: [ + generic(tx, `${typeArg}`, args.witness), + pure(tx, args.decimals, `u8`), + pure(tx, args.symbol, `vector`), + pure(tx, args.name, `vector`), + pure(tx, args.description, `vector`), + option(tx, `${Url.$typeName}`, args.iconUrl), + ], + }); +} + +export interface CreateRegulatedCurrencyV2Args { + witness: GenericArg; + decimals: number | TransactionArgument; + symbol: Array | TransactionArgument; + name: Array | TransactionArgument; + description: Array | TransactionArgument; + iconUrl: TransactionObjectInput | TransactionArgument | null; + allowGlobalPause: boolean | TransactionArgument; +} + +export function createRegulatedCurrencyV2(tx: Transaction, typeArg: string, args: CreateRegulatedCurrencyV2Args) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::create_regulated_currency_v2`, + typeArguments: [typeArg], + arguments: [ + generic(tx, `${typeArg}`, args.witness), + pure(tx, args.decimals, `u8`), + pure(tx, args.symbol, `vector`), + pure(tx, args.name, `vector`), + pure(tx, args.description, `vector`), + option(tx, `${Url.$typeName}`, args.iconUrl), + pure(tx, args.allowGlobalPause, `bool`), + ], + }); +} + +export interface DenyListAddArgs { + denyList: TransactionObjectInput; + denyCap: TransactionObjectInput; + addr: string | TransactionArgument; +} + +export function denyListAdd(tx: Transaction, typeArg: string, args: DenyListAddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::deny_list_add`, + typeArguments: [typeArg], + arguments: [obj(tx, args.denyList), obj(tx, args.denyCap), pure(tx, args.addr, `address`)], + }); +} + +export interface DenyListContainsArgs { + denyList: TransactionObjectInput; + addr: string | TransactionArgument; +} + +export function denyListContains(tx: Transaction, typeArg: string, args: DenyListContainsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::deny_list_contains`, + typeArguments: [typeArg], + arguments: [obj(tx, args.denyList), pure(tx, args.addr, `address`)], + }); +} + +export interface DenyListRemoveArgs { + denyList: TransactionObjectInput; + denyCap: TransactionObjectInput; + addr: string | TransactionArgument; +} + +export function denyListRemove(tx: Transaction, typeArg: string, args: DenyListRemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::deny_list_remove`, + typeArguments: [typeArg], + arguments: [obj(tx, args.denyList), obj(tx, args.denyCap), pure(tx, args.addr, `address`)], + }); +} + +export interface DenyListV2AddArgs { + denyList: TransactionObjectInput; + denyCap: TransactionObjectInput; + addr: string | TransactionArgument; +} + +export function denyListV2Add(tx: Transaction, typeArg: string, args: DenyListV2AddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::deny_list_v2_add`, + typeArguments: [typeArg], + arguments: [obj(tx, args.denyList), obj(tx, args.denyCap), pure(tx, args.addr, `address`)], + }); +} + +export interface DenyListV2ContainsCurrentEpochArgs { + denyList: TransactionObjectInput; + addr: string | TransactionArgument; +} + +export function denyListV2ContainsCurrentEpoch( + tx: Transaction, + typeArg: string, + args: DenyListV2ContainsCurrentEpochArgs +) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::deny_list_v2_contains_current_epoch`, + typeArguments: [typeArg], + arguments: [obj(tx, args.denyList), pure(tx, args.addr, `address`)], + }); +} + +export interface DenyListV2ContainsNextEpochArgs { + denyList: TransactionObjectInput; + addr: string | TransactionArgument; +} + +export function denyListV2ContainsNextEpoch(tx: Transaction, typeArg: string, args: DenyListV2ContainsNextEpochArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::deny_list_v2_contains_next_epoch`, + typeArguments: [typeArg], + arguments: [obj(tx, args.denyList), pure(tx, args.addr, `address`)], + }); +} + +export interface DenyListV2DisableGlobalPauseArgs { + denyList: TransactionObjectInput; + denyCap: TransactionObjectInput; +} + +export function denyListV2DisableGlobalPause(tx: Transaction, typeArg: string, args: DenyListV2DisableGlobalPauseArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::deny_list_v2_disable_global_pause`, + typeArguments: [typeArg], + arguments: [obj(tx, args.denyList), obj(tx, args.denyCap)], + }); +} + +export interface DenyListV2EnableGlobalPauseArgs { + denyList: TransactionObjectInput; + denyCap: TransactionObjectInput; +} + +export function denyListV2EnableGlobalPause(tx: Transaction, typeArg: string, args: DenyListV2EnableGlobalPauseArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::deny_list_v2_enable_global_pause`, + typeArguments: [typeArg], + arguments: [obj(tx, args.denyList), obj(tx, args.denyCap)], + }); +} + +export function denyListV2IsGlobalPauseEnabledCurrentEpoch( + tx: Transaction, + typeArg: string, + denyList: TransactionObjectInput +) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::deny_list_v2_is_global_pause_enabled_current_epoch`, + typeArguments: [typeArg], + arguments: [obj(tx, denyList)], + }); +} + +export function denyListV2IsGlobalPauseEnabledNextEpoch( + tx: Transaction, + typeArg: string, + denyList: TransactionObjectInput +) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::deny_list_v2_is_global_pause_enabled_next_epoch`, + typeArguments: [typeArg], + arguments: [obj(tx, denyList)], + }); +} + +export interface DenyListV2RemoveArgs { + denyList: TransactionObjectInput; + denyCap: TransactionObjectInput; + addr: string | TransactionArgument; +} + +export function denyListV2Remove(tx: Transaction, typeArg: string, args: DenyListV2RemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::deny_list_v2_remove`, + typeArguments: [typeArg], + arguments: [obj(tx, args.denyList), obj(tx, args.denyCap), pure(tx, args.addr, `address`)], + }); +} + +export interface DivideIntoNArgs { + self: TransactionObjectInput; + n: bigint | TransactionArgument; +} + +export function divideIntoN(tx: Transaction, typeArg: string, args: DivideIntoNArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::divide_into_n`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), pure(tx, args.n, `u64`)], + }); +} + +export function fromBalance(tx: Transaction, typeArg: string, balance: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::from_balance`, + typeArguments: [typeArg], + arguments: [obj(tx, balance)], + }); +} + +export function getDecimals(tx: Transaction, typeArg: string, metadata: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::get_decimals`, + typeArguments: [typeArg], + arguments: [obj(tx, metadata)], + }); +} + +export function getDescription(tx: Transaction, typeArg: string, metadata: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::get_description`, + typeArguments: [typeArg], + arguments: [obj(tx, metadata)], + }); +} + +export function getIconUrl(tx: Transaction, typeArg: string, metadata: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::get_icon_url`, + typeArguments: [typeArg], + arguments: [obj(tx, metadata)], + }); +} + +export function getName(tx: Transaction, typeArg: string, metadata: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::get_name`, + typeArguments: [typeArg], + arguments: [obj(tx, metadata)], + }); +} + +export function getSymbol(tx: Transaction, typeArg: string, metadata: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::get_symbol`, + typeArguments: [typeArg], + arguments: [obj(tx, metadata)], + }); +} + +export function intoBalance(tx: Transaction, typeArg: string, coin: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::into_balance`, + typeArguments: [typeArg], + arguments: [obj(tx, coin)], + }); +} + +export interface MigrateRegulatedCurrencyToV2Args { + denyList: TransactionObjectInput; + cap: TransactionObjectInput; + allowGlobalPause: boolean | TransactionArgument; +} + +export function migrateRegulatedCurrencyToV2(tx: Transaction, typeArg: string, args: MigrateRegulatedCurrencyToV2Args) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::migrate_regulated_currency_to_v2`, + typeArguments: [typeArg], + arguments: [obj(tx, args.denyList), obj(tx, args.cap), pure(tx, args.allowGlobalPause, `bool`)], + }); +} + +export interface MintArgs { + cap: TransactionObjectInput; + value: bigint | TransactionArgument; +} + +export function mint(tx: Transaction, typeArg: string, args: MintArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::mint`, + typeArguments: [typeArg], + arguments: [obj(tx, args.cap), pure(tx, args.value, `u64`)], + }); +} + +export interface MintAndTransferArgs { + c: TransactionObjectInput; + amount: bigint | TransactionArgument; + recipient: string | TransactionArgument; +} + +export function mintAndTransfer(tx: Transaction, typeArg: string, args: MintAndTransferArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::mint_and_transfer`, + typeArguments: [typeArg], + arguments: [obj(tx, args.c), pure(tx, args.amount, `u64`), pure(tx, args.recipient, `address`)], + }); +} + +export interface MintBalanceArgs { + cap: TransactionObjectInput; + value: bigint | TransactionArgument; +} + +export function mintBalance(tx: Transaction, typeArg: string, args: MintBalanceArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::mint_balance`, + typeArguments: [typeArg], + arguments: [obj(tx, args.cap), pure(tx, args.value, `u64`)], + }); +} + +export interface PutArgs { + balance: TransactionObjectInput; + coin: TransactionObjectInput; +} + +export function put(tx: Transaction, typeArg: string, args: PutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::put`, + typeArguments: [typeArg], + arguments: [obj(tx, args.balance), obj(tx, args.coin)], + }); +} + +export function supplyImmut(tx: Transaction, typeArg: string, treasury: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::supply_immut`, + typeArguments: [typeArg], + arguments: [obj(tx, treasury)], + }); +} + +export function supplyMut(tx: Transaction, typeArg: string, treasury: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::supply_mut`, + typeArguments: [typeArg], + arguments: [obj(tx, treasury)], + }); +} + +export function totalSupply(tx: Transaction, typeArg: string, cap: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::total_supply`, + typeArguments: [typeArg], + arguments: [obj(tx, cap)], + }); +} + +export function treasuryIntoSupply(tx: Transaction, typeArg: string, treasury: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::treasury_into_supply`, + typeArguments: [typeArg], + arguments: [obj(tx, treasury)], + }); +} + +export interface UpdateDescriptionArgs { + treasury: TransactionObjectInput; + metadata: TransactionObjectInput; + description: string | TransactionArgument; +} + +export function updateDescription(tx: Transaction, typeArg: string, args: UpdateDescriptionArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::update_description`, + typeArguments: [typeArg], + arguments: [obj(tx, args.treasury), obj(tx, args.metadata), pure(tx, args.description, `${String.$typeName}`)], + }); +} + +export interface UpdateIconUrlArgs { + treasury: TransactionObjectInput; + metadata: TransactionObjectInput; + url: string | TransactionArgument; +} + +export function updateIconUrl(tx: Transaction, typeArg: string, args: UpdateIconUrlArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::update_icon_url`, + typeArguments: [typeArg], + arguments: [obj(tx, args.treasury), obj(tx, args.metadata), pure(tx, args.url, `${String1.$typeName}`)], + }); +} + +export interface UpdateNameArgs { + treasury: TransactionObjectInput; + metadata: TransactionObjectInput; + name: string | TransactionArgument; +} + +export function updateName(tx: Transaction, typeArg: string, args: UpdateNameArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::update_name`, + typeArguments: [typeArg], + arguments: [obj(tx, args.treasury), obj(tx, args.metadata), pure(tx, args.name, `${String.$typeName}`)], + }); +} + +export interface UpdateSymbolArgs { + treasury: TransactionObjectInput; + metadata: TransactionObjectInput; + symbol: string | TransactionArgument; +} + +export function updateSymbol(tx: Transaction, typeArg: string, args: UpdateSymbolArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::coin::update_symbol`, + typeArguments: [typeArg], + arguments: [obj(tx, args.treasury), obj(tx, args.metadata), pure(tx, args.symbol, `${String1.$typeName}`)], + }); +} diff --git a/src/services/models/sui/sui/coin/structs.ts b/src/services/models/sui/sui/coin/structs.ts new file mode 100644 index 00000000..ce6f205b --- /dev/null +++ b/src/services/models/sui/sui/coin/structs.ts @@ -0,0 +1,1538 @@ +// @ts-nocheck +import { String as String1 } from "../../_dependencies/source/0x1/ascii/structs"; +import { Option } from "../../_dependencies/source/0x1/option/structs"; +import { String } from "../../_dependencies/source/0x1/string/structs"; +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + fieldToJSON, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { Balance, Supply } from "../balance/structs"; +import { PKG_V26 } from "../index"; +import { ID, UID } from "../object/structs"; +import { Url } from "../url/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Coin =============================== */ + +export function isCoin(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::coin::Coin` + "<"); +} + +export interface CoinFields { + id: ToField; + balance: ToField>; +} + +export type CoinReified = Reified, CoinFields>; + +export class Coin implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::coin::Coin`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = Coin.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = Coin.$isPhantom; + + readonly id: ToField; + readonly balance: ToField>; + + private constructor(typeArgs: [PhantomToTypeStr], fields: CoinFields) { + this.$fullTypeName = composeSuiType(Coin.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.balance = fields.balance; + } + + static reified>(T: T): CoinReified> { + return { + typeName: Coin.$typeName, + fullTypeName: composeSuiType(Coin.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: Coin.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => Coin.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Coin.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => Coin.fromBcs(T, data), + bcs: Coin.bcs, + fromJSONField: (field: any) => Coin.fromJSONField(T, field), + fromJSON: (json: Record) => Coin.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => Coin.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => Coin.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => Coin.fetch(client, T, id), + new: (fields: CoinFields>) => { + return new Coin([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Coin.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(Coin.reified(T)); + } + static get p() { + return Coin.phantom; + } + + static get bcs() { + return bcs.struct("Coin", { + id: UID.bcs, + balance: Balance.bcs, + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): Coin> { + return Coin.reified(typeArg).new({ + id: decodeFromFields(UID.reified(), fields.id), + balance: decodeFromFields(Balance.reified(typeArg), fields.balance), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): Coin> { + if (!isCoin(item.type)) { + throw new Error("not a Coin type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Coin.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + balance: decodeFromFieldsWithTypes(Balance.reified(typeArg), item.fields.balance), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): Coin> { + return Coin.fromFields(typeArg, Coin.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + balance: this.balance.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): Coin> { + return Coin.reified(typeArg).new({ + id: decodeFromJSONField(UID.reified(), field.id), + balance: decodeFromJSONField(Balance.reified(typeArg), field.balance), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): Coin> { + if (json.$typeName !== Coin.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Coin.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Coin.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): Coin> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isCoin(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Coin object`); + } + return Coin.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): Coin> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isCoin(data.bcs.type)) { + throw new Error(`object at is not a Coin object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Coin.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Coin.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Coin object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isCoin(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Coin object`); + } + + return Coin.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== CoinMetadata =============================== */ + +export function isCoinMetadata(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::coin::CoinMetadata` + "<"); +} + +export interface CoinMetadataFields { + id: ToField; + decimals: ToField<"u8">; + name: ToField; + symbol: ToField; + description: ToField; + iconUrl: ToField>; +} + +export type CoinMetadataReified = Reified, CoinMetadataFields>; + +export class CoinMetadata implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::coin::CoinMetadata`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = CoinMetadata.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = CoinMetadata.$isPhantom; + + readonly id: ToField; + readonly decimals: ToField<"u8">; + readonly name: ToField; + readonly symbol: ToField; + readonly description: ToField; + readonly iconUrl: ToField>; + + private constructor(typeArgs: [PhantomToTypeStr], fields: CoinMetadataFields) { + this.$fullTypeName = composeSuiType(CoinMetadata.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.decimals = fields.decimals; + this.name = fields.name; + this.symbol = fields.symbol; + this.description = fields.description; + this.iconUrl = fields.iconUrl; + } + + static reified>(T: T): CoinMetadataReified> { + return { + typeName: CoinMetadata.$typeName, + fullTypeName: composeSuiType(CoinMetadata.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: CoinMetadata.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => CoinMetadata.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => CoinMetadata.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => CoinMetadata.fromBcs(T, data), + bcs: CoinMetadata.bcs, + fromJSONField: (field: any) => CoinMetadata.fromJSONField(T, field), + fromJSON: (json: Record) => CoinMetadata.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => CoinMetadata.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => CoinMetadata.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => CoinMetadata.fetch(client, T, id), + new: (fields: CoinMetadataFields>) => { + return new CoinMetadata([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return CoinMetadata.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(CoinMetadata.reified(T)); + } + static get p() { + return CoinMetadata.phantom; + } + + static get bcs() { + return bcs.struct("CoinMetadata", { + id: UID.bcs, + decimals: bcs.u8(), + name: String.bcs, + symbol: String1.bcs, + description: String.bcs, + icon_url: Option.bcs(Url.bcs), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): CoinMetadata> { + return CoinMetadata.reified(typeArg).new({ + id: decodeFromFields(UID.reified(), fields.id), + decimals: decodeFromFields("u8", fields.decimals), + name: decodeFromFields(String.reified(), fields.name), + symbol: decodeFromFields(String1.reified(), fields.symbol), + description: decodeFromFields(String.reified(), fields.description), + iconUrl: decodeFromFields(Option.reified(Url.reified()), fields.icon_url), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): CoinMetadata> { + if (!isCoinMetadata(item.type)) { + throw new Error("not a CoinMetadata type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return CoinMetadata.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + decimals: decodeFromFieldsWithTypes("u8", item.fields.decimals), + name: decodeFromFieldsWithTypes(String.reified(), item.fields.name), + symbol: decodeFromFieldsWithTypes(String1.reified(), item.fields.symbol), + description: decodeFromFieldsWithTypes(String.reified(), item.fields.description), + iconUrl: decodeFromFieldsWithTypes(Option.reified(Url.reified()), item.fields.icon_url), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): CoinMetadata> { + return CoinMetadata.fromFields(typeArg, CoinMetadata.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + decimals: this.decimals, + name: this.name, + symbol: this.symbol, + description: this.description, + iconUrl: fieldToJSON>(`${Option.$typeName}<${Url.$typeName}>`, this.iconUrl), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): CoinMetadata> { + return CoinMetadata.reified(typeArg).new({ + id: decodeFromJSONField(UID.reified(), field.id), + decimals: decodeFromJSONField("u8", field.decimals), + name: decodeFromJSONField(String.reified(), field.name), + symbol: decodeFromJSONField(String1.reified(), field.symbol), + description: decodeFromJSONField(String.reified(), field.description), + iconUrl: decodeFromJSONField(Option.reified(Url.reified()), field.iconUrl), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): CoinMetadata> { + if (json.$typeName !== CoinMetadata.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(CoinMetadata.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return CoinMetadata.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): CoinMetadata> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isCoinMetadata(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a CoinMetadata object`); + } + return CoinMetadata.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): CoinMetadata> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isCoinMetadata(data.bcs.type)) { + throw new Error(`object at is not a CoinMetadata object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return CoinMetadata.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return CoinMetadata.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching CoinMetadata object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isCoinMetadata(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a CoinMetadata object`); + } + + return CoinMetadata.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== CurrencyCreated =============================== */ + +export function isCurrencyCreated(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::coin::CurrencyCreated` + "<"); +} + +export interface CurrencyCreatedFields { + decimals: ToField<"u8">; +} + +export type CurrencyCreatedReified = Reified< + CurrencyCreated, + CurrencyCreatedFields +>; + +export class CurrencyCreated implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::coin::CurrencyCreated`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = CurrencyCreated.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = CurrencyCreated.$isPhantom; + + readonly decimals: ToField<"u8">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: CurrencyCreatedFields) { + this.$fullTypeName = composeSuiType(CurrencyCreated.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.decimals = fields.decimals; + } + + static reified>( + T: T + ): CurrencyCreatedReified> { + return { + typeName: CurrencyCreated.$typeName, + fullTypeName: composeSuiType(CurrencyCreated.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: CurrencyCreated.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => CurrencyCreated.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => CurrencyCreated.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => CurrencyCreated.fromBcs(T, data), + bcs: CurrencyCreated.bcs, + fromJSONField: (field: any) => CurrencyCreated.fromJSONField(T, field), + fromJSON: (json: Record) => CurrencyCreated.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => CurrencyCreated.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => CurrencyCreated.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => CurrencyCreated.fetch(client, T, id), + new: (fields: CurrencyCreatedFields>) => { + return new CurrencyCreated([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return CurrencyCreated.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(CurrencyCreated.reified(T)); + } + static get p() { + return CurrencyCreated.phantom; + } + + static get bcs() { + return bcs.struct("CurrencyCreated", { + decimals: bcs.u8(), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): CurrencyCreated> { + return CurrencyCreated.reified(typeArg).new({ + decimals: decodeFromFields("u8", fields.decimals), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): CurrencyCreated> { + if (!isCurrencyCreated(item.type)) { + throw new Error("not a CurrencyCreated type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return CurrencyCreated.reified(typeArg).new({ + decimals: decodeFromFieldsWithTypes("u8", item.fields.decimals), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): CurrencyCreated> { + return CurrencyCreated.fromFields(typeArg, CurrencyCreated.bcs.parse(data)); + } + + toJSONField() { + return { + decimals: this.decimals, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): CurrencyCreated> { + return CurrencyCreated.reified(typeArg).new({ + decimals: decodeFromJSONField("u8", field.decimals), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): CurrencyCreated> { + if (json.$typeName !== CurrencyCreated.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(CurrencyCreated.$typeName, extractType(typeArg)), json.$typeArgs, [ + typeArg, + ]); + + return CurrencyCreated.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): CurrencyCreated> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isCurrencyCreated(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a CurrencyCreated object`); + } + return CurrencyCreated.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): CurrencyCreated> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isCurrencyCreated(data.bcs.type)) { + throw new Error(`object at is not a CurrencyCreated object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return CurrencyCreated.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return CurrencyCreated.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching CurrencyCreated object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isCurrencyCreated(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a CurrencyCreated object`); + } + + return CurrencyCreated.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== DenyCap =============================== */ + +export function isDenyCap(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::coin::DenyCap` + "<"); +} + +export interface DenyCapFields { + id: ToField; +} + +export type DenyCapReified = Reified, DenyCapFields>; + +export class DenyCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::coin::DenyCap`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = DenyCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = DenyCap.$isPhantom; + + readonly id: ToField; + + private constructor(typeArgs: [PhantomToTypeStr], fields: DenyCapFields) { + this.$fullTypeName = composeSuiType(DenyCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified>(T: T): DenyCapReified> { + return { + typeName: DenyCap.$typeName, + fullTypeName: composeSuiType(DenyCap.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: DenyCap.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => DenyCap.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => DenyCap.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => DenyCap.fromBcs(T, data), + bcs: DenyCap.bcs, + fromJSONField: (field: any) => DenyCap.fromJSONField(T, field), + fromJSON: (json: Record) => DenyCap.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => DenyCap.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => DenyCap.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => DenyCap.fetch(client, T, id), + new: (fields: DenyCapFields>) => { + return new DenyCap([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return DenyCap.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(DenyCap.reified(T)); + } + static get p() { + return DenyCap.phantom; + } + + static get bcs() { + return bcs.struct("DenyCap", { + id: UID.bcs, + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): DenyCap> { + return DenyCap.reified(typeArg).new({ + id: decodeFromFields(UID.reified(), fields.id), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): DenyCap> { + if (!isDenyCap(item.type)) { + throw new Error("not a DenyCap type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return DenyCap.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): DenyCap> { + return DenyCap.fromFields(typeArg, DenyCap.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): DenyCap> { + return DenyCap.reified(typeArg).new({ + id: decodeFromJSONField(UID.reified(), field.id), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): DenyCap> { + if (json.$typeName !== DenyCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(DenyCap.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return DenyCap.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): DenyCap> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isDenyCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a DenyCap object`); + } + return DenyCap.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): DenyCap> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isDenyCap(data.bcs.type)) { + throw new Error(`object at is not a DenyCap object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return DenyCap.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return DenyCap.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching DenyCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isDenyCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a DenyCap object`); + } + + return DenyCap.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== DenyCapV2 =============================== */ + +export function isDenyCapV2(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::coin::DenyCapV2` + "<"); +} + +export interface DenyCapV2Fields { + id: ToField; + allowGlobalPause: ToField<"bool">; +} + +export type DenyCapV2Reified = Reified, DenyCapV2Fields>; + +export class DenyCapV2 implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::coin::DenyCapV2`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = DenyCapV2.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = DenyCapV2.$isPhantom; + + readonly id: ToField; + readonly allowGlobalPause: ToField<"bool">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: DenyCapV2Fields) { + this.$fullTypeName = composeSuiType(DenyCapV2.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.allowGlobalPause = fields.allowGlobalPause; + } + + static reified>(T: T): DenyCapV2Reified> { + return { + typeName: DenyCapV2.$typeName, + fullTypeName: composeSuiType(DenyCapV2.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: DenyCapV2.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => DenyCapV2.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => DenyCapV2.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => DenyCapV2.fromBcs(T, data), + bcs: DenyCapV2.bcs, + fromJSONField: (field: any) => DenyCapV2.fromJSONField(T, field), + fromJSON: (json: Record) => DenyCapV2.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => DenyCapV2.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => DenyCapV2.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => DenyCapV2.fetch(client, T, id), + new: (fields: DenyCapV2Fields>) => { + return new DenyCapV2([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return DenyCapV2.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(DenyCapV2.reified(T)); + } + static get p() { + return DenyCapV2.phantom; + } + + static get bcs() { + return bcs.struct("DenyCapV2", { + id: UID.bcs, + allow_global_pause: bcs.bool(), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): DenyCapV2> { + return DenyCapV2.reified(typeArg).new({ + id: decodeFromFields(UID.reified(), fields.id), + allowGlobalPause: decodeFromFields("bool", fields.allow_global_pause), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): DenyCapV2> { + if (!isDenyCapV2(item.type)) { + throw new Error("not a DenyCapV2 type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return DenyCapV2.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + allowGlobalPause: decodeFromFieldsWithTypes("bool", item.fields.allow_global_pause), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): DenyCapV2> { + return DenyCapV2.fromFields(typeArg, DenyCapV2.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + allowGlobalPause: this.allowGlobalPause, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): DenyCapV2> { + return DenyCapV2.reified(typeArg).new({ + id: decodeFromJSONField(UID.reified(), field.id), + allowGlobalPause: decodeFromJSONField("bool", field.allowGlobalPause), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): DenyCapV2> { + if (json.$typeName !== DenyCapV2.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(DenyCapV2.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return DenyCapV2.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): DenyCapV2> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isDenyCapV2(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a DenyCapV2 object`); + } + return DenyCapV2.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): DenyCapV2> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isDenyCapV2(data.bcs.type)) { + throw new Error(`object at is not a DenyCapV2 object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return DenyCapV2.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return DenyCapV2.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching DenyCapV2 object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isDenyCapV2(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a DenyCapV2 object`); + } + + return DenyCapV2.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== RegulatedCoinMetadata =============================== */ + +export function isRegulatedCoinMetadata(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::coin::RegulatedCoinMetadata` + "<"); +} + +export interface RegulatedCoinMetadataFields { + id: ToField; + coinMetadataObject: ToField; + denyCapObject: ToField; +} + +export type RegulatedCoinMetadataReified = Reified< + RegulatedCoinMetadata, + RegulatedCoinMetadataFields +>; + +export class RegulatedCoinMetadata implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::coin::RegulatedCoinMetadata`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = RegulatedCoinMetadata.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = RegulatedCoinMetadata.$isPhantom; + + readonly id: ToField; + readonly coinMetadataObject: ToField; + readonly denyCapObject: ToField; + + private constructor(typeArgs: [PhantomToTypeStr], fields: RegulatedCoinMetadataFields) { + this.$fullTypeName = composeSuiType(RegulatedCoinMetadata.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.coinMetadataObject = fields.coinMetadataObject; + this.denyCapObject = fields.denyCapObject; + } + + static reified>( + T: T + ): RegulatedCoinMetadataReified> { + return { + typeName: RegulatedCoinMetadata.$typeName, + fullTypeName: composeSuiType(RegulatedCoinMetadata.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: RegulatedCoinMetadata.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => RegulatedCoinMetadata.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => RegulatedCoinMetadata.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => RegulatedCoinMetadata.fromBcs(T, data), + bcs: RegulatedCoinMetadata.bcs, + fromJSONField: (field: any) => RegulatedCoinMetadata.fromJSONField(T, field), + fromJSON: (json: Record) => RegulatedCoinMetadata.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => RegulatedCoinMetadata.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => RegulatedCoinMetadata.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => RegulatedCoinMetadata.fetch(client, T, id), + new: (fields: RegulatedCoinMetadataFields>) => { + return new RegulatedCoinMetadata([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return RegulatedCoinMetadata.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(RegulatedCoinMetadata.reified(T)); + } + static get p() { + return RegulatedCoinMetadata.phantom; + } + + static get bcs() { + return bcs.struct("RegulatedCoinMetadata", { + id: UID.bcs, + coin_metadata_object: ID.bcs, + deny_cap_object: ID.bcs, + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): RegulatedCoinMetadata> { + return RegulatedCoinMetadata.reified(typeArg).new({ + id: decodeFromFields(UID.reified(), fields.id), + coinMetadataObject: decodeFromFields(ID.reified(), fields.coin_metadata_object), + denyCapObject: decodeFromFields(ID.reified(), fields.deny_cap_object), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): RegulatedCoinMetadata> { + if (!isRegulatedCoinMetadata(item.type)) { + throw new Error("not a RegulatedCoinMetadata type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return RegulatedCoinMetadata.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + coinMetadataObject: decodeFromFieldsWithTypes(ID.reified(), item.fields.coin_metadata_object), + denyCapObject: decodeFromFieldsWithTypes(ID.reified(), item.fields.deny_cap_object), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): RegulatedCoinMetadata> { + return RegulatedCoinMetadata.fromFields(typeArg, RegulatedCoinMetadata.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + coinMetadataObject: this.coinMetadataObject, + denyCapObject: this.denyCapObject, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): RegulatedCoinMetadata> { + return RegulatedCoinMetadata.reified(typeArg).new({ + id: decodeFromJSONField(UID.reified(), field.id), + coinMetadataObject: decodeFromJSONField(ID.reified(), field.coinMetadataObject), + denyCapObject: decodeFromJSONField(ID.reified(), field.denyCapObject), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): RegulatedCoinMetadata> { + if (json.$typeName !== RegulatedCoinMetadata.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(RegulatedCoinMetadata.$typeName, extractType(typeArg)), json.$typeArgs, [ + typeArg, + ]); + + return RegulatedCoinMetadata.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): RegulatedCoinMetadata> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isRegulatedCoinMetadata(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a RegulatedCoinMetadata object`); + } + return RegulatedCoinMetadata.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): RegulatedCoinMetadata> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isRegulatedCoinMetadata(data.bcs.type)) { + throw new Error(`object at is not a RegulatedCoinMetadata object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return RegulatedCoinMetadata.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return RegulatedCoinMetadata.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching RegulatedCoinMetadata object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isRegulatedCoinMetadata(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a RegulatedCoinMetadata object`); + } + + return RegulatedCoinMetadata.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== TreasuryCap =============================== */ + +export function isTreasuryCap(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::coin::TreasuryCap` + "<"); +} + +export interface TreasuryCapFields { + id: ToField; + totalSupply: ToField>; +} + +export type TreasuryCapReified = Reified, TreasuryCapFields>; + +export class TreasuryCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::coin::TreasuryCap`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = TreasuryCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = TreasuryCap.$isPhantom; + + readonly id: ToField; + readonly totalSupply: ToField>; + + private constructor(typeArgs: [PhantomToTypeStr], fields: TreasuryCapFields) { + this.$fullTypeName = composeSuiType(TreasuryCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.totalSupply = fields.totalSupply; + } + + static reified>(T: T): TreasuryCapReified> { + return { + typeName: TreasuryCap.$typeName, + fullTypeName: composeSuiType(TreasuryCap.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: TreasuryCap.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => TreasuryCap.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => TreasuryCap.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => TreasuryCap.fromBcs(T, data), + bcs: TreasuryCap.bcs, + fromJSONField: (field: any) => TreasuryCap.fromJSONField(T, field), + fromJSON: (json: Record) => TreasuryCap.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => TreasuryCap.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => TreasuryCap.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => TreasuryCap.fetch(client, T, id), + new: (fields: TreasuryCapFields>) => { + return new TreasuryCap([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return TreasuryCap.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(TreasuryCap.reified(T)); + } + static get p() { + return TreasuryCap.phantom; + } + + static get bcs() { + return bcs.struct("TreasuryCap", { + id: UID.bcs, + total_supply: Supply.bcs, + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): TreasuryCap> { + return TreasuryCap.reified(typeArg).new({ + id: decodeFromFields(UID.reified(), fields.id), + totalSupply: decodeFromFields(Supply.reified(typeArg), fields.total_supply), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): TreasuryCap> { + if (!isTreasuryCap(item.type)) { + throw new Error("not a TreasuryCap type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return TreasuryCap.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + totalSupply: decodeFromFieldsWithTypes(Supply.reified(typeArg), item.fields.total_supply), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): TreasuryCap> { + return TreasuryCap.fromFields(typeArg, TreasuryCap.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + totalSupply: this.totalSupply.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): TreasuryCap> { + return TreasuryCap.reified(typeArg).new({ + id: decodeFromJSONField(UID.reified(), field.id), + totalSupply: decodeFromJSONField(Supply.reified(typeArg), field.totalSupply), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): TreasuryCap> { + if (json.$typeName !== TreasuryCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(TreasuryCap.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return TreasuryCap.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): TreasuryCap> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTreasuryCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a TreasuryCap object`); + } + return TreasuryCap.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): TreasuryCap> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTreasuryCap(data.bcs.type)) { + throw new Error(`object at is not a TreasuryCap object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return TreasuryCap.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return TreasuryCap.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching TreasuryCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTreasuryCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a TreasuryCap object`); + } + + return TreasuryCap.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/sui/config/functions.ts b/src/services/models/sui/sui/config/functions.ts new file mode 100644 index 00000000..32b66f51 --- /dev/null +++ b/src/services/models/sui/sui/config/functions.ts @@ -0,0 +1,172 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj, pure } from "../../_framework/util"; +import { ID } from "../object/structs"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function new_(tx: Transaction, typeArg: string, cap: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::config::new`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, cap)], + }); +} + +export interface TransferArgs { + config: TransactionObjectInput; + owner: string | TransactionArgument; +} + +export function transfer(tx: Transaction, typeArg: string, args: TransferArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::config::transfer`, + typeArguments: [typeArg], + arguments: [obj(tx, args.config), pure(tx, args.owner, `address`)], + }); +} + +export interface ExistsWithTypeArgs { + config: TransactionObjectInput; + name: GenericArg; +} + +export function existsWithType(tx: Transaction, typeArgs: [string, string, string], args: ExistsWithTypeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::config::exists_with_type`, + typeArguments: typeArgs, + arguments: [obj(tx, args.config), generic(tx, `${typeArgs[1]}`, args.name)], + }); +} + +export interface AddForNextEpochArgs { + config: TransactionObjectInput; + cap: GenericArg; + name: GenericArg; + value: GenericArg; +} + +export function addForNextEpoch(tx: Transaction, typeArgs: [string, string, string], args: AddForNextEpochArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::config::add_for_next_epoch`, + typeArguments: typeArgs, + arguments: [ + obj(tx, args.config), + generic(tx, `${typeArgs[0]}`, args.cap), + generic(tx, `${typeArgs[1]}`, args.name), + generic(tx, `${typeArgs[2]}`, args.value), + ], + }); +} + +export interface BorrowForNextEpochMutArgs { + config: TransactionObjectInput; + cap: GenericArg; + name: GenericArg; +} + +export function borrowForNextEpochMut( + tx: Transaction, + typeArgs: [string, string, string], + args: BorrowForNextEpochMutArgs +) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::config::borrow_for_next_epoch_mut`, + typeArguments: typeArgs, + arguments: [ + obj(tx, args.config), + generic(tx, `${typeArgs[0]}`, args.cap), + generic(tx, `${typeArgs[1]}`, args.name), + ], + }); +} + +export interface ExistsWithTypeForNextEpochArgs { + config: TransactionObjectInput; + name: GenericArg; +} + +export function existsWithTypeForNextEpoch( + tx: Transaction, + typeArgs: [string, string, string], + args: ExistsWithTypeForNextEpochArgs +) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::config::exists_with_type_for_next_epoch`, + typeArguments: typeArgs, + arguments: [obj(tx, args.config), generic(tx, `${typeArgs[1]}`, args.name)], + }); +} + +export interface ReadSettingArgs { + config: string | TransactionArgument; + name: GenericArg; +} + +export function readSetting(tx: Transaction, typeArgs: [string, string], args: ReadSettingArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::config::read_setting`, + typeArguments: typeArgs, + arguments: [pure(tx, args.config, `${ID.$typeName}`), generic(tx, `${typeArgs[0]}`, args.name)], + }); +} + +export interface ReadSettingForNextEpochArgs { + config: TransactionObjectInput; + name: GenericArg; +} + +export function readSettingForNextEpoch( + tx: Transaction, + typeArgs: [string, string, string], + args: ReadSettingForNextEpochArgs +) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::config::read_setting_for_next_epoch`, + typeArguments: typeArgs, + arguments: [obj(tx, args.config), generic(tx, `${typeArgs[1]}`, args.name)], + }); +} + +export interface ReadSettingImplArgs { + config: string | TransactionArgument; + name: string | TransactionArgument; + currentEpoch: bigint | TransactionArgument; +} + +export function readSettingImpl( + tx: Transaction, + typeArgs: [string, string, string, string], + args: ReadSettingImplArgs +) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::config::read_setting_impl`, + typeArguments: typeArgs, + arguments: [pure(tx, args.config, `address`), pure(tx, args.name, `address`), pure(tx, args.currentEpoch, `u64`)], + }); +} + +export interface RemoveForNextEpochArgs { + config: TransactionObjectInput; + cap: GenericArg; + name: GenericArg; +} + +export function removeForNextEpoch(tx: Transaction, typeArgs: [string, string, string], args: RemoveForNextEpochArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::config::remove_for_next_epoch`, + typeArguments: typeArgs, + arguments: [ + obj(tx, args.config), + generic(tx, `${typeArgs[0]}`, args.cap), + generic(tx, `${typeArgs[1]}`, args.name), + ], + }); +} + +export function share(tx: Transaction, typeArg: string, config: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::config::share`, + typeArguments: [typeArg], + arguments: [obj(tx, config)], + }); +} diff --git a/src/services/models/sui/sui/config/structs.ts b/src/services/models/sui/sui/config/structs.ts new file mode 100644 index 00000000..70f98836 --- /dev/null +++ b/src/services/models/sui/sui/config/structs.ts @@ -0,0 +1,662 @@ +// @ts-nocheck +import { Option } from "../../_dependencies/source/0x1/option/structs"; +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeArgument, + ToTypeStr, + TypeArgument, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + fieldToJSON, + phantom, + toBcs, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { UID } from "../object/structs"; +import { BcsType, bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Config =============================== */ + +export function isConfig(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::config::Config` + "<"); +} + +export interface ConfigFields { + id: ToField; +} + +export type ConfigReified = Reified, ConfigFields>; + +export class Config implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::config::Config`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = Config.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = Config.$isPhantom; + + readonly id: ToField; + + private constructor(typeArgs: [PhantomToTypeStr], fields: ConfigFields) { + this.$fullTypeName = composeSuiType(Config.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified>( + WriteCap: WriteCap + ): ConfigReified> { + return { + typeName: Config.$typeName, + fullTypeName: composeSuiType(Config.$typeName, ...[extractType(WriteCap)]) as string, + typeArgs: [extractType(WriteCap)] as [PhantomToTypeStr>], + isPhantom: Config.$isPhantom, + reifiedTypeArgs: [WriteCap], + fromFields: (fields: Record) => Config.fromFields(WriteCap, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Config.fromFieldsWithTypes(WriteCap, item), + fromBcs: (data: Uint8Array) => Config.fromBcs(WriteCap, data), + bcs: Config.bcs, + fromJSONField: (field: any) => Config.fromJSONField(WriteCap, field), + fromJSON: (json: Record) => Config.fromJSON(WriteCap, json), + fromSuiParsedData: (content: SuiParsedData) => Config.fromSuiParsedData(WriteCap, content), + fromSuiObjectData: (content: SuiObjectData) => Config.fromSuiObjectData(WriteCap, content), + fetch: async (client: SuiClient, id: string) => Config.fetch(client, WriteCap, id), + new: (fields: ConfigFields>) => { + return new Config([extractType(WriteCap)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Config.reified; + } + + static phantom>( + WriteCap: WriteCap + ): PhantomReified>>> { + return phantom(Config.reified(WriteCap)); + } + static get p() { + return Config.phantom; + } + + static get bcs() { + return bcs.struct("Config", { + id: UID.bcs, + }); + } + + static fromFields>( + typeArg: WriteCap, + fields: Record + ): Config> { + return Config.reified(typeArg).new({ + id: decodeFromFields(UID.reified(), fields.id), + }); + } + + static fromFieldsWithTypes>( + typeArg: WriteCap, + item: FieldsWithTypes + ): Config> { + if (!isConfig(item.type)) { + throw new Error("not a Config type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Config.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + }); + } + + static fromBcs>( + typeArg: WriteCap, + data: Uint8Array + ): Config> { + return Config.fromFields(typeArg, Config.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: WriteCap, + field: any + ): Config> { + return Config.reified(typeArg).new({ + id: decodeFromJSONField(UID.reified(), field.id), + }); + } + + static fromJSON>( + typeArg: WriteCap, + json: Record + ): Config> { + if (json.$typeName !== Config.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Config.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Config.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: WriteCap, + content: SuiParsedData + ): Config> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isConfig(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Config object`); + } + return Config.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: WriteCap, + data: SuiObjectData + ): Config> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isConfig(data.bcs.type)) { + throw new Error(`object at is not a Config object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Config.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Config.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: WriteCap, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Config object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isConfig(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Config object`); + } + + return Config.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== Setting =============================== */ + +export function isSetting(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::config::Setting` + "<"); +} + +export interface SettingFields { + data: ToField>>; +} + +export type SettingReified = Reified, SettingFields>; + +export class Setting implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::config::Setting`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [false] as const; + + readonly $typeName = Setting.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [ToTypeStr]; + readonly $isPhantom = Setting.$isPhantom; + + readonly data: ToField>>; + + private constructor(typeArgs: [ToTypeStr], fields: SettingFields) { + this.$fullTypeName = composeSuiType(Setting.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.data = fields.data; + } + + static reified>(Value: Value): SettingReified> { + return { + typeName: Setting.$typeName, + fullTypeName: composeSuiType(Setting.$typeName, ...[extractType(Value)]) as string, + typeArgs: [extractType(Value)] as [ToTypeStr>], + isPhantom: Setting.$isPhantom, + reifiedTypeArgs: [Value], + fromFields: (fields: Record) => Setting.fromFields(Value, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Setting.fromFieldsWithTypes(Value, item), + fromBcs: (data: Uint8Array) => Setting.fromBcs(Value, data), + bcs: Setting.bcs(toBcs(Value)), + fromJSONField: (field: any) => Setting.fromJSONField(Value, field), + fromJSON: (json: Record) => Setting.fromJSON(Value, json), + fromSuiParsedData: (content: SuiParsedData) => Setting.fromSuiParsedData(Value, content), + fromSuiObjectData: (content: SuiObjectData) => Setting.fromSuiObjectData(Value, content), + fetch: async (client: SuiClient, id: string) => Setting.fetch(client, Value, id), + new: (fields: SettingFields>) => { + return new Setting([extractType(Value)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Setting.reified; + } + + static phantom>( + Value: Value + ): PhantomReified>>> { + return phantom(Setting.reified(Value)); + } + static get p() { + return Setting.phantom; + } + + static get bcs() { + return >(Value: Value) => + bcs.struct(`Setting<${Value.name}>`, { + data: Option.bcs(SettingData.bcs(Value)), + }); + } + + static fromFields>( + typeArg: Value, + fields: Record + ): Setting> { + return Setting.reified(typeArg).new({ + data: decodeFromFields(Option.reified(SettingData.reified(typeArg)), fields.data), + }); + } + + static fromFieldsWithTypes>( + typeArg: Value, + item: FieldsWithTypes + ): Setting> { + if (!isSetting(item.type)) { + throw new Error("not a Setting type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Setting.reified(typeArg).new({ + data: decodeFromFieldsWithTypes(Option.reified(SettingData.reified(typeArg)), item.fields.data), + }); + } + + static fromBcs>( + typeArg: Value, + data: Uint8Array + ): Setting> { + const typeArgs = [typeArg]; + + return Setting.fromFields(typeArg, Setting.bcs(toBcs(typeArgs[0])).parse(data)); + } + + toJSONField() { + return { + data: fieldToJSON>>( + `${Option.$typeName}<${SettingData.$typeName}<${this.$typeArgs[0]}>>`, + this.data + ), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: Value, + field: any + ): Setting> { + return Setting.reified(typeArg).new({ + data: decodeFromJSONField(Option.reified(SettingData.reified(typeArg)), field.data), + }); + } + + static fromJSON>( + typeArg: Value, + json: Record + ): Setting> { + if (json.$typeName !== Setting.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Setting.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Setting.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: Value, + content: SuiParsedData + ): Setting> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isSetting(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Setting object`); + } + return Setting.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: Value, + data: SuiObjectData + ): Setting> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isSetting(data.bcs.type)) { + throw new Error(`object at is not a Setting object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Setting.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Setting.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: Value, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Setting object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isSetting(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Setting object`); + } + + return Setting.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== SettingData =============================== */ + +export function isSettingData(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::config::SettingData` + "<"); +} + +export interface SettingDataFields { + newerValueEpoch: ToField<"u64">; + newerValue: ToField>; + olderValueOpt: ToField>; +} + +export type SettingDataReified = Reified, SettingDataFields>; + +export class SettingData implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::config::SettingData`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [false] as const; + + readonly $typeName = SettingData.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [ToTypeStr]; + readonly $isPhantom = SettingData.$isPhantom; + + readonly newerValueEpoch: ToField<"u64">; + readonly newerValue: ToField>; + readonly olderValueOpt: ToField>; + + private constructor(typeArgs: [ToTypeStr], fields: SettingDataFields) { + this.$fullTypeName = composeSuiType(SettingData.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.newerValueEpoch = fields.newerValueEpoch; + this.newerValue = fields.newerValue; + this.olderValueOpt = fields.olderValueOpt; + } + + static reified>(Value: Value): SettingDataReified> { + return { + typeName: SettingData.$typeName, + fullTypeName: composeSuiType(SettingData.$typeName, ...[extractType(Value)]) as string, + typeArgs: [extractType(Value)] as [ToTypeStr>], + isPhantom: SettingData.$isPhantom, + reifiedTypeArgs: [Value], + fromFields: (fields: Record) => SettingData.fromFields(Value, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => SettingData.fromFieldsWithTypes(Value, item), + fromBcs: (data: Uint8Array) => SettingData.fromBcs(Value, data), + bcs: SettingData.bcs(toBcs(Value)), + fromJSONField: (field: any) => SettingData.fromJSONField(Value, field), + fromJSON: (json: Record) => SettingData.fromJSON(Value, json), + fromSuiParsedData: (content: SuiParsedData) => SettingData.fromSuiParsedData(Value, content), + fromSuiObjectData: (content: SuiObjectData) => SettingData.fromSuiObjectData(Value, content), + fetch: async (client: SuiClient, id: string) => SettingData.fetch(client, Value, id), + new: (fields: SettingDataFields>) => { + return new SettingData([extractType(Value)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return SettingData.reified; + } + + static phantom>( + Value: Value + ): PhantomReified>>> { + return phantom(SettingData.reified(Value)); + } + static get p() { + return SettingData.phantom; + } + + static get bcs() { + return >(Value: Value) => + bcs.struct(`SettingData<${Value.name}>`, { + newer_value_epoch: bcs.u64(), + newer_value: Option.bcs(Value), + older_value_opt: Option.bcs(Value), + }); + } + + static fromFields>( + typeArg: Value, + fields: Record + ): SettingData> { + return SettingData.reified(typeArg).new({ + newerValueEpoch: decodeFromFields("u64", fields.newer_value_epoch), + newerValue: decodeFromFields(Option.reified(typeArg), fields.newer_value), + olderValueOpt: decodeFromFields(Option.reified(typeArg), fields.older_value_opt), + }); + } + + static fromFieldsWithTypes>( + typeArg: Value, + item: FieldsWithTypes + ): SettingData> { + if (!isSettingData(item.type)) { + throw new Error("not a SettingData type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return SettingData.reified(typeArg).new({ + newerValueEpoch: decodeFromFieldsWithTypes("u64", item.fields.newer_value_epoch), + newerValue: decodeFromFieldsWithTypes(Option.reified(typeArg), item.fields.newer_value), + olderValueOpt: decodeFromFieldsWithTypes(Option.reified(typeArg), item.fields.older_value_opt), + }); + } + + static fromBcs>( + typeArg: Value, + data: Uint8Array + ): SettingData> { + const typeArgs = [typeArg]; + + return SettingData.fromFields(typeArg, SettingData.bcs(toBcs(typeArgs[0])).parse(data)); + } + + toJSONField() { + return { + newerValueEpoch: this.newerValueEpoch.toString(), + newerValue: fieldToJSON>(`${Option.$typeName}<${this.$typeArgs[0]}>`, this.newerValue), + olderValueOpt: fieldToJSON>(`${Option.$typeName}<${this.$typeArgs[0]}>`, this.olderValueOpt), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: Value, + field: any + ): SettingData> { + return SettingData.reified(typeArg).new({ + newerValueEpoch: decodeFromJSONField("u64", field.newerValueEpoch), + newerValue: decodeFromJSONField(Option.reified(typeArg), field.newerValue), + olderValueOpt: decodeFromJSONField(Option.reified(typeArg), field.olderValueOpt), + }); + } + + static fromJSON>( + typeArg: Value, + json: Record + ): SettingData> { + if (json.$typeName !== SettingData.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(SettingData.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return SettingData.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: Value, + content: SuiParsedData + ): SettingData> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isSettingData(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a SettingData object`); + } + return SettingData.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: Value, + data: SuiObjectData + ): SettingData> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isSettingData(data.bcs.type)) { + throw new Error(`object at is not a SettingData object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return SettingData.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return SettingData.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: Value, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching SettingData object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isSettingData(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a SettingData object`); + } + + return SettingData.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/sui/deny-list/functions.ts b/src/services/models/sui/sui/deny-list/functions.ts new file mode 100644 index 00000000..c8b4c72d --- /dev/null +++ b/src/services/models/sui/sui/deny-list/functions.ts @@ -0,0 +1,307 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface AddPerTypeConfigArgs { + denyList: TransactionObjectInput; + perTypeIndex: bigint | TransactionArgument; + perTypeKey: Array | TransactionArgument; +} + +export function addPerTypeConfig(tx: Transaction, args: AddPerTypeConfigArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::add_per_type_config`, + arguments: [obj(tx, args.denyList), pure(tx, args.perTypeIndex, `u64`), pure(tx, args.perTypeKey, `vector`)], + }); +} + +export interface BorrowPerTypeConfigArgs { + denyList: TransactionObjectInput; + perTypeIndex: bigint | TransactionArgument; + perTypeKey: Array | TransactionArgument; +} + +export function borrowPerTypeConfig(tx: Transaction, args: BorrowPerTypeConfigArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::borrow_per_type_config`, + arguments: [obj(tx, args.denyList), pure(tx, args.perTypeIndex, `u64`), pure(tx, args.perTypeKey, `vector`)], + }); +} + +export interface BorrowPerTypeConfigMutArgs { + denyList: TransactionObjectInput; + perTypeIndex: bigint | TransactionArgument; + perTypeKey: Array | TransactionArgument; +} + +export function borrowPerTypeConfigMut(tx: Transaction, args: BorrowPerTypeConfigMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::borrow_per_type_config_mut`, + arguments: [obj(tx, args.denyList), pure(tx, args.perTypeIndex, `u64`), pure(tx, args.perTypeKey, `vector`)], + }); +} + +export function create(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::create`, + arguments: [], + }); +} + +export interface MigrateV1ToV2Args { + denyList: TransactionObjectInput; + perTypeIndex: bigint | TransactionArgument; + perTypeKey: Array | TransactionArgument; +} + +export function migrateV1ToV2(tx: Transaction, args: MigrateV1ToV2Args) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::migrate_v1_to_v2`, + arguments: [obj(tx, args.denyList), pure(tx, args.perTypeIndex, `u64`), pure(tx, args.perTypeKey, `vector`)], + }); +} + +export interface PerTypeExistsArgs { + denyList: TransactionObjectInput; + perTypeIndex: bigint | TransactionArgument; + perTypeKey: Array | TransactionArgument; +} + +export function perTypeExists(tx: Transaction, args: PerTypeExistsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::per_type_exists`, + arguments: [obj(tx, args.denyList), pure(tx, args.perTypeIndex, `u64`), pure(tx, args.perTypeKey, `vector`)], + }); +} + +export function perTypeList(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::per_type_list`, + arguments: [], + }); +} + +export interface V1AddArgs { + denyList: TransactionObjectInput; + perTypeIndex: bigint | TransactionArgument; + type: Array | TransactionArgument; + addr: string | TransactionArgument; +} + +export function v1Add(tx: Transaction, args: V1AddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::v1_add`, + arguments: [ + obj(tx, args.denyList), + pure(tx, args.perTypeIndex, `u64`), + pure(tx, args.type, `vector`), + pure(tx, args.addr, `address`), + ], + }); +} + +export interface V1ContainsArgs { + denyList: TransactionObjectInput; + perTypeIndex: bigint | TransactionArgument; + type: Array | TransactionArgument; + addr: string | TransactionArgument; +} + +export function v1Contains(tx: Transaction, args: V1ContainsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::v1_contains`, + arguments: [ + obj(tx, args.denyList), + pure(tx, args.perTypeIndex, `u64`), + pure(tx, args.type, `vector`), + pure(tx, args.addr, `address`), + ], + }); +} + +export interface V1PerTypeListAddArgs { + list: TransactionObjectInput; + type: Array | TransactionArgument; + addr: string | TransactionArgument; +} + +export function v1PerTypeListAdd(tx: Transaction, args: V1PerTypeListAddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::v1_per_type_list_add`, + arguments: [obj(tx, args.list), pure(tx, args.type, `vector`), pure(tx, args.addr, `address`)], + }); +} + +export interface V1PerTypeListContainsArgs { + list: TransactionObjectInput; + type: Array | TransactionArgument; + addr: string | TransactionArgument; +} + +export function v1PerTypeListContains(tx: Transaction, args: V1PerTypeListContainsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::v1_per_type_list_contains`, + arguments: [obj(tx, args.list), pure(tx, args.type, `vector`), pure(tx, args.addr, `address`)], + }); +} + +export interface V1PerTypeListRemoveArgs { + list: TransactionObjectInput; + type: Array | TransactionArgument; + addr: string | TransactionArgument; +} + +export function v1PerTypeListRemove(tx: Transaction, args: V1PerTypeListRemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::v1_per_type_list_remove`, + arguments: [obj(tx, args.list), pure(tx, args.type, `vector`), pure(tx, args.addr, `address`)], + }); +} + +export interface V1RemoveArgs { + denyList: TransactionObjectInput; + perTypeIndex: bigint | TransactionArgument; + type: Array | TransactionArgument; + addr: string | TransactionArgument; +} + +export function v1Remove(tx: Transaction, args: V1RemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::v1_remove`, + arguments: [ + obj(tx, args.denyList), + pure(tx, args.perTypeIndex, `u64`), + pure(tx, args.type, `vector`), + pure(tx, args.addr, `address`), + ], + }); +} + +export interface V2AddArgs { + denyList: TransactionObjectInput; + perTypeIndex: bigint | TransactionArgument; + perTypeKey: Array | TransactionArgument; + addr: string | TransactionArgument; +} + +export function v2Add(tx: Transaction, args: V2AddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::v2_add`, + arguments: [ + obj(tx, args.denyList), + pure(tx, args.perTypeIndex, `u64`), + pure(tx, args.perTypeKey, `vector`), + pure(tx, args.addr, `address`), + ], + }); +} + +export interface V2ContainsCurrentEpochArgs { + denyList: TransactionObjectInput; + perTypeIndex: bigint | TransactionArgument; + perTypeKey: Array | TransactionArgument; + addr: string | TransactionArgument; +} + +export function v2ContainsCurrentEpoch(tx: Transaction, args: V2ContainsCurrentEpochArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::v2_contains_current_epoch`, + arguments: [ + obj(tx, args.denyList), + pure(tx, args.perTypeIndex, `u64`), + pure(tx, args.perTypeKey, `vector`), + pure(tx, args.addr, `address`), + ], + }); +} + +export interface V2ContainsNextEpochArgs { + denyList: TransactionObjectInput; + perTypeIndex: bigint | TransactionArgument; + perTypeKey: Array | TransactionArgument; + addr: string | TransactionArgument; +} + +export function v2ContainsNextEpoch(tx: Transaction, args: V2ContainsNextEpochArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::v2_contains_next_epoch`, + arguments: [ + obj(tx, args.denyList), + pure(tx, args.perTypeIndex, `u64`), + pure(tx, args.perTypeKey, `vector`), + pure(tx, args.addr, `address`), + ], + }); +} + +export interface V2DisableGlobalPauseArgs { + denyList: TransactionObjectInput; + perTypeIndex: bigint | TransactionArgument; + perTypeKey: Array | TransactionArgument; +} + +export function v2DisableGlobalPause(tx: Transaction, args: V2DisableGlobalPauseArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::v2_disable_global_pause`, + arguments: [obj(tx, args.denyList), pure(tx, args.perTypeIndex, `u64`), pure(tx, args.perTypeKey, `vector`)], + }); +} + +export interface V2EnableGlobalPauseArgs { + denyList: TransactionObjectInput; + perTypeIndex: bigint | TransactionArgument; + perTypeKey: Array | TransactionArgument; +} + +export function v2EnableGlobalPause(tx: Transaction, args: V2EnableGlobalPauseArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::v2_enable_global_pause`, + arguments: [obj(tx, args.denyList), pure(tx, args.perTypeIndex, `u64`), pure(tx, args.perTypeKey, `vector`)], + }); +} + +export interface V2IsGlobalPauseEnabledCurrentEpochArgs { + denyList: TransactionObjectInput; + perTypeIndex: bigint | TransactionArgument; + perTypeKey: Array | TransactionArgument; +} + +export function v2IsGlobalPauseEnabledCurrentEpoch(tx: Transaction, args: V2IsGlobalPauseEnabledCurrentEpochArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::v2_is_global_pause_enabled_current_epoch`, + arguments: [obj(tx, args.denyList), pure(tx, args.perTypeIndex, `u64`), pure(tx, args.perTypeKey, `vector`)], + }); +} + +export interface V2IsGlobalPauseEnabledNextEpochArgs { + denyList: TransactionObjectInput; + perTypeIndex: bigint | TransactionArgument; + perTypeKey: Array | TransactionArgument; +} + +export function v2IsGlobalPauseEnabledNextEpoch(tx: Transaction, args: V2IsGlobalPauseEnabledNextEpochArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::v2_is_global_pause_enabled_next_epoch`, + arguments: [obj(tx, args.denyList), pure(tx, args.perTypeIndex, `u64`), pure(tx, args.perTypeKey, `vector`)], + }); +} + +export interface V2RemoveArgs { + denyList: TransactionObjectInput; + perTypeIndex: bigint | TransactionArgument; + perTypeKey: Array | TransactionArgument; + addr: string | TransactionArgument; +} + +export function v2Remove(tx: Transaction, args: V2RemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::deny_list::v2_remove`, + arguments: [ + obj(tx, args.denyList), + pure(tx, args.perTypeIndex, `u64`), + pure(tx, args.perTypeKey, `vector`), + pure(tx, args.addr, `address`), + ], + }); +} diff --git a/src/services/models/sui/sui/deny-list/structs.ts b/src/services/models/sui/sui/deny-list/structs.ts new file mode 100644 index 00000000..338fe2a3 --- /dev/null +++ b/src/services/models/sui/sui/deny-list/structs.ts @@ -0,0 +1,1227 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, + ToTypeStr as ToPhantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { Vector } from "../../_framework/vector"; +import { Bag } from "../bag/structs"; +import { PKG_V26 } from "../index"; +import { ID, UID } from "../object/structs"; +import { Table } from "../table/structs"; +import { VecSet } from "../vec-set/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64, fromHEX, toHEX } from "@mysten/sui/utils"; + +/* ============================== AddressKey =============================== */ + +export function isAddressKey(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::deny_list::AddressKey`; +} + +export interface AddressKeyFields { + pos0: ToField<"address">; +} + +export type AddressKeyReified = Reified; + +export class AddressKey implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::deny_list::AddressKey`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = AddressKey.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = AddressKey.$isPhantom; + + readonly pos0: ToField<"address">; + + private constructor(typeArgs: [], fields: AddressKeyFields) { + this.$fullTypeName = composeSuiType(AddressKey.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.pos0 = fields.pos0; + } + + static reified(): AddressKeyReified { + return { + typeName: AddressKey.$typeName, + fullTypeName: composeSuiType(AddressKey.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: AddressKey.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => AddressKey.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => AddressKey.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => AddressKey.fromBcs(data), + bcs: AddressKey.bcs, + fromJSONField: (field: any) => AddressKey.fromJSONField(field), + fromJSON: (json: Record) => AddressKey.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => AddressKey.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => AddressKey.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => AddressKey.fetch(client, id), + new: (fields: AddressKeyFields) => { + return new AddressKey([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return AddressKey.reified(); + } + + static phantom(): PhantomReified> { + return phantom(AddressKey.reified()); + } + static get p() { + return AddressKey.phantom(); + } + + static get bcs() { + return bcs.struct("AddressKey", { + pos0: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + }); + } + + static fromFields(fields: Record): AddressKey { + return AddressKey.reified().new({ + pos0: decodeFromFields("address", fields.pos0), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): AddressKey { + if (!isAddressKey(item.type)) { + throw new Error("not a AddressKey type"); + } + + return AddressKey.reified().new({ + pos0: decodeFromFieldsWithTypes("address", item.fields.pos0), + }); + } + + static fromBcs(data: Uint8Array): AddressKey { + return AddressKey.fromFields(AddressKey.bcs.parse(data)); + } + + toJSONField() { + return { + pos0: this.pos0, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): AddressKey { + return AddressKey.reified().new({ + pos0: decodeFromJSONField("address", field.pos0), + }); + } + + static fromJSON(json: Record): AddressKey { + if (json.$typeName !== AddressKey.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return AddressKey.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): AddressKey { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isAddressKey(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a AddressKey object`); + } + return AddressKey.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): AddressKey { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isAddressKey(data.bcs.type)) { + throw new Error(`object at is not a AddressKey object`); + } + + return AddressKey.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return AddressKey.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching AddressKey object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isAddressKey(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a AddressKey object`); + } + + return AddressKey.fromSuiObjectData(res.data); + } +} + +/* ============================== ConfigKey =============================== */ + +export function isConfigKey(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::deny_list::ConfigKey`; +} + +export interface ConfigKeyFields { + perTypeIndex: ToField<"u64">; + perTypeKey: ToField>; +} + +export type ConfigKeyReified = Reified; + +export class ConfigKey implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::deny_list::ConfigKey`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = ConfigKey.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = ConfigKey.$isPhantom; + + readonly perTypeIndex: ToField<"u64">; + readonly perTypeKey: ToField>; + + private constructor(typeArgs: [], fields: ConfigKeyFields) { + this.$fullTypeName = composeSuiType(ConfigKey.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.perTypeIndex = fields.perTypeIndex; + this.perTypeKey = fields.perTypeKey; + } + + static reified(): ConfigKeyReified { + return { + typeName: ConfigKey.$typeName, + fullTypeName: composeSuiType(ConfigKey.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: ConfigKey.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => ConfigKey.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => ConfigKey.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => ConfigKey.fromBcs(data), + bcs: ConfigKey.bcs, + fromJSONField: (field: any) => ConfigKey.fromJSONField(field), + fromJSON: (json: Record) => ConfigKey.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => ConfigKey.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => ConfigKey.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => ConfigKey.fetch(client, id), + new: (fields: ConfigKeyFields) => { + return new ConfigKey([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return ConfigKey.reified(); + } + + static phantom(): PhantomReified> { + return phantom(ConfigKey.reified()); + } + static get p() { + return ConfigKey.phantom(); + } + + static get bcs() { + return bcs.struct("ConfigKey", { + per_type_index: bcs.u64(), + per_type_key: bcs.vector(bcs.u8()), + }); + } + + static fromFields(fields: Record): ConfigKey { + return ConfigKey.reified().new({ + perTypeIndex: decodeFromFields("u64", fields.per_type_index), + perTypeKey: decodeFromFields(reified.vector("u8"), fields.per_type_key), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): ConfigKey { + if (!isConfigKey(item.type)) { + throw new Error("not a ConfigKey type"); + } + + return ConfigKey.reified().new({ + perTypeIndex: decodeFromFieldsWithTypes("u64", item.fields.per_type_index), + perTypeKey: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.per_type_key), + }); + } + + static fromBcs(data: Uint8Array): ConfigKey { + return ConfigKey.fromFields(ConfigKey.bcs.parse(data)); + } + + toJSONField() { + return { + perTypeIndex: this.perTypeIndex.toString(), + perTypeKey: fieldToJSON>(`vector`, this.perTypeKey), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): ConfigKey { + return ConfigKey.reified().new({ + perTypeIndex: decodeFromJSONField("u64", field.perTypeIndex), + perTypeKey: decodeFromJSONField(reified.vector("u8"), field.perTypeKey), + }); + } + + static fromJSON(json: Record): ConfigKey { + if (json.$typeName !== ConfigKey.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return ConfigKey.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): ConfigKey { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isConfigKey(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a ConfigKey object`); + } + return ConfigKey.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): ConfigKey { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isConfigKey(data.bcs.type)) { + throw new Error(`object at is not a ConfigKey object`); + } + + return ConfigKey.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return ConfigKey.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching ConfigKey object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isConfigKey(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a ConfigKey object`); + } + + return ConfigKey.fromSuiObjectData(res.data); + } +} + +/* ============================== ConfigWriteCap =============================== */ + +export function isConfigWriteCap(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::deny_list::ConfigWriteCap`; +} + +export interface ConfigWriteCapFields { + dummyField: ToField<"bool">; +} + +export type ConfigWriteCapReified = Reified; + +export class ConfigWriteCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::deny_list::ConfigWriteCap`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = ConfigWriteCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = ConfigWriteCap.$isPhantom; + + readonly dummyField: ToField<"bool">; + + private constructor(typeArgs: [], fields: ConfigWriteCapFields) { + this.$fullTypeName = composeSuiType(ConfigWriteCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.dummyField = fields.dummyField; + } + + static reified(): ConfigWriteCapReified { + return { + typeName: ConfigWriteCap.$typeName, + fullTypeName: composeSuiType(ConfigWriteCap.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: ConfigWriteCap.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => ConfigWriteCap.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => ConfigWriteCap.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => ConfigWriteCap.fromBcs(data), + bcs: ConfigWriteCap.bcs, + fromJSONField: (field: any) => ConfigWriteCap.fromJSONField(field), + fromJSON: (json: Record) => ConfigWriteCap.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => ConfigWriteCap.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => ConfigWriteCap.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => ConfigWriteCap.fetch(client, id), + new: (fields: ConfigWriteCapFields) => { + return new ConfigWriteCap([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return ConfigWriteCap.reified(); + } + + static phantom(): PhantomReified> { + return phantom(ConfigWriteCap.reified()); + } + static get p() { + return ConfigWriteCap.phantom(); + } + + static get bcs() { + return bcs.struct("ConfigWriteCap", { + dummy_field: bcs.bool(), + }); + } + + static fromFields(fields: Record): ConfigWriteCap { + return ConfigWriteCap.reified().new({ + dummyField: decodeFromFields("bool", fields.dummy_field), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): ConfigWriteCap { + if (!isConfigWriteCap(item.type)) { + throw new Error("not a ConfigWriteCap type"); + } + + return ConfigWriteCap.reified().new({ + dummyField: decodeFromFieldsWithTypes("bool", item.fields.dummy_field), + }); + } + + static fromBcs(data: Uint8Array): ConfigWriteCap { + return ConfigWriteCap.fromFields(ConfigWriteCap.bcs.parse(data)); + } + + toJSONField() { + return { + dummyField: this.dummyField, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): ConfigWriteCap { + return ConfigWriteCap.reified().new({ + dummyField: decodeFromJSONField("bool", field.dummyField), + }); + } + + static fromJSON(json: Record): ConfigWriteCap { + if (json.$typeName !== ConfigWriteCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return ConfigWriteCap.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): ConfigWriteCap { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isConfigWriteCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a ConfigWriteCap object`); + } + return ConfigWriteCap.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): ConfigWriteCap { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isConfigWriteCap(data.bcs.type)) { + throw new Error(`object at is not a ConfigWriteCap object`); + } + + return ConfigWriteCap.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return ConfigWriteCap.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching ConfigWriteCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isConfigWriteCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a ConfigWriteCap object`); + } + + return ConfigWriteCap.fromSuiObjectData(res.data); + } +} + +/* ============================== DenyList =============================== */ + +export function isDenyList(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::deny_list::DenyList`; +} + +export interface DenyListFields { + id: ToField; + lists: ToField; +} + +export type DenyListReified = Reified; + +export class DenyList implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::deny_list::DenyList`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = DenyList.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = DenyList.$isPhantom; + + readonly id: ToField; + readonly lists: ToField; + + private constructor(typeArgs: [], fields: DenyListFields) { + this.$fullTypeName = composeSuiType(DenyList.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.lists = fields.lists; + } + + static reified(): DenyListReified { + return { + typeName: DenyList.$typeName, + fullTypeName: composeSuiType(DenyList.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: DenyList.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => DenyList.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => DenyList.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => DenyList.fromBcs(data), + bcs: DenyList.bcs, + fromJSONField: (field: any) => DenyList.fromJSONField(field), + fromJSON: (json: Record) => DenyList.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => DenyList.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => DenyList.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => DenyList.fetch(client, id), + new: (fields: DenyListFields) => { + return new DenyList([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return DenyList.reified(); + } + + static phantom(): PhantomReified> { + return phantom(DenyList.reified()); + } + static get p() { + return DenyList.phantom(); + } + + static get bcs() { + return bcs.struct("DenyList", { + id: UID.bcs, + lists: Bag.bcs, + }); + } + + static fromFields(fields: Record): DenyList { + return DenyList.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + lists: decodeFromFields(Bag.reified(), fields.lists), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): DenyList { + if (!isDenyList(item.type)) { + throw new Error("not a DenyList type"); + } + + return DenyList.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + lists: decodeFromFieldsWithTypes(Bag.reified(), item.fields.lists), + }); + } + + static fromBcs(data: Uint8Array): DenyList { + return DenyList.fromFields(DenyList.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + lists: this.lists.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): DenyList { + return DenyList.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + lists: decodeFromJSONField(Bag.reified(), field.lists), + }); + } + + static fromJSON(json: Record): DenyList { + if (json.$typeName !== DenyList.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return DenyList.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): DenyList { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isDenyList(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a DenyList object`); + } + return DenyList.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): DenyList { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isDenyList(data.bcs.type)) { + throw new Error(`object at is not a DenyList object`); + } + + return DenyList.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return DenyList.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching DenyList object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isDenyList(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a DenyList object`); + } + + return DenyList.fromSuiObjectData(res.data); + } +} + +/* ============================== GlobalPauseKey =============================== */ + +export function isGlobalPauseKey(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::deny_list::GlobalPauseKey`; +} + +export interface GlobalPauseKeyFields { + dummyField: ToField<"bool">; +} + +export type GlobalPauseKeyReified = Reified; + +export class GlobalPauseKey implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::deny_list::GlobalPauseKey`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = GlobalPauseKey.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = GlobalPauseKey.$isPhantom; + + readonly dummyField: ToField<"bool">; + + private constructor(typeArgs: [], fields: GlobalPauseKeyFields) { + this.$fullTypeName = composeSuiType(GlobalPauseKey.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.dummyField = fields.dummyField; + } + + static reified(): GlobalPauseKeyReified { + return { + typeName: GlobalPauseKey.$typeName, + fullTypeName: composeSuiType(GlobalPauseKey.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: GlobalPauseKey.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => GlobalPauseKey.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => GlobalPauseKey.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => GlobalPauseKey.fromBcs(data), + bcs: GlobalPauseKey.bcs, + fromJSONField: (field: any) => GlobalPauseKey.fromJSONField(field), + fromJSON: (json: Record) => GlobalPauseKey.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => GlobalPauseKey.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => GlobalPauseKey.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => GlobalPauseKey.fetch(client, id), + new: (fields: GlobalPauseKeyFields) => { + return new GlobalPauseKey([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return GlobalPauseKey.reified(); + } + + static phantom(): PhantomReified> { + return phantom(GlobalPauseKey.reified()); + } + static get p() { + return GlobalPauseKey.phantom(); + } + + static get bcs() { + return bcs.struct("GlobalPauseKey", { + dummy_field: bcs.bool(), + }); + } + + static fromFields(fields: Record): GlobalPauseKey { + return GlobalPauseKey.reified().new({ + dummyField: decodeFromFields("bool", fields.dummy_field), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): GlobalPauseKey { + if (!isGlobalPauseKey(item.type)) { + throw new Error("not a GlobalPauseKey type"); + } + + return GlobalPauseKey.reified().new({ + dummyField: decodeFromFieldsWithTypes("bool", item.fields.dummy_field), + }); + } + + static fromBcs(data: Uint8Array): GlobalPauseKey { + return GlobalPauseKey.fromFields(GlobalPauseKey.bcs.parse(data)); + } + + toJSONField() { + return { + dummyField: this.dummyField, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): GlobalPauseKey { + return GlobalPauseKey.reified().new({ + dummyField: decodeFromJSONField("bool", field.dummyField), + }); + } + + static fromJSON(json: Record): GlobalPauseKey { + if (json.$typeName !== GlobalPauseKey.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return GlobalPauseKey.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): GlobalPauseKey { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isGlobalPauseKey(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a GlobalPauseKey object`); + } + return GlobalPauseKey.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): GlobalPauseKey { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isGlobalPauseKey(data.bcs.type)) { + throw new Error(`object at is not a GlobalPauseKey object`); + } + + return GlobalPauseKey.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return GlobalPauseKey.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching GlobalPauseKey object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isGlobalPauseKey(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a GlobalPauseKey object`); + } + + return GlobalPauseKey.fromSuiObjectData(res.data); + } +} + +/* ============================== PerTypeConfigCreated =============================== */ + +export function isPerTypeConfigCreated(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::deny_list::PerTypeConfigCreated`; +} + +export interface PerTypeConfigCreatedFields { + key: ToField; + configId: ToField; +} + +export type PerTypeConfigCreatedReified = Reified; + +export class PerTypeConfigCreated implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::deny_list::PerTypeConfigCreated`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = PerTypeConfigCreated.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = PerTypeConfigCreated.$isPhantom; + + readonly key: ToField; + readonly configId: ToField; + + private constructor(typeArgs: [], fields: PerTypeConfigCreatedFields) { + this.$fullTypeName = composeSuiType(PerTypeConfigCreated.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.key = fields.key; + this.configId = fields.configId; + } + + static reified(): PerTypeConfigCreatedReified { + return { + typeName: PerTypeConfigCreated.$typeName, + fullTypeName: composeSuiType(PerTypeConfigCreated.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: PerTypeConfigCreated.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => PerTypeConfigCreated.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => PerTypeConfigCreated.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => PerTypeConfigCreated.fromBcs(data), + bcs: PerTypeConfigCreated.bcs, + fromJSONField: (field: any) => PerTypeConfigCreated.fromJSONField(field), + fromJSON: (json: Record) => PerTypeConfigCreated.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => PerTypeConfigCreated.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => PerTypeConfigCreated.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => PerTypeConfigCreated.fetch(client, id), + new: (fields: PerTypeConfigCreatedFields) => { + return new PerTypeConfigCreated([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return PerTypeConfigCreated.reified(); + } + + static phantom(): PhantomReified> { + return phantom(PerTypeConfigCreated.reified()); + } + static get p() { + return PerTypeConfigCreated.phantom(); + } + + static get bcs() { + return bcs.struct("PerTypeConfigCreated", { + key: ConfigKey.bcs, + config_id: ID.bcs, + }); + } + + static fromFields(fields: Record): PerTypeConfigCreated { + return PerTypeConfigCreated.reified().new({ + key: decodeFromFields(ConfigKey.reified(), fields.key), + configId: decodeFromFields(ID.reified(), fields.config_id), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): PerTypeConfigCreated { + if (!isPerTypeConfigCreated(item.type)) { + throw new Error("not a PerTypeConfigCreated type"); + } + + return PerTypeConfigCreated.reified().new({ + key: decodeFromFieldsWithTypes(ConfigKey.reified(), item.fields.key), + configId: decodeFromFieldsWithTypes(ID.reified(), item.fields.config_id), + }); + } + + static fromBcs(data: Uint8Array): PerTypeConfigCreated { + return PerTypeConfigCreated.fromFields(PerTypeConfigCreated.bcs.parse(data)); + } + + toJSONField() { + return { + key: this.key.toJSONField(), + configId: this.configId, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): PerTypeConfigCreated { + return PerTypeConfigCreated.reified().new({ + key: decodeFromJSONField(ConfigKey.reified(), field.key), + configId: decodeFromJSONField(ID.reified(), field.configId), + }); + } + + static fromJSON(json: Record): PerTypeConfigCreated { + if (json.$typeName !== PerTypeConfigCreated.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return PerTypeConfigCreated.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): PerTypeConfigCreated { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isPerTypeConfigCreated(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a PerTypeConfigCreated object`); + } + return PerTypeConfigCreated.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): PerTypeConfigCreated { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isPerTypeConfigCreated(data.bcs.type)) { + throw new Error(`object at is not a PerTypeConfigCreated object`); + } + + return PerTypeConfigCreated.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return PerTypeConfigCreated.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching PerTypeConfigCreated object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isPerTypeConfigCreated(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a PerTypeConfigCreated object`); + } + + return PerTypeConfigCreated.fromSuiObjectData(res.data); + } +} + +/* ============================== PerTypeList =============================== */ + +export function isPerTypeList(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::deny_list::PerTypeList`; +} + +export interface PerTypeListFields { + id: ToField; + deniedCount: ToField>; + deniedAddresses: ToField>, ToPhantom>>>; +} + +export type PerTypeListReified = Reified; + +export class PerTypeList implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::deny_list::PerTypeList`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = PerTypeList.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = PerTypeList.$isPhantom; + + readonly id: ToField; + readonly deniedCount: ToField>; + readonly deniedAddresses: ToField>, ToPhantom>>>; + + private constructor(typeArgs: [], fields: PerTypeListFields) { + this.$fullTypeName = composeSuiType(PerTypeList.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.deniedCount = fields.deniedCount; + this.deniedAddresses = fields.deniedAddresses; + } + + static reified(): PerTypeListReified { + return { + typeName: PerTypeList.$typeName, + fullTypeName: composeSuiType(PerTypeList.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: PerTypeList.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => PerTypeList.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => PerTypeList.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => PerTypeList.fromBcs(data), + bcs: PerTypeList.bcs, + fromJSONField: (field: any) => PerTypeList.fromJSONField(field), + fromJSON: (json: Record) => PerTypeList.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => PerTypeList.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => PerTypeList.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => PerTypeList.fetch(client, id), + new: (fields: PerTypeListFields) => { + return new PerTypeList([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return PerTypeList.reified(); + } + + static phantom(): PhantomReified> { + return phantom(PerTypeList.reified()); + } + static get p() { + return PerTypeList.phantom(); + } + + static get bcs() { + return bcs.struct("PerTypeList", { + id: UID.bcs, + denied_count: Table.bcs, + denied_addresses: Table.bcs, + }); + } + + static fromFields(fields: Record): PerTypeList { + return PerTypeList.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + deniedCount: decodeFromFields( + Table.reified(reified.phantom("address"), reified.phantom("u64")), + fields.denied_count + ), + deniedAddresses: decodeFromFields( + Table.reified(reified.phantom(reified.vector("u8")), reified.phantom(VecSet.reified("address"))), + fields.denied_addresses + ), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): PerTypeList { + if (!isPerTypeList(item.type)) { + throw new Error("not a PerTypeList type"); + } + + return PerTypeList.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + deniedCount: decodeFromFieldsWithTypes( + Table.reified(reified.phantom("address"), reified.phantom("u64")), + item.fields.denied_count + ), + deniedAddresses: decodeFromFieldsWithTypes( + Table.reified(reified.phantom(reified.vector("u8")), reified.phantom(VecSet.reified("address"))), + item.fields.denied_addresses + ), + }); + } + + static fromBcs(data: Uint8Array): PerTypeList { + return PerTypeList.fromFields(PerTypeList.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + deniedCount: this.deniedCount.toJSONField(), + deniedAddresses: this.deniedAddresses.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): PerTypeList { + return PerTypeList.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + deniedCount: decodeFromJSONField( + Table.reified(reified.phantom("address"), reified.phantom("u64")), + field.deniedCount + ), + deniedAddresses: decodeFromJSONField( + Table.reified(reified.phantom(reified.vector("u8")), reified.phantom(VecSet.reified("address"))), + field.deniedAddresses + ), + }); + } + + static fromJSON(json: Record): PerTypeList { + if (json.$typeName !== PerTypeList.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return PerTypeList.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): PerTypeList { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isPerTypeList(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a PerTypeList object`); + } + return PerTypeList.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): PerTypeList { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isPerTypeList(data.bcs.type)) { + throw new Error(`object at is not a PerTypeList object`); + } + + return PerTypeList.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return PerTypeList.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching PerTypeList object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isPerTypeList(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a PerTypeList object`); + } + + return PerTypeList.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/sui/display/functions.ts b/src/services/models/sui/sui/display/functions.ts new file mode 100644 index 00000000..95a8f24b --- /dev/null +++ b/src/services/models/sui/sui/display/functions.ts @@ -0,0 +1,164 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { String } from "../../_dependencies/source/0x1/string/structs"; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface AddArgs { + self: TransactionObjectInput; + name: string | TransactionArgument; + value: string | TransactionArgument; +} + +export function add(tx: Transaction, typeArg: string, args: AddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::display::add`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.self), + pure(tx, args.name, `${String.$typeName}`), + pure(tx, args.value, `${String.$typeName}`), + ], + }); +} + +export interface RemoveArgs { + self: TransactionObjectInput; + name: string | TransactionArgument; +} + +export function remove(tx: Transaction, typeArg: string, args: RemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::display::remove`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), pure(tx, args.name, `${String.$typeName}`)], + }); +} + +export function new_(tx: Transaction, typeArg: string, pub: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::display::new`, + typeArguments: [typeArg], + arguments: [obj(tx, pub)], + }); +} + +export function version(tx: Transaction, typeArg: string, d: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::display::version`, + typeArguments: [typeArg], + arguments: [obj(tx, d)], + }); +} + +export interface AddInternalArgs { + display: TransactionObjectInput; + name: string | TransactionArgument; + value: string | TransactionArgument; +} + +export function addInternal(tx: Transaction, typeArg: string, args: AddInternalArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::display::add_internal`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.display), + pure(tx, args.name, `${String.$typeName}`), + pure(tx, args.value, `${String.$typeName}`), + ], + }); +} + +export interface AddMultipleArgs { + self: TransactionObjectInput; + fields: Array | TransactionArgument; + values: Array | TransactionArgument; +} + +export function addMultiple(tx: Transaction, typeArg: string, args: AddMultipleArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::display::add_multiple`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.self), + pure(tx, args.fields, `vector<${String.$typeName}>`), + pure(tx, args.values, `vector<${String.$typeName}>`), + ], + }); +} + +export function fields(tx: Transaction, typeArg: string, d: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::display::fields`, + typeArguments: [typeArg], + arguments: [obj(tx, d)], + }); +} + +export function createAndKeep(tx: Transaction, typeArg: string, pub: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::display::create_and_keep`, + typeArguments: [typeArg], + arguments: [obj(tx, pub)], + }); +} + +export function createInternal(tx: Transaction, typeArg: string) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::display::create_internal`, + typeArguments: [typeArg], + arguments: [], + }); +} + +export interface EditArgs { + self: TransactionObjectInput; + name: string | TransactionArgument; + value: string | TransactionArgument; +} + +export function edit(tx: Transaction, typeArg: string, args: EditArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::display::edit`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.self), + pure(tx, args.name, `${String.$typeName}`), + pure(tx, args.value, `${String.$typeName}`), + ], + }); +} + +export function isAuthorized(tx: Transaction, typeArg: string, pub: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::display::is_authorized`, + typeArguments: [typeArg], + arguments: [obj(tx, pub)], + }); +} + +export interface NewWithFieldsArgs { + pub: TransactionObjectInput; + fields: Array | TransactionArgument; + values: Array | TransactionArgument; +} + +export function newWithFields(tx: Transaction, typeArg: string, args: NewWithFieldsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::display::new_with_fields`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.pub), + pure(tx, args.fields, `vector<${String.$typeName}>`), + pure(tx, args.values, `vector<${String.$typeName}>`), + ], + }); +} + +export function updateVersion(tx: Transaction, typeArg: string, display: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::display::update_version`, + typeArguments: [typeArg], + arguments: [obj(tx, display)], + }); +} diff --git a/src/services/models/sui/sui/display/structs.ts b/src/services/models/sui/sui/display/structs.ts new file mode 100644 index 00000000..f434d3d8 --- /dev/null +++ b/src/services/models/sui/sui/display/structs.ts @@ -0,0 +1,668 @@ +// @ts-nocheck +import { String } from "../../_dependencies/source/0x1/string/structs"; +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { ID, UID } from "../object/structs"; +import { VecMap } from "../vec-map/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Display =============================== */ + +export function isDisplay(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::display::Display` + "<"); +} + +export interface DisplayFields { + id: ToField; + fields: ToField>; + version: ToField<"u16">; +} + +export type DisplayReified = Reified, DisplayFields>; + +export class Display implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::display::Display`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = Display.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = Display.$isPhantom; + + readonly id: ToField; + readonly fields: ToField>; + readonly version: ToField<"u16">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: DisplayFields) { + this.$fullTypeName = composeSuiType(Display.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.fields = fields.fields; + this.version = fields.version; + } + + static reified>(T: T): DisplayReified> { + return { + typeName: Display.$typeName, + fullTypeName: composeSuiType(Display.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: Display.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => Display.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Display.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => Display.fromBcs(T, data), + bcs: Display.bcs, + fromJSONField: (field: any) => Display.fromJSONField(T, field), + fromJSON: (json: Record) => Display.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => Display.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => Display.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => Display.fetch(client, T, id), + new: (fields: DisplayFields>) => { + return new Display([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Display.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(Display.reified(T)); + } + static get p() { + return Display.phantom; + } + + static get bcs() { + return bcs.struct("Display", { + id: UID.bcs, + fields: VecMap.bcs(String.bcs, String.bcs), + version: bcs.u16(), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): Display> { + return Display.reified(typeArg).new({ + id: decodeFromFields(UID.reified(), fields.id), + fields: decodeFromFields(VecMap.reified(String.reified(), String.reified()), fields.fields), + version: decodeFromFields("u16", fields.version), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): Display> { + if (!isDisplay(item.type)) { + throw new Error("not a Display type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Display.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + fields: decodeFromFieldsWithTypes(VecMap.reified(String.reified(), String.reified()), item.fields.fields), + version: decodeFromFieldsWithTypes("u16", item.fields.version), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): Display> { + return Display.fromFields(typeArg, Display.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + fields: this.fields.toJSONField(), + version: this.version, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): Display> { + return Display.reified(typeArg).new({ + id: decodeFromJSONField(UID.reified(), field.id), + fields: decodeFromJSONField(VecMap.reified(String.reified(), String.reified()), field.fields), + version: decodeFromJSONField("u16", field.version), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): Display> { + if (json.$typeName !== Display.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Display.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Display.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): Display> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isDisplay(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Display object`); + } + return Display.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): Display> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isDisplay(data.bcs.type)) { + throw new Error(`object at is not a Display object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Display.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Display.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Display object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isDisplay(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Display object`); + } + + return Display.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== DisplayCreated =============================== */ + +export function isDisplayCreated(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::display::DisplayCreated` + "<"); +} + +export interface DisplayCreatedFields { + id: ToField; +} + +export type DisplayCreatedReified = Reified, DisplayCreatedFields>; + +export class DisplayCreated implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::display::DisplayCreated`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = DisplayCreated.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = DisplayCreated.$isPhantom; + + readonly id: ToField; + + private constructor(typeArgs: [PhantomToTypeStr], fields: DisplayCreatedFields) { + this.$fullTypeName = composeSuiType(DisplayCreated.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified>(T: T): DisplayCreatedReified> { + return { + typeName: DisplayCreated.$typeName, + fullTypeName: composeSuiType(DisplayCreated.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: DisplayCreated.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => DisplayCreated.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => DisplayCreated.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => DisplayCreated.fromBcs(T, data), + bcs: DisplayCreated.bcs, + fromJSONField: (field: any) => DisplayCreated.fromJSONField(T, field), + fromJSON: (json: Record) => DisplayCreated.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => DisplayCreated.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => DisplayCreated.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => DisplayCreated.fetch(client, T, id), + new: (fields: DisplayCreatedFields>) => { + return new DisplayCreated([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return DisplayCreated.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(DisplayCreated.reified(T)); + } + static get p() { + return DisplayCreated.phantom; + } + + static get bcs() { + return bcs.struct("DisplayCreated", { + id: ID.bcs, + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): DisplayCreated> { + return DisplayCreated.reified(typeArg).new({ + id: decodeFromFields(ID.reified(), fields.id), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): DisplayCreated> { + if (!isDisplayCreated(item.type)) { + throw new Error("not a DisplayCreated type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return DisplayCreated.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(ID.reified(), item.fields.id), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): DisplayCreated> { + return DisplayCreated.fromFields(typeArg, DisplayCreated.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): DisplayCreated> { + return DisplayCreated.reified(typeArg).new({ + id: decodeFromJSONField(ID.reified(), field.id), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): DisplayCreated> { + if (json.$typeName !== DisplayCreated.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(DisplayCreated.$typeName, extractType(typeArg)), json.$typeArgs, [ + typeArg, + ]); + + return DisplayCreated.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): DisplayCreated> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isDisplayCreated(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a DisplayCreated object`); + } + return DisplayCreated.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): DisplayCreated> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isDisplayCreated(data.bcs.type)) { + throw new Error(`object at is not a DisplayCreated object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return DisplayCreated.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return DisplayCreated.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching DisplayCreated object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isDisplayCreated(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a DisplayCreated object`); + } + + return DisplayCreated.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== VersionUpdated =============================== */ + +export function isVersionUpdated(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::display::VersionUpdated` + "<"); +} + +export interface VersionUpdatedFields { + id: ToField; + version: ToField<"u16">; + fields: ToField>; +} + +export type VersionUpdatedReified = Reified, VersionUpdatedFields>; + +export class VersionUpdated implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::display::VersionUpdated`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = VersionUpdated.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = VersionUpdated.$isPhantom; + + readonly id: ToField; + readonly version: ToField<"u16">; + readonly fields: ToField>; + + private constructor(typeArgs: [PhantomToTypeStr], fields: VersionUpdatedFields) { + this.$fullTypeName = composeSuiType(VersionUpdated.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.version = fields.version; + this.fields = fields.fields; + } + + static reified>(T: T): VersionUpdatedReified> { + return { + typeName: VersionUpdated.$typeName, + fullTypeName: composeSuiType(VersionUpdated.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: VersionUpdated.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => VersionUpdated.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => VersionUpdated.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => VersionUpdated.fromBcs(T, data), + bcs: VersionUpdated.bcs, + fromJSONField: (field: any) => VersionUpdated.fromJSONField(T, field), + fromJSON: (json: Record) => VersionUpdated.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => VersionUpdated.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => VersionUpdated.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => VersionUpdated.fetch(client, T, id), + new: (fields: VersionUpdatedFields>) => { + return new VersionUpdated([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return VersionUpdated.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(VersionUpdated.reified(T)); + } + static get p() { + return VersionUpdated.phantom; + } + + static get bcs() { + return bcs.struct("VersionUpdated", { + id: ID.bcs, + version: bcs.u16(), + fields: VecMap.bcs(String.bcs, String.bcs), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): VersionUpdated> { + return VersionUpdated.reified(typeArg).new({ + id: decodeFromFields(ID.reified(), fields.id), + version: decodeFromFields("u16", fields.version), + fields: decodeFromFields(VecMap.reified(String.reified(), String.reified()), fields.fields), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): VersionUpdated> { + if (!isVersionUpdated(item.type)) { + throw new Error("not a VersionUpdated type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return VersionUpdated.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(ID.reified(), item.fields.id), + version: decodeFromFieldsWithTypes("u16", item.fields.version), + fields: decodeFromFieldsWithTypes(VecMap.reified(String.reified(), String.reified()), item.fields.fields), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): VersionUpdated> { + return VersionUpdated.fromFields(typeArg, VersionUpdated.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + version: this.version, + fields: this.fields.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): VersionUpdated> { + return VersionUpdated.reified(typeArg).new({ + id: decodeFromJSONField(ID.reified(), field.id), + version: decodeFromJSONField("u16", field.version), + fields: decodeFromJSONField(VecMap.reified(String.reified(), String.reified()), field.fields), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): VersionUpdated> { + if (json.$typeName !== VersionUpdated.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(VersionUpdated.$typeName, extractType(typeArg)), json.$typeArgs, [ + typeArg, + ]); + + return VersionUpdated.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): VersionUpdated> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isVersionUpdated(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a VersionUpdated object`); + } + return VersionUpdated.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): VersionUpdated> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isVersionUpdated(data.bcs.type)) { + throw new Error(`object at is not a VersionUpdated object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return VersionUpdated.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return VersionUpdated.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching VersionUpdated object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isVersionUpdated(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a VersionUpdated object`); + } + + return VersionUpdated.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/sui/dynamic-field/functions.ts b/src/services/models/sui/sui/dynamic-field/functions.ts new file mode 100644 index 00000000..d50364f5 --- /dev/null +++ b/src/services/models/sui/sui/dynamic-field/functions.ts @@ -0,0 +1,216 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface AddArgs { + object: TransactionObjectInput; + name: GenericArg; + value: GenericArg; +} + +export function add(tx: Transaction, typeArgs: [string, string], args: AddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_field::add`, + typeArguments: typeArgs, + arguments: [ + obj(tx, args.object), + generic(tx, `${typeArgs[0]}`, args.name), + generic(tx, `${typeArgs[1]}`, args.value), + ], + }); +} + +export interface BorrowArgs { + object: TransactionObjectInput; + name: GenericArg; +} + +export function borrow(tx: Transaction, typeArgs: [string, string], args: BorrowArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_field::borrow`, + typeArguments: typeArgs, + arguments: [obj(tx, args.object), generic(tx, `${typeArgs[0]}`, args.name)], + }); +} + +export interface BorrowMutArgs { + object: TransactionObjectInput; + name: GenericArg; +} + +export function borrowMut(tx: Transaction, typeArgs: [string, string], args: BorrowMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_field::borrow_mut`, + typeArguments: typeArgs, + arguments: [obj(tx, args.object), generic(tx, `${typeArgs[0]}`, args.name)], + }); +} + +export interface RemoveArgs { + object: TransactionObjectInput; + name: GenericArg; +} + +export function remove(tx: Transaction, typeArgs: [string, string], args: RemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_field::remove`, + typeArguments: typeArgs, + arguments: [obj(tx, args.object), generic(tx, `${typeArgs[0]}`, args.name)], + }); +} + +export interface AddChildObjectArgs { + parent: string | TransactionArgument; + child: GenericArg; +} + +export function addChildObject(tx: Transaction, typeArg: string, args: AddChildObjectArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_field::add_child_object`, + typeArguments: [typeArg], + arguments: [pure(tx, args.parent, `address`), generic(tx, `${typeArg}`, args.child)], + }); +} + +export interface BorrowChildObjectArgs { + object: TransactionObjectInput; + id: string | TransactionArgument; +} + +export function borrowChildObject(tx: Transaction, typeArg: string, args: BorrowChildObjectArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_field::borrow_child_object`, + typeArguments: [typeArg], + arguments: [obj(tx, args.object), pure(tx, args.id, `address`)], + }); +} + +export interface BorrowChildObjectMutArgs { + object: TransactionObjectInput; + id: string | TransactionArgument; +} + +export function borrowChildObjectMut(tx: Transaction, typeArg: string, args: BorrowChildObjectMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_field::borrow_child_object_mut`, + typeArguments: [typeArg], + arguments: [obj(tx, args.object), pure(tx, args.id, `address`)], + }); +} + +export interface Exists_Args { + object: TransactionObjectInput; + name: GenericArg; +} + +export function exists_(tx: Transaction, typeArg: string, args: Exists_Args) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_field::exists_`, + typeArguments: [typeArg], + arguments: [obj(tx, args.object), generic(tx, `${typeArg}`, args.name)], + }); +} + +export interface ExistsWithTypeArgs { + object: TransactionObjectInput; + name: GenericArg; +} + +export function existsWithType(tx: Transaction, typeArgs: [string, string], args: ExistsWithTypeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_field::exists_with_type`, + typeArguments: typeArgs, + arguments: [obj(tx, args.object), generic(tx, `${typeArgs[0]}`, args.name)], + }); +} + +export interface FieldInfoArgs { + object: TransactionObjectInput; + name: GenericArg; +} + +export function fieldInfo(tx: Transaction, typeArg: string, args: FieldInfoArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_field::field_info`, + typeArguments: [typeArg], + arguments: [obj(tx, args.object), generic(tx, `${typeArg}`, args.name)], + }); +} + +export interface FieldInfoMutArgs { + object: TransactionObjectInput; + name: GenericArg; +} + +export function fieldInfoMut(tx: Transaction, typeArg: string, args: FieldInfoMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_field::field_info_mut`, + typeArguments: [typeArg], + arguments: [obj(tx, args.object), generic(tx, `${typeArg}`, args.name)], + }); +} + +export interface HasChildObjectArgs { + parent: string | TransactionArgument; + id: string | TransactionArgument; +} + +export function hasChildObject(tx: Transaction, args: HasChildObjectArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_field::has_child_object`, + arguments: [pure(tx, args.parent, `address`), pure(tx, args.id, `address`)], + }); +} + +export interface HasChildObjectWithTyArgs { + parent: string | TransactionArgument; + id: string | TransactionArgument; +} + +export function hasChildObjectWithTy(tx: Transaction, typeArg: string, args: HasChildObjectWithTyArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_field::has_child_object_with_ty`, + typeArguments: [typeArg], + arguments: [pure(tx, args.parent, `address`), pure(tx, args.id, `address`)], + }); +} + +export interface HashTypeAndKeyArgs { + parent: string | TransactionArgument; + k: GenericArg; +} + +export function hashTypeAndKey(tx: Transaction, typeArg: string, args: HashTypeAndKeyArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_field::hash_type_and_key`, + typeArguments: [typeArg], + arguments: [pure(tx, args.parent, `address`), generic(tx, `${typeArg}`, args.k)], + }); +} + +export interface RemoveChildObjectArgs { + parent: string | TransactionArgument; + id: string | TransactionArgument; +} + +export function removeChildObject(tx: Transaction, typeArg: string, args: RemoveChildObjectArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_field::remove_child_object`, + typeArguments: [typeArg], + arguments: [pure(tx, args.parent, `address`), pure(tx, args.id, `address`)], + }); +} + +export interface RemoveIfExistsArgs { + object: TransactionObjectInput; + name: GenericArg; +} + +export function removeIfExists(tx: Transaction, typeArgs: [string, string], args: RemoveIfExistsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_field::remove_if_exists`, + typeArguments: typeArgs, + arguments: [obj(tx, args.object), generic(tx, `${typeArgs[0]}`, args.name)], + }); +} diff --git a/src/services/models/sui/sui/dynamic-field/structs.ts b/src/services/models/sui/sui/dynamic-field/structs.ts new file mode 100644 index 00000000..1b2ffac0 --- /dev/null +++ b/src/services/models/sui/sui/dynamic-field/structs.ts @@ -0,0 +1,258 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeArgument, + ToTypeStr, + TypeArgument, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + fieldToJSON, + phantom, + toBcs, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { UID } from "../object/structs"; +import { BcsType, bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Field =============================== */ + +export function isField(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::dynamic_field::Field` + "<"); +} + +export interface FieldFields { + id: ToField; + name: ToField; + value: ToField; +} + +export type FieldReified = Reified< + Field, + FieldFields +>; + +export class Field implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::dynamic_field::Field`; + } + static readonly $numTypeParams = 2; + static readonly $isPhantom = [false, false] as const; + + readonly $typeName = Field.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [ToTypeStr, ToTypeStr]; + readonly $isPhantom = Field.$isPhantom; + + readonly id: ToField; + readonly name: ToField; + readonly value: ToField; + + private constructor(typeArgs: [ToTypeStr, ToTypeStr], fields: FieldFields) { + this.$fullTypeName = composeSuiType(Field.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.name = fields.name; + this.value = fields.value; + } + + static reified, Value extends Reified>( + Name: Name, + Value: Value + ): FieldReified, ToTypeArgument> { + return { + typeName: Field.$typeName, + fullTypeName: composeSuiType(Field.$typeName, ...[extractType(Name), extractType(Value)]) as string, + typeArgs: [extractType(Name), extractType(Value)] as [ + ToTypeStr>, + ToTypeStr>, + ], + isPhantom: Field.$isPhantom, + reifiedTypeArgs: [Name, Value], + fromFields: (fields: Record) => Field.fromFields([Name, Value], fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Field.fromFieldsWithTypes([Name, Value], item), + fromBcs: (data: Uint8Array) => Field.fromBcs([Name, Value], data), + bcs: Field.bcs(toBcs(Name), toBcs(Value)), + fromJSONField: (field: any) => Field.fromJSONField([Name, Value], field), + fromJSON: (json: Record) => Field.fromJSON([Name, Value], json), + fromSuiParsedData: (content: SuiParsedData) => Field.fromSuiParsedData([Name, Value], content), + fromSuiObjectData: (content: SuiObjectData) => Field.fromSuiObjectData([Name, Value], content), + fetch: async (client: SuiClient, id: string) => Field.fetch(client, [Name, Value], id), + new: (fields: FieldFields, ToTypeArgument>) => { + return new Field([extractType(Name), extractType(Value)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Field.reified; + } + + static phantom, Value extends Reified>( + Name: Name, + Value: Value + ): PhantomReified, ToTypeArgument>>> { + return phantom(Field.reified(Name, Value)); + } + static get p() { + return Field.phantom; + } + + static get bcs() { + return , Value extends BcsType>(Name: Name, Value: Value) => + bcs.struct(`Field<${Name.name}, ${Value.name}>`, { + id: UID.bcs, + name: Name, + value: Value, + }); + } + + static fromFields, Value extends Reified>( + typeArgs: [Name, Value], + fields: Record + ): Field, ToTypeArgument> { + return Field.reified(typeArgs[0], typeArgs[1]).new({ + id: decodeFromFields(UID.reified(), fields.id), + name: decodeFromFields(typeArgs[0], fields.name), + value: decodeFromFields(typeArgs[1], fields.value), + }); + } + + static fromFieldsWithTypes, Value extends Reified>( + typeArgs: [Name, Value], + item: FieldsWithTypes + ): Field, ToTypeArgument> { + if (!isField(item.type)) { + throw new Error("not a Field type"); + } + assertFieldsWithTypesArgsMatch(item, typeArgs); + + return Field.reified(typeArgs[0], typeArgs[1]).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + name: decodeFromFieldsWithTypes(typeArgs[0], item.fields.name), + value: decodeFromFieldsWithTypes(typeArgs[1], item.fields.value), + }); + } + + static fromBcs, Value extends Reified>( + typeArgs: [Name, Value], + data: Uint8Array + ): Field, ToTypeArgument> { + return Field.fromFields(typeArgs, Field.bcs(toBcs(typeArgs[0]), toBcs(typeArgs[1])).parse(data)); + } + + toJSONField() { + return { + id: this.id, + name: fieldToJSON(this.$typeArgs[0], this.name), + value: fieldToJSON(this.$typeArgs[1], this.value), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField, Value extends Reified>( + typeArgs: [Name, Value], + field: any + ): Field, ToTypeArgument> { + return Field.reified(typeArgs[0], typeArgs[1]).new({ + id: decodeFromJSONField(UID.reified(), field.id), + name: decodeFromJSONField(typeArgs[0], field.name), + value: decodeFromJSONField(typeArgs[1], field.value), + }); + } + + static fromJSON, Value extends Reified>( + typeArgs: [Name, Value], + json: Record + ): Field, ToTypeArgument> { + if (json.$typeName !== Field.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Field.$typeName, ...typeArgs.map(extractType)), json.$typeArgs, typeArgs); + + return Field.fromJSONField(typeArgs, json); + } + + static fromSuiParsedData, Value extends Reified>( + typeArgs: [Name, Value], + content: SuiParsedData + ): Field, ToTypeArgument> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isField(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Field object`); + } + return Field.fromFieldsWithTypes(typeArgs, content); + } + + static fromSuiObjectData, Value extends Reified>( + typeArgs: [Name, Value], + data: SuiObjectData + ): Field, ToTypeArgument> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isField(data.bcs.type)) { + throw new Error(`object at is not a Field object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 2) { + throw new Error(`type argument mismatch: expected 2 type arguments but got ${gotTypeArgs.length}`); + } + for (let i = 0; i < 2; i++) { + const gotTypeArg = compressSuiType(gotTypeArgs[i]); + const expectedTypeArg = compressSuiType(extractType(typeArgs[i])); + if (gotTypeArg !== expectedTypeArg) { + throw new Error( + `type argument mismatch at position ${i}: expected '${expectedTypeArg}' but got '${gotTypeArg}'` + ); + } + } + + return Field.fromBcs(typeArgs, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Field.fromSuiParsedData(typeArgs, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch, Value extends Reified>( + client: SuiClient, + typeArgs: [Name, Value], + id: string + ): Promise, ToTypeArgument>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Field object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isField(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Field object`); + } + + return Field.fromSuiObjectData(typeArgs, res.data); + } +} diff --git a/src/services/models/sui/sui/dynamic-object-field/functions.ts b/src/services/models/sui/sui/dynamic-object-field/functions.ts new file mode 100644 index 00000000..3a1397d7 --- /dev/null +++ b/src/services/models/sui/sui/dynamic-object-field/functions.ts @@ -0,0 +1,170 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj } from "../../_framework/util"; +import { Transaction, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface AddArgs { + object: TransactionObjectInput; + name: GenericArg; + value: GenericArg; +} + +export function add(tx: Transaction, typeArgs: [string, string], args: AddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_object_field::add`, + typeArguments: typeArgs, + arguments: [ + obj(tx, args.object), + generic(tx, `${typeArgs[0]}`, args.name), + generic(tx, `${typeArgs[1]}`, args.value), + ], + }); +} + +export interface IdArgs { + object: TransactionObjectInput; + name: GenericArg; +} + +export function id(tx: Transaction, typeArg: string, args: IdArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_object_field::id`, + typeArguments: [typeArg], + arguments: [obj(tx, args.object), generic(tx, `${typeArg}`, args.name)], + }); +} + +export interface BorrowArgs { + object: TransactionObjectInput; + name: GenericArg; +} + +export function borrow(tx: Transaction, typeArgs: [string, string], args: BorrowArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_object_field::borrow`, + typeArguments: typeArgs, + arguments: [obj(tx, args.object), generic(tx, `${typeArgs[0]}`, args.name)], + }); +} + +export interface BorrowMutArgs { + object: TransactionObjectInput; + name: GenericArg; +} + +export function borrowMut(tx: Transaction, typeArgs: [string, string], args: BorrowMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_object_field::borrow_mut`, + typeArguments: typeArgs, + arguments: [obj(tx, args.object), generic(tx, `${typeArgs[0]}`, args.name)], + }); +} + +export interface RemoveArgs { + object: TransactionObjectInput; + name: GenericArg; +} + +export function remove(tx: Transaction, typeArgs: [string, string], args: RemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_object_field::remove`, + typeArguments: typeArgs, + arguments: [obj(tx, args.object), generic(tx, `${typeArgs[0]}`, args.name)], + }); +} + +export interface Exists_Args { + object: TransactionObjectInput; + name: GenericArg; +} + +export function exists_(tx: Transaction, typeArg: string, args: Exists_Args) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_object_field::exists_`, + typeArguments: [typeArg], + arguments: [obj(tx, args.object), generic(tx, `${typeArg}`, args.name)], + }); +} + +export interface ExistsWithTypeArgs { + object: TransactionObjectInput; + name: GenericArg; +} + +export function existsWithType(tx: Transaction, typeArgs: [string, string], args: ExistsWithTypeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_object_field::exists_with_type`, + typeArguments: typeArgs, + arguments: [obj(tx, args.object), generic(tx, `${typeArgs[0]}`, args.name)], + }); +} + +export interface InternalAddArgs { + object: TransactionObjectInput; + name: GenericArg; + value: GenericArg; +} + +export function internalAdd(tx: Transaction, typeArgs: [string, string], args: InternalAddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_object_field::internal_add`, + typeArguments: typeArgs, + arguments: [ + obj(tx, args.object), + generic(tx, `${typeArgs[0]}`, args.name), + generic(tx, `${typeArgs[1]}`, args.value), + ], + }); +} + +export interface InternalBorrowArgs { + object: TransactionObjectInput; + name: GenericArg; +} + +export function internalBorrow(tx: Transaction, typeArgs: [string, string], args: InternalBorrowArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_object_field::internal_borrow`, + typeArguments: typeArgs, + arguments: [obj(tx, args.object), generic(tx, `${typeArgs[0]}`, args.name)], + }); +} + +export interface InternalBorrowMutArgs { + object: TransactionObjectInput; + name: GenericArg; +} + +export function internalBorrowMut(tx: Transaction, typeArgs: [string, string], args: InternalBorrowMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_object_field::internal_borrow_mut`, + typeArguments: typeArgs, + arguments: [obj(tx, args.object), generic(tx, `${typeArgs[0]}`, args.name)], + }); +} + +export interface InternalExistsWithTypeArgs { + object: TransactionObjectInput; + name: GenericArg; +} + +export function internalExistsWithType(tx: Transaction, typeArgs: [string, string], args: InternalExistsWithTypeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_object_field::internal_exists_with_type`, + typeArguments: typeArgs, + arguments: [obj(tx, args.object), generic(tx, `${typeArgs[0]}`, args.name)], + }); +} + +export interface InternalRemoveArgs { + object: TransactionObjectInput; + name: GenericArg; +} + +export function internalRemove(tx: Transaction, typeArgs: [string, string], args: InternalRemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::dynamic_object_field::internal_remove`, + typeArguments: typeArgs, + arguments: [obj(tx, args.object), generic(tx, `${typeArgs[0]}`, args.name)], + }); +} diff --git a/src/services/models/sui/sui/dynamic-object-field/structs.ts b/src/services/models/sui/sui/dynamic-object-field/structs.ts new file mode 100644 index 00000000..f4b6fd5d --- /dev/null +++ b/src/services/models/sui/sui/dynamic-object-field/structs.ts @@ -0,0 +1,229 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeArgument, + ToTypeStr, + TypeArgument, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + fieldToJSON, + phantom, + toBcs, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { BcsType, bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Wrapper =============================== */ + +export function isWrapper(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::dynamic_object_field::Wrapper` + "<"); +} + +export interface WrapperFields { + name: ToField; +} + +export type WrapperReified = Reified, WrapperFields>; + +export class Wrapper implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::dynamic_object_field::Wrapper`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [false] as const; + + readonly $typeName = Wrapper.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [ToTypeStr]; + readonly $isPhantom = Wrapper.$isPhantom; + + readonly name: ToField; + + private constructor(typeArgs: [ToTypeStr], fields: WrapperFields) { + this.$fullTypeName = composeSuiType(Wrapper.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.name = fields.name; + } + + static reified>(Name: Name): WrapperReified> { + return { + typeName: Wrapper.$typeName, + fullTypeName: composeSuiType(Wrapper.$typeName, ...[extractType(Name)]) as string, + typeArgs: [extractType(Name)] as [ToTypeStr>], + isPhantom: Wrapper.$isPhantom, + reifiedTypeArgs: [Name], + fromFields: (fields: Record) => Wrapper.fromFields(Name, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Wrapper.fromFieldsWithTypes(Name, item), + fromBcs: (data: Uint8Array) => Wrapper.fromBcs(Name, data), + bcs: Wrapper.bcs(toBcs(Name)), + fromJSONField: (field: any) => Wrapper.fromJSONField(Name, field), + fromJSON: (json: Record) => Wrapper.fromJSON(Name, json), + fromSuiParsedData: (content: SuiParsedData) => Wrapper.fromSuiParsedData(Name, content), + fromSuiObjectData: (content: SuiObjectData) => Wrapper.fromSuiObjectData(Name, content), + fetch: async (client: SuiClient, id: string) => Wrapper.fetch(client, Name, id), + new: (fields: WrapperFields>) => { + return new Wrapper([extractType(Name)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Wrapper.reified; + } + + static phantom>( + Name: Name + ): PhantomReified>>> { + return phantom(Wrapper.reified(Name)); + } + static get p() { + return Wrapper.phantom; + } + + static get bcs() { + return >(Name: Name) => + bcs.struct(`Wrapper<${Name.name}>`, { + name: Name, + }); + } + + static fromFields>( + typeArg: Name, + fields: Record + ): Wrapper> { + return Wrapper.reified(typeArg).new({ + name: decodeFromFields(typeArg, fields.name), + }); + } + + static fromFieldsWithTypes>( + typeArg: Name, + item: FieldsWithTypes + ): Wrapper> { + if (!isWrapper(item.type)) { + throw new Error("not a Wrapper type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Wrapper.reified(typeArg).new({ + name: decodeFromFieldsWithTypes(typeArg, item.fields.name), + }); + } + + static fromBcs>( + typeArg: Name, + data: Uint8Array + ): Wrapper> { + const typeArgs = [typeArg]; + + return Wrapper.fromFields(typeArg, Wrapper.bcs(toBcs(typeArgs[0])).parse(data)); + } + + toJSONField() { + return { + name: fieldToJSON(this.$typeArgs[0], this.name), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: Name, + field: any + ): Wrapper> { + return Wrapper.reified(typeArg).new({ + name: decodeFromJSONField(typeArg, field.name), + }); + } + + static fromJSON>( + typeArg: Name, + json: Record + ): Wrapper> { + if (json.$typeName !== Wrapper.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Wrapper.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Wrapper.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: Name, + content: SuiParsedData + ): Wrapper> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isWrapper(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Wrapper object`); + } + return Wrapper.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: Name, + data: SuiObjectData + ): Wrapper> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isWrapper(data.bcs.type)) { + throw new Error(`object at is not a Wrapper object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Wrapper.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Wrapper.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: Name, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Wrapper object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isWrapper(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Wrapper object`); + } + + return Wrapper.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/sui/ecdsa-k1/functions.ts b/src/services/models/sui/sui/ecdsa-k1/functions.ts new file mode 100644 index 00000000..10a39517 --- /dev/null +++ b/src/services/models/sui/sui/ecdsa-k1/functions.ts @@ -0,0 +1,43 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { pure } from "../../_framework/util"; +import { Transaction, TransactionArgument } from "@mysten/sui/transactions"; + +export function decompressPubkey(tx: Transaction, pubkey: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::ecdsa_k1::decompress_pubkey`, + arguments: [pure(tx, pubkey, `vector`)], + }); +} + +export interface Secp256k1EcrecoverArgs { + signature: Array | TransactionArgument; + msg: Array | TransactionArgument; + hash: number | TransactionArgument; +} + +export function secp256k1Ecrecover(tx: Transaction, args: Secp256k1EcrecoverArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::ecdsa_k1::secp256k1_ecrecover`, + arguments: [pure(tx, args.signature, `vector`), pure(tx, args.msg, `vector`), pure(tx, args.hash, `u8`)], + }); +} + +export interface Secp256k1VerifyArgs { + signature: Array | TransactionArgument; + publicKey: Array | TransactionArgument; + msg: Array | TransactionArgument; + hash: number | TransactionArgument; +} + +export function secp256k1Verify(tx: Transaction, args: Secp256k1VerifyArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::ecdsa_k1::secp256k1_verify`, + arguments: [ + pure(tx, args.signature, `vector`), + pure(tx, args.publicKey, `vector`), + pure(tx, args.msg, `vector`), + pure(tx, args.hash, `u8`), + ], + }); +} diff --git a/src/services/models/sui/sui/ecdsa-r1/functions.ts b/src/services/models/sui/sui/ecdsa-r1/functions.ts new file mode 100644 index 00000000..65415470 --- /dev/null +++ b/src/services/models/sui/sui/ecdsa-r1/functions.ts @@ -0,0 +1,36 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { pure } from "../../_framework/util"; +import { Transaction, TransactionArgument } from "@mysten/sui/transactions"; + +export interface Secp256r1EcrecoverArgs { + signature: Array | TransactionArgument; + msg: Array | TransactionArgument; + hash: number | TransactionArgument; +} + +export function secp256r1Ecrecover(tx: Transaction, args: Secp256r1EcrecoverArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::ecdsa_r1::secp256r1_ecrecover`, + arguments: [pure(tx, args.signature, `vector`), pure(tx, args.msg, `vector`), pure(tx, args.hash, `u8`)], + }); +} + +export interface Secp256r1VerifyArgs { + signature: Array | TransactionArgument; + publicKey: Array | TransactionArgument; + msg: Array | TransactionArgument; + hash: number | TransactionArgument; +} + +export function secp256r1Verify(tx: Transaction, args: Secp256r1VerifyArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::ecdsa_r1::secp256r1_verify`, + arguments: [ + pure(tx, args.signature, `vector`), + pure(tx, args.publicKey, `vector`), + pure(tx, args.msg, `vector`), + pure(tx, args.hash, `u8`), + ], + }); +} diff --git a/src/services/models/sui/sui/ecvrf/functions.ts b/src/services/models/sui/sui/ecvrf/functions.ts new file mode 100644 index 00000000..790ca28f --- /dev/null +++ b/src/services/models/sui/sui/ecvrf/functions.ts @@ -0,0 +1,23 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { pure } from "../../_framework/util"; +import { Transaction, TransactionArgument } from "@mysten/sui/transactions"; + +export interface EcvrfVerifyArgs { + hash: Array | TransactionArgument; + alphaString: Array | TransactionArgument; + publicKey: Array | TransactionArgument; + proof: Array | TransactionArgument; +} + +export function ecvrfVerify(tx: Transaction, args: EcvrfVerifyArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::ecvrf::ecvrf_verify`, + arguments: [ + pure(tx, args.hash, `vector`), + pure(tx, args.alphaString, `vector`), + pure(tx, args.publicKey, `vector`), + pure(tx, args.proof, `vector`), + ], + }); +} diff --git a/src/services/models/sui/sui/ed25519/functions.ts b/src/services/models/sui/sui/ed25519/functions.ts new file mode 100644 index 00000000..ae47efcf --- /dev/null +++ b/src/services/models/sui/sui/ed25519/functions.ts @@ -0,0 +1,21 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { pure } from "../../_framework/util"; +import { Transaction, TransactionArgument } from "@mysten/sui/transactions"; + +export interface Ed25519VerifyArgs { + signature: Array | TransactionArgument; + publicKey: Array | TransactionArgument; + msg: Array | TransactionArgument; +} + +export function ed25519Verify(tx: Transaction, args: Ed25519VerifyArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::ed25519::ed25519_verify`, + arguments: [ + pure(tx, args.signature, `vector`), + pure(tx, args.publicKey, `vector`), + pure(tx, args.msg, `vector`), + ], + }); +} diff --git a/src/services/models/sui/sui/event/functions.ts b/src/services/models/sui/sui/event/functions.ts new file mode 100644 index 00000000..d623b667 --- /dev/null +++ b/src/services/models/sui/sui/event/functions.ts @@ -0,0 +1,12 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic } from "../../_framework/util"; +import { Transaction } from "@mysten/sui/transactions"; + +export function emit(tx: Transaction, typeArg: string, event: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::event::emit`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, event)], + }); +} diff --git a/src/services/models/sui/sui/groth16/functions.ts b/src/services/models/sui/sui/groth16/functions.ts new file mode 100644 index 00000000..16363b77 --- /dev/null +++ b/src/services/models/sui/sui/groth16/functions.ts @@ -0,0 +1,132 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function bls12381(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::groth16::bls12381`, + arguments: [], + }); +} + +export function bn254(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::groth16::bn254`, + arguments: [], + }); +} + +export interface PrepareVerifyingKeyArgs { + curve: TransactionObjectInput; + verifyingKey: Array | TransactionArgument; +} + +export function prepareVerifyingKey(tx: Transaction, args: PrepareVerifyingKeyArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::groth16::prepare_verifying_key`, + arguments: [obj(tx, args.curve), pure(tx, args.verifyingKey, `vector`)], + }); +} + +export interface PrepareVerifyingKeyInternalArgs { + curve: number | TransactionArgument; + verifyingKey: Array | TransactionArgument; +} + +export function prepareVerifyingKeyInternal(tx: Transaction, args: PrepareVerifyingKeyInternalArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::groth16::prepare_verifying_key_internal`, + arguments: [pure(tx, args.curve, `u8`), pure(tx, args.verifyingKey, `vector`)], + }); +} + +export function proofPointsFromBytes( + tx: Transaction, + bytes: Array | TransactionArgument +) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::groth16::proof_points_from_bytes`, + arguments: [pure(tx, bytes, `vector`)], + }); +} + +export function publicProofInputsFromBytes( + tx: Transaction, + bytes: Array | TransactionArgument +) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::groth16::public_proof_inputs_from_bytes`, + arguments: [pure(tx, bytes, `vector`)], + }); +} + +export interface PvkFromBytesArgs { + vkGammaAbcG1Bytes: Array | TransactionArgument; + alphaG1BetaG2Bytes: Array | TransactionArgument; + gammaG2NegPcBytes: Array | TransactionArgument; + deltaG2NegPcBytes: Array | TransactionArgument; +} + +export function pvkFromBytes(tx: Transaction, args: PvkFromBytesArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::groth16::pvk_from_bytes`, + arguments: [ + pure(tx, args.vkGammaAbcG1Bytes, `vector`), + pure(tx, args.alphaG1BetaG2Bytes, `vector`), + pure(tx, args.gammaG2NegPcBytes, `vector`), + pure(tx, args.deltaG2NegPcBytes, `vector`), + ], + }); +} + +export function pvkToBytes(tx: Transaction, pvk: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::groth16::pvk_to_bytes`, + arguments: [obj(tx, pvk)], + }); +} + +export interface VerifyGroth16ProofArgs { + curve: TransactionObjectInput; + preparedVerifyingKey: TransactionObjectInput; + publicProofInputs: TransactionObjectInput; + proofPoints: TransactionObjectInput; +} + +export function verifyGroth16Proof(tx: Transaction, args: VerifyGroth16ProofArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::groth16::verify_groth16_proof`, + arguments: [ + obj(tx, args.curve), + obj(tx, args.preparedVerifyingKey), + obj(tx, args.publicProofInputs), + obj(tx, args.proofPoints), + ], + }); +} + +export interface VerifyGroth16ProofInternalArgs { + curve: number | TransactionArgument; + vkGammaAbcG1Bytes: Array | TransactionArgument; + alphaG1BetaG2Bytes: Array | TransactionArgument; + gammaG2NegPcBytes: Array | TransactionArgument; + deltaG2NegPcBytes: Array | TransactionArgument; + publicProofInputs: Array | TransactionArgument; + proofPoints: Array | TransactionArgument; +} + +export function verifyGroth16ProofInternal(tx: Transaction, args: VerifyGroth16ProofInternalArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::groth16::verify_groth16_proof_internal`, + arguments: [ + pure(tx, args.curve, `u8`), + pure(tx, args.vkGammaAbcG1Bytes, `vector`), + pure(tx, args.alphaG1BetaG2Bytes, `vector`), + pure(tx, args.gammaG2NegPcBytes, `vector`), + pure(tx, args.deltaG2NegPcBytes, `vector`), + pure(tx, args.publicProofInputs, `vector`), + pure(tx, args.proofPoints, `vector`), + ], + }); +} diff --git a/src/services/models/sui/sui/groth16/structs.ts b/src/services/models/sui/sui/groth16/structs.ts new file mode 100644 index 00000000..9d55f835 --- /dev/null +++ b/src/services/models/sui/sui/groth16/structs.ts @@ -0,0 +1,692 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { Vector } from "../../_framework/vector"; +import { PKG_V26 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Curve =============================== */ + +export function isCurve(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::groth16::Curve`; +} + +export interface CurveFields { + id: ToField<"u8">; +} + +export type CurveReified = Reified; + +export class Curve implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::groth16::Curve`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Curve.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Curve.$isPhantom; + + readonly id: ToField<"u8">; + + private constructor(typeArgs: [], fields: CurveFields) { + this.$fullTypeName = composeSuiType(Curve.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified(): CurveReified { + return { + typeName: Curve.$typeName, + fullTypeName: composeSuiType(Curve.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Curve.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Curve.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Curve.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Curve.fromBcs(data), + bcs: Curve.bcs, + fromJSONField: (field: any) => Curve.fromJSONField(field), + fromJSON: (json: Record) => Curve.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Curve.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Curve.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Curve.fetch(client, id), + new: (fields: CurveFields) => { + return new Curve([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Curve.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Curve.reified()); + } + static get p() { + return Curve.phantom(); + } + + static get bcs() { + return bcs.struct("Curve", { + id: bcs.u8(), + }); + } + + static fromFields(fields: Record): Curve { + return Curve.reified().new({ id: decodeFromFields("u8", fields.id) }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Curve { + if (!isCurve(item.type)) { + throw new Error("not a Curve type"); + } + + return Curve.reified().new({ + id: decodeFromFieldsWithTypes("u8", item.fields.id), + }); + } + + static fromBcs(data: Uint8Array): Curve { + return Curve.fromFields(Curve.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Curve { + return Curve.reified().new({ id: decodeFromJSONField("u8", field.id) }); + } + + static fromJSON(json: Record): Curve { + if (json.$typeName !== Curve.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Curve.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Curve { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isCurve(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Curve object`); + } + return Curve.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Curve { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isCurve(data.bcs.type)) { + throw new Error(`object at is not a Curve object`); + } + + return Curve.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Curve.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Curve object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isCurve(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Curve object`); + } + + return Curve.fromSuiObjectData(res.data); + } +} + +/* ============================== PreparedVerifyingKey =============================== */ + +export function isPreparedVerifyingKey(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::groth16::PreparedVerifyingKey`; +} + +export interface PreparedVerifyingKeyFields { + vkGammaAbcG1Bytes: ToField>; + alphaG1BetaG2Bytes: ToField>; + gammaG2NegPcBytes: ToField>; + deltaG2NegPcBytes: ToField>; +} + +export type PreparedVerifyingKeyReified = Reified; + +export class PreparedVerifyingKey implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::groth16::PreparedVerifyingKey`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = PreparedVerifyingKey.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = PreparedVerifyingKey.$isPhantom; + + readonly vkGammaAbcG1Bytes: ToField>; + readonly alphaG1BetaG2Bytes: ToField>; + readonly gammaG2NegPcBytes: ToField>; + readonly deltaG2NegPcBytes: ToField>; + + private constructor(typeArgs: [], fields: PreparedVerifyingKeyFields) { + this.$fullTypeName = composeSuiType(PreparedVerifyingKey.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.vkGammaAbcG1Bytes = fields.vkGammaAbcG1Bytes; + this.alphaG1BetaG2Bytes = fields.alphaG1BetaG2Bytes; + this.gammaG2NegPcBytes = fields.gammaG2NegPcBytes; + this.deltaG2NegPcBytes = fields.deltaG2NegPcBytes; + } + + static reified(): PreparedVerifyingKeyReified { + return { + typeName: PreparedVerifyingKey.$typeName, + fullTypeName: composeSuiType(PreparedVerifyingKey.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: PreparedVerifyingKey.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => PreparedVerifyingKey.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => PreparedVerifyingKey.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => PreparedVerifyingKey.fromBcs(data), + bcs: PreparedVerifyingKey.bcs, + fromJSONField: (field: any) => PreparedVerifyingKey.fromJSONField(field), + fromJSON: (json: Record) => PreparedVerifyingKey.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => PreparedVerifyingKey.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => PreparedVerifyingKey.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => PreparedVerifyingKey.fetch(client, id), + new: (fields: PreparedVerifyingKeyFields) => { + return new PreparedVerifyingKey([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return PreparedVerifyingKey.reified(); + } + + static phantom(): PhantomReified> { + return phantom(PreparedVerifyingKey.reified()); + } + static get p() { + return PreparedVerifyingKey.phantom(); + } + + static get bcs() { + return bcs.struct("PreparedVerifyingKey", { + vk_gamma_abc_g1_bytes: bcs.vector(bcs.u8()), + alpha_g1_beta_g2_bytes: bcs.vector(bcs.u8()), + gamma_g2_neg_pc_bytes: bcs.vector(bcs.u8()), + delta_g2_neg_pc_bytes: bcs.vector(bcs.u8()), + }); + } + + static fromFields(fields: Record): PreparedVerifyingKey { + return PreparedVerifyingKey.reified().new({ + vkGammaAbcG1Bytes: decodeFromFields(reified.vector("u8"), fields.vk_gamma_abc_g1_bytes), + alphaG1BetaG2Bytes: decodeFromFields(reified.vector("u8"), fields.alpha_g1_beta_g2_bytes), + gammaG2NegPcBytes: decodeFromFields(reified.vector("u8"), fields.gamma_g2_neg_pc_bytes), + deltaG2NegPcBytes: decodeFromFields(reified.vector("u8"), fields.delta_g2_neg_pc_bytes), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): PreparedVerifyingKey { + if (!isPreparedVerifyingKey(item.type)) { + throw new Error("not a PreparedVerifyingKey type"); + } + + return PreparedVerifyingKey.reified().new({ + vkGammaAbcG1Bytes: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.vk_gamma_abc_g1_bytes), + alphaG1BetaG2Bytes: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.alpha_g1_beta_g2_bytes), + gammaG2NegPcBytes: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.gamma_g2_neg_pc_bytes), + deltaG2NegPcBytes: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.delta_g2_neg_pc_bytes), + }); + } + + static fromBcs(data: Uint8Array): PreparedVerifyingKey { + return PreparedVerifyingKey.fromFields(PreparedVerifyingKey.bcs.parse(data)); + } + + toJSONField() { + return { + vkGammaAbcG1Bytes: fieldToJSON>(`vector`, this.vkGammaAbcG1Bytes), + alphaG1BetaG2Bytes: fieldToJSON>(`vector`, this.alphaG1BetaG2Bytes), + gammaG2NegPcBytes: fieldToJSON>(`vector`, this.gammaG2NegPcBytes), + deltaG2NegPcBytes: fieldToJSON>(`vector`, this.deltaG2NegPcBytes), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): PreparedVerifyingKey { + return PreparedVerifyingKey.reified().new({ + vkGammaAbcG1Bytes: decodeFromJSONField(reified.vector("u8"), field.vkGammaAbcG1Bytes), + alphaG1BetaG2Bytes: decodeFromJSONField(reified.vector("u8"), field.alphaG1BetaG2Bytes), + gammaG2NegPcBytes: decodeFromJSONField(reified.vector("u8"), field.gammaG2NegPcBytes), + deltaG2NegPcBytes: decodeFromJSONField(reified.vector("u8"), field.deltaG2NegPcBytes), + }); + } + + static fromJSON(json: Record): PreparedVerifyingKey { + if (json.$typeName !== PreparedVerifyingKey.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return PreparedVerifyingKey.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): PreparedVerifyingKey { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isPreparedVerifyingKey(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a PreparedVerifyingKey object`); + } + return PreparedVerifyingKey.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): PreparedVerifyingKey { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isPreparedVerifyingKey(data.bcs.type)) { + throw new Error(`object at is not a PreparedVerifyingKey object`); + } + + return PreparedVerifyingKey.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return PreparedVerifyingKey.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching PreparedVerifyingKey object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isPreparedVerifyingKey(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a PreparedVerifyingKey object`); + } + + return PreparedVerifyingKey.fromSuiObjectData(res.data); + } +} + +/* ============================== ProofPoints =============================== */ + +export function isProofPoints(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::groth16::ProofPoints`; +} + +export interface ProofPointsFields { + bytes: ToField>; +} + +export type ProofPointsReified = Reified; + +export class ProofPoints implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::groth16::ProofPoints`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = ProofPoints.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = ProofPoints.$isPhantom; + + readonly bytes: ToField>; + + private constructor(typeArgs: [], fields: ProofPointsFields) { + this.$fullTypeName = composeSuiType(ProofPoints.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.bytes = fields.bytes; + } + + static reified(): ProofPointsReified { + return { + typeName: ProofPoints.$typeName, + fullTypeName: composeSuiType(ProofPoints.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: ProofPoints.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => ProofPoints.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => ProofPoints.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => ProofPoints.fromBcs(data), + bcs: ProofPoints.bcs, + fromJSONField: (field: any) => ProofPoints.fromJSONField(field), + fromJSON: (json: Record) => ProofPoints.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => ProofPoints.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => ProofPoints.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => ProofPoints.fetch(client, id), + new: (fields: ProofPointsFields) => { + return new ProofPoints([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return ProofPoints.reified(); + } + + static phantom(): PhantomReified> { + return phantom(ProofPoints.reified()); + } + static get p() { + return ProofPoints.phantom(); + } + + static get bcs() { + return bcs.struct("ProofPoints", { + bytes: bcs.vector(bcs.u8()), + }); + } + + static fromFields(fields: Record): ProofPoints { + return ProofPoints.reified().new({ + bytes: decodeFromFields(reified.vector("u8"), fields.bytes), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): ProofPoints { + if (!isProofPoints(item.type)) { + throw new Error("not a ProofPoints type"); + } + + return ProofPoints.reified().new({ + bytes: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.bytes), + }); + } + + static fromBcs(data: Uint8Array): ProofPoints { + return ProofPoints.fromFields(ProofPoints.bcs.parse(data)); + } + + toJSONField() { + return { + bytes: fieldToJSON>(`vector`, this.bytes), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): ProofPoints { + return ProofPoints.reified().new({ + bytes: decodeFromJSONField(reified.vector("u8"), field.bytes), + }); + } + + static fromJSON(json: Record): ProofPoints { + if (json.$typeName !== ProofPoints.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return ProofPoints.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): ProofPoints { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isProofPoints(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a ProofPoints object`); + } + return ProofPoints.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): ProofPoints { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isProofPoints(data.bcs.type)) { + throw new Error(`object at is not a ProofPoints object`); + } + + return ProofPoints.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return ProofPoints.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching ProofPoints object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isProofPoints(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a ProofPoints object`); + } + + return ProofPoints.fromSuiObjectData(res.data); + } +} + +/* ============================== PublicProofInputs =============================== */ + +export function isPublicProofInputs(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::groth16::PublicProofInputs`; +} + +export interface PublicProofInputsFields { + bytes: ToField>; +} + +export type PublicProofInputsReified = Reified; + +export class PublicProofInputs implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::groth16::PublicProofInputs`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = PublicProofInputs.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = PublicProofInputs.$isPhantom; + + readonly bytes: ToField>; + + private constructor(typeArgs: [], fields: PublicProofInputsFields) { + this.$fullTypeName = composeSuiType(PublicProofInputs.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.bytes = fields.bytes; + } + + static reified(): PublicProofInputsReified { + return { + typeName: PublicProofInputs.$typeName, + fullTypeName: composeSuiType(PublicProofInputs.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: PublicProofInputs.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => PublicProofInputs.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => PublicProofInputs.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => PublicProofInputs.fromBcs(data), + bcs: PublicProofInputs.bcs, + fromJSONField: (field: any) => PublicProofInputs.fromJSONField(field), + fromJSON: (json: Record) => PublicProofInputs.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => PublicProofInputs.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => PublicProofInputs.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => PublicProofInputs.fetch(client, id), + new: (fields: PublicProofInputsFields) => { + return new PublicProofInputs([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return PublicProofInputs.reified(); + } + + static phantom(): PhantomReified> { + return phantom(PublicProofInputs.reified()); + } + static get p() { + return PublicProofInputs.phantom(); + } + + static get bcs() { + return bcs.struct("PublicProofInputs", { + bytes: bcs.vector(bcs.u8()), + }); + } + + static fromFields(fields: Record): PublicProofInputs { + return PublicProofInputs.reified().new({ + bytes: decodeFromFields(reified.vector("u8"), fields.bytes), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): PublicProofInputs { + if (!isPublicProofInputs(item.type)) { + throw new Error("not a PublicProofInputs type"); + } + + return PublicProofInputs.reified().new({ + bytes: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.bytes), + }); + } + + static fromBcs(data: Uint8Array): PublicProofInputs { + return PublicProofInputs.fromFields(PublicProofInputs.bcs.parse(data)); + } + + toJSONField() { + return { + bytes: fieldToJSON>(`vector`, this.bytes), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): PublicProofInputs { + return PublicProofInputs.reified().new({ + bytes: decodeFromJSONField(reified.vector("u8"), field.bytes), + }); + } + + static fromJSON(json: Record): PublicProofInputs { + if (json.$typeName !== PublicProofInputs.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return PublicProofInputs.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): PublicProofInputs { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isPublicProofInputs(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a PublicProofInputs object`); + } + return PublicProofInputs.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): PublicProofInputs { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isPublicProofInputs(data.bcs.type)) { + throw new Error(`object at is not a PublicProofInputs object`); + } + + return PublicProofInputs.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return PublicProofInputs.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching PublicProofInputs object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isPublicProofInputs(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a PublicProofInputs object`); + } + + return PublicProofInputs.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/sui/group-ops/functions.ts b/src/services/models/sui/sui/group-ops/functions.ts new file mode 100644 index 00000000..7d583fd1 --- /dev/null +++ b/src/services/models/sui/sui/group-ops/functions.ts @@ -0,0 +1,312 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure, vector } from "../../_framework/util"; +import { Element } from "./structs"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface AddArgs { + type: number | TransactionArgument; + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function add(tx: Transaction, typeArg: string, args: AddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::add`, + typeArguments: [typeArg], + arguments: [pure(tx, args.type, `u8`), obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export interface DivArgs { + type: number | TransactionArgument; + scalar: TransactionObjectInput; + e: TransactionObjectInput; +} + +export function div(tx: Transaction, typeArgs: [string, string], args: DivArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::div`, + typeArguments: typeArgs, + arguments: [pure(tx, args.type, `u8`), obj(tx, args.scalar), obj(tx, args.e)], + }); +} + +export interface MulArgs { + type: number | TransactionArgument; + scalar: TransactionObjectInput; + e: TransactionObjectInput; +} + +export function mul(tx: Transaction, typeArgs: [string, string], args: MulArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::mul`, + typeArguments: typeArgs, + arguments: [pure(tx, args.type, `u8`), obj(tx, args.scalar), obj(tx, args.e)], + }); +} + +export interface SubArgs { + type: number | TransactionArgument; + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function sub(tx: Transaction, typeArg: string, args: SubArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::sub`, + typeArguments: [typeArg], + arguments: [pure(tx, args.type, `u8`), obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export function bytes(tx: Transaction, typeArg: string, e: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::bytes`, + typeArguments: [typeArg], + arguments: [obj(tx, e)], + }); +} + +export interface FromBytesArgs { + type: number | TransactionArgument; + bytes: Array | TransactionArgument; + isTrusted: boolean | TransactionArgument; +} + +export function fromBytes(tx: Transaction, typeArg: string, args: FromBytesArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::from_bytes`, + typeArguments: [typeArg], + arguments: [pure(tx, args.type, `u8`), pure(tx, args.bytes, `vector`), pure(tx, args.isTrusted, `bool`)], + }); +} + +export interface InternalAddArgs { + type: number | TransactionArgument; + e1: Array | TransactionArgument; + e2: Array | TransactionArgument; +} + +export function internalAdd(tx: Transaction, args: InternalAddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::internal_add`, + arguments: [pure(tx, args.type, `u8`), pure(tx, args.e1, `vector`), pure(tx, args.e2, `vector`)], + }); +} + +export interface ConvertArgs { + fromType: number | TransactionArgument; + toType: number | TransactionArgument; + e: TransactionObjectInput; +} + +export function convert(tx: Transaction, typeArgs: [string, string], args: ConvertArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::convert`, + typeArguments: typeArgs, + arguments: [pure(tx, args.fromType, `u8`), pure(tx, args.toType, `u8`), obj(tx, args.e)], + }); +} + +export interface EqualArgs { + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function equal(tx: Transaction, typeArg: string, args: EqualArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::equal`, + typeArguments: [typeArg], + arguments: [obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export interface HashToArgs { + type: number | TransactionArgument; + m: Array | TransactionArgument; +} + +export function hashTo(tx: Transaction, typeArg: string, args: HashToArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::hash_to`, + typeArguments: [typeArg], + arguments: [pure(tx, args.type, `u8`), pure(tx, args.m, `vector`)], + }); +} + +export interface InternalConvertArgs { + fromType: number | TransactionArgument; + toType: number | TransactionArgument; + e: Array | TransactionArgument; +} + +export function internalConvert(tx: Transaction, args: InternalConvertArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::internal_convert`, + arguments: [pure(tx, args.fromType, `u8`), pure(tx, args.toType, `u8`), pure(tx, args.e, `vector`)], + }); +} + +export interface InternalDivArgs { + type: number | TransactionArgument; + e1: Array | TransactionArgument; + e2: Array | TransactionArgument; +} + +export function internalDiv(tx: Transaction, args: InternalDivArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::internal_div`, + arguments: [pure(tx, args.type, `u8`), pure(tx, args.e1, `vector`), pure(tx, args.e2, `vector`)], + }); +} + +export interface InternalHashToArgs { + type: number | TransactionArgument; + m: Array | TransactionArgument; +} + +export function internalHashTo(tx: Transaction, args: InternalHashToArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::internal_hash_to`, + arguments: [pure(tx, args.type, `u8`), pure(tx, args.m, `vector`)], + }); +} + +export interface InternalMulArgs { + type: number | TransactionArgument; + e1: Array | TransactionArgument; + e2: Array | TransactionArgument; +} + +export function internalMul(tx: Transaction, args: InternalMulArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::internal_mul`, + arguments: [pure(tx, args.type, `u8`), pure(tx, args.e1, `vector`), pure(tx, args.e2, `vector`)], + }); +} + +export interface InternalMultiScalarMulArgs { + type: number | TransactionArgument; + scalars: Array | TransactionArgument; + elements: Array | TransactionArgument; +} + +export function internalMultiScalarMul(tx: Transaction, args: InternalMultiScalarMulArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::internal_multi_scalar_mul`, + arguments: [pure(tx, args.type, `u8`), pure(tx, args.scalars, `vector`), pure(tx, args.elements, `vector`)], + }); +} + +export interface InternalPairingArgs { + type: number | TransactionArgument; + e1: Array | TransactionArgument; + e2: Array | TransactionArgument; +} + +export function internalPairing(tx: Transaction, args: InternalPairingArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::internal_pairing`, + arguments: [pure(tx, args.type, `u8`), pure(tx, args.e1, `vector`), pure(tx, args.e2, `vector`)], + }); +} + +export interface InternalSubArgs { + type: number | TransactionArgument; + e1: Array | TransactionArgument; + e2: Array | TransactionArgument; +} + +export function internalSub(tx: Transaction, args: InternalSubArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::internal_sub`, + arguments: [pure(tx, args.type, `u8`), pure(tx, args.e1, `vector`), pure(tx, args.e2, `vector`)], + }); +} + +export interface InternalSumArgs { + type: number | TransactionArgument; + e: Array | TransactionArgument> | TransactionArgument; +} + +export function internalSum(tx: Transaction, args: InternalSumArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::internal_sum`, + arguments: [pure(tx, args.type, `u8`), pure(tx, args.e, `vector>`)], + }); +} + +export interface InternalValidateArgs { + type: number | TransactionArgument; + bytes: Array | TransactionArgument; +} + +export function internalValidate(tx: Transaction, args: InternalValidateArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::internal_validate`, + arguments: [pure(tx, args.type, `u8`), pure(tx, args.bytes, `vector`)], + }); +} + +export interface MultiScalarMultiplicationArgs { + type: number | TransactionArgument; + scalars: Array | TransactionArgument; + elements: Array | TransactionArgument; +} + +export function multiScalarMultiplication( + tx: Transaction, + typeArgs: [string, string], + args: MultiScalarMultiplicationArgs +) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::multi_scalar_multiplication`, + typeArguments: typeArgs, + arguments: [ + pure(tx, args.type, `u8`), + vector(tx, `${Element.$typeName}<${typeArgs[0]}>`, args.scalars), + vector(tx, `${Element.$typeName}<${typeArgs[1]}>`, args.elements), + ], + }); +} + +export interface PairingArgs { + type: number | TransactionArgument; + e1: TransactionObjectInput; + e2: TransactionObjectInput; +} + +export function pairing(tx: Transaction, typeArgs: [string, string, string], args: PairingArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::pairing`, + typeArguments: typeArgs, + arguments: [pure(tx, args.type, `u8`), obj(tx, args.e1), obj(tx, args.e2)], + }); +} + +export interface SetAsPrefixArgs { + x: bigint | TransactionArgument; + bigEndian: boolean | TransactionArgument; + buffer: Array | TransactionArgument; +} + +export function setAsPrefix(tx: Transaction, args: SetAsPrefixArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::set_as_prefix`, + arguments: [pure(tx, args.x, `u64`), pure(tx, args.bigEndian, `bool`), pure(tx, args.buffer, `vector`)], + }); +} + +export interface SumArgs { + type: number | TransactionArgument; + terms: Array | TransactionArgument; +} + +export function sum(tx: Transaction, typeArg: string, args: SumArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::group_ops::sum`, + typeArguments: [typeArg], + arguments: [pure(tx, args.type, `u8`), vector(tx, `${Element.$typeName}<${typeArg}>`, args.terms)], + }); +} diff --git a/src/services/models/sui/sui/group-ops/structs.ts b/src/services/models/sui/sui/group-ops/structs.ts new file mode 100644 index 00000000..dfe10e2c --- /dev/null +++ b/src/services/models/sui/sui/group-ops/structs.ts @@ -0,0 +1,228 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + fieldToJSON, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { Vector } from "../../_framework/vector"; +import { PKG_V26 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Element =============================== */ + +export function isElement(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::group_ops::Element` + "<"); +} + +export interface ElementFields { + bytes: ToField>; +} + +export type ElementReified = Reified, ElementFields>; + +export class Element implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::group_ops::Element`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = Element.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = Element.$isPhantom; + + readonly bytes: ToField>; + + private constructor(typeArgs: [PhantomToTypeStr], fields: ElementFields) { + this.$fullTypeName = composeSuiType(Element.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.bytes = fields.bytes; + } + + static reified>(T: T): ElementReified> { + return { + typeName: Element.$typeName, + fullTypeName: composeSuiType(Element.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: Element.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => Element.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Element.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => Element.fromBcs(T, data), + bcs: Element.bcs, + fromJSONField: (field: any) => Element.fromJSONField(T, field), + fromJSON: (json: Record) => Element.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => Element.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => Element.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => Element.fetch(client, T, id), + new: (fields: ElementFields>) => { + return new Element([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Element.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(Element.reified(T)); + } + static get p() { + return Element.phantom; + } + + static get bcs() { + return bcs.struct("Element", { + bytes: bcs.vector(bcs.u8()), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): Element> { + return Element.reified(typeArg).new({ + bytes: decodeFromFields(reified.vector("u8"), fields.bytes), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): Element> { + if (!isElement(item.type)) { + throw new Error("not a Element type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Element.reified(typeArg).new({ + bytes: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.bytes), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): Element> { + return Element.fromFields(typeArg, Element.bcs.parse(data)); + } + + toJSONField() { + return { + bytes: fieldToJSON>(`vector`, this.bytes), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): Element> { + return Element.reified(typeArg).new({ + bytes: decodeFromJSONField(reified.vector("u8"), field.bytes), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): Element> { + if (json.$typeName !== Element.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Element.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Element.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): Element> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isElement(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Element object`); + } + return Element.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): Element> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isElement(data.bcs.type)) { + throw new Error(`object at is not a Element object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Element.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Element.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Element object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isElement(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Element object`); + } + + return Element.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/sui/hash/functions.ts b/src/services/models/sui/sui/hash/functions.ts new file mode 100644 index 00000000..3dc03f52 --- /dev/null +++ b/src/services/models/sui/sui/hash/functions.ts @@ -0,0 +1,18 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { pure } from "../../_framework/util"; +import { Transaction, TransactionArgument } from "@mysten/sui/transactions"; + +export function blake2b256(tx: Transaction, data: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::hash::blake2b256`, + arguments: [pure(tx, data, `vector`)], + }); +} + +export function keccak256(tx: Transaction, data: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::hash::keccak256`, + arguments: [pure(tx, data, `vector`)], + }); +} diff --git a/src/services/models/sui/sui/hex/functions.ts b/src/services/models/sui/sui/hex/functions.ts new file mode 100644 index 00000000..46a758c7 --- /dev/null +++ b/src/services/models/sui/sui/hex/functions.ts @@ -0,0 +1,25 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { pure } from "../../_framework/util"; +import { Transaction, TransactionArgument } from "@mysten/sui/transactions"; + +export function decode(tx: Transaction, hex: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::hex::decode`, + arguments: [pure(tx, hex, `vector`)], + }); +} + +export function decodeByte(tx: Transaction, hex: number | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::hex::decode_byte`, + arguments: [pure(tx, hex, `u8`)], + }); +} + +export function encode(tx: Transaction, bytes: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::hex::encode`, + arguments: [pure(tx, bytes, `vector`)], + }); +} diff --git a/src/services/models/sui/sui/hmac/functions.ts b/src/services/models/sui/sui/hmac/functions.ts new file mode 100644 index 00000000..ef527cfc --- /dev/null +++ b/src/services/models/sui/sui/hmac/functions.ts @@ -0,0 +1,16 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { pure } from "../../_framework/util"; +import { Transaction, TransactionArgument } from "@mysten/sui/transactions"; + +export interface HmacSha3256Args { + key: Array | TransactionArgument; + msg: Array | TransactionArgument; +} + +export function hmacSha3256(tx: Transaction, args: HmacSha3256Args) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::hmac::hmac_sha3_256`, + arguments: [pure(tx, args.key, `vector`), pure(tx, args.msg, `vector`)], + }); +} diff --git a/src/services/models/sui/sui/index.ts b/src/services/models/sui/sui/index.ts new file mode 100644 index 00000000..38d5da70 --- /dev/null +++ b/src/services/models/sui/sui/index.ts @@ -0,0 +1,4 @@ +// @ts-nocheck +export const PACKAGE_ID = "0x2"; +export const PUBLISHED_AT = "0x2"; +export const PKG_V26 = "0x2"; diff --git a/src/services/models/sui/sui/init.ts b/src/services/models/sui/sui/init.ts new file mode 100644 index 00000000..ae0509f7 --- /dev/null +++ b/src/services/models/sui/sui/init.ts @@ -0,0 +1,138 @@ +// @ts-nocheck +import * as authenticatorState from "./authenticator-state/structs"; +import * as bag from "./bag/structs"; +import * as balance from "./balance/structs"; +import * as bcs from "./bcs/structs"; +import * as bls12381 from "./bls12381/structs"; +import * as borrow from "./borrow/structs"; +import * as clock from "./clock/structs"; +import * as coin from "./coin/structs"; +import * as config from "./config/structs"; +import * as denyList from "./deny-list/structs"; +import * as display from "./display/structs"; +import * as dynamicField from "./dynamic-field/structs"; +import * as dynamicObjectField from "./dynamic-object-field/structs"; +import * as groth16 from "./groth16/structs"; +import * as groupOps from "./group-ops/structs"; +import * as kioskExtension from "./kiosk-extension/structs"; +import * as kiosk from "./kiosk/structs"; +import * as linkedTable from "./linked-table/structs"; +import * as objectBag from "./object-bag/structs"; +import * as objectTable from "./object-table/structs"; +import * as object from "./object/structs"; +import * as package_ from "./package/structs"; +import * as priorityQueue from "./priority-queue/structs"; +import * as random from "./random/structs"; +import * as sui from "./sui/structs"; +import * as tableVec from "./table-vec/structs"; +import * as table from "./table/structs"; +import * as token from "./token/structs"; +import * as transferPolicy from "./transfer-policy/structs"; +import * as transfer from "./transfer/structs"; +import * as txContext from "./tx-context/structs"; +import * as url from "./url/structs"; +import * as vecMap from "./vec-map/structs"; +import * as vecSet from "./vec-set/structs"; +import * as versioned from "./versioned/structs"; +import * as zkloginVerifiedId from "./zklogin-verified-id/structs"; +import * as zkloginVerifiedIssuer from "./zklogin-verified-issuer/structs"; +import { StructClassLoader } from "../_framework/loader"; + +export function registerClasses(loader: StructClassLoader) { + loader.register(txContext.TxContext); + loader.register(object.ID); + loader.register(object.UID); + loader.register(bcs.BCS); + loader.register(url.Url); + loader.register(transfer.Receiving); + loader.register(vecSet.VecSet); + loader.register(dynamicField.Field); + loader.register(table.Table); + loader.register(dynamicObjectField.Wrapper); + loader.register(config.Config); + loader.register(config.Setting); + loader.register(config.SettingData); + loader.register(bag.Bag); + loader.register(denyList.AddressKey); + loader.register(denyList.ConfigKey); + loader.register(denyList.ConfigWriteCap); + loader.register(denyList.DenyList); + loader.register(denyList.GlobalPauseKey); + loader.register(denyList.PerTypeConfigCreated); + loader.register(denyList.PerTypeList); + loader.register(balance.Balance); + loader.register(balance.Supply); + loader.register(coin.Coin); + loader.register(coin.CoinMetadata); + loader.register(coin.CurrencyCreated); + loader.register(coin.DenyCap); + loader.register(coin.DenyCapV2); + loader.register(coin.RegulatedCoinMetadata); + loader.register(coin.TreasuryCap); + loader.register(sui.SUI); + loader.register(package_.Publisher); + loader.register(package_.UpgradeCap); + loader.register(package_.UpgradeReceipt); + loader.register(package_.UpgradeTicket); + loader.register(clock.Clock); + loader.register(authenticatorState.ActiveJwk); + loader.register(authenticatorState.AuthenticatorState); + loader.register(authenticatorState.AuthenticatorStateInner); + loader.register(authenticatorState.JWK); + loader.register(authenticatorState.JwkId); + loader.register(groupOps.Element); + loader.register(bls12381.G1); + loader.register(bls12381.G2); + loader.register(bls12381.GT); + loader.register(bls12381.Scalar); + loader.register(bls12381.UncompressedG1); + loader.register(borrow.Borrow); + loader.register(borrow.Referent); + loader.register(vecMap.Entry); + loader.register(vecMap.VecMap); + loader.register(display.Display); + loader.register(display.DisplayCreated); + loader.register(display.VersionUpdated); + loader.register(groth16.Curve); + loader.register(groth16.PreparedVerifyingKey); + loader.register(groth16.ProofPoints); + loader.register(groth16.PublicProofInputs); + loader.register(transferPolicy.RuleKey); + loader.register(transferPolicy.TransferPolicy); + loader.register(transferPolicy.TransferPolicyCap); + loader.register(transferPolicy.TransferPolicyCreated); + loader.register(transferPolicy.TransferPolicyDestroyed); + loader.register(transferPolicy.TransferRequest); + loader.register(kiosk.Borrow); + loader.register(kiosk.Item); + loader.register(kiosk.ItemDelisted); + loader.register(kiosk.ItemListed); + loader.register(kiosk.ItemPurchased); + loader.register(kiosk.Kiosk); + loader.register(kiosk.KioskOwnerCap); + loader.register(kiosk.Listing); + loader.register(kiosk.Lock); + loader.register(kiosk.PurchaseCap); + loader.register(kioskExtension.Extension); + loader.register(kioskExtension.ExtensionKey); + loader.register(linkedTable.LinkedTable); + loader.register(linkedTable.Node); + loader.register(objectBag.ObjectBag); + loader.register(objectTable.ObjectTable); + loader.register(priorityQueue.Entry); + loader.register(priorityQueue.PriorityQueue); + loader.register(versioned.VersionChangeCap); + loader.register(versioned.Versioned); + loader.register(random.Random); + loader.register(random.RandomGenerator); + loader.register(random.RandomInner); + loader.register(tableVec.TableVec); + loader.register(token.RuleKey); + loader.register(token.ActionRequest); + loader.register(token.Token); + loader.register(token.TokenPolicy); + loader.register(token.TokenPolicyCap); + loader.register(token.TokenPolicyCreated); + loader.register(zkloginVerifiedId.VerifiedID); + loader.register(zkloginVerifiedIssuer.VerifiedIssuer); +} diff --git a/src/services/models/sui/sui/kiosk-extension/functions.ts b/src/services/models/sui/sui/kiosk-extension/functions.ts new file mode 100644 index 00000000..b2d88c94 --- /dev/null +++ b/src/services/models/sui/sui/kiosk-extension/functions.ts @@ -0,0 +1,177 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface AddArgs { + ext: GenericArg; + self: TransactionObjectInput; + cap: TransactionObjectInput; + permissions: bigint | TransactionArgument; +} + +export function add(tx: Transaction, typeArg: string, args: AddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk_extension::add`, + typeArguments: [typeArg], + arguments: [ + generic(tx, `${typeArg}`, args.ext), + obj(tx, args.self), + obj(tx, args.cap), + pure(tx, args.permissions, `u128`), + ], + }); +} + +export interface RemoveArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; +} + +export function remove(tx: Transaction, typeArg: string, args: RemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk_extension::remove`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.cap)], + }); +} + +export interface LockArgs { + ext: GenericArg; + self: TransactionObjectInput; + item: GenericArg; + policy: TransactionObjectInput; +} + +export function lock(tx: Transaction, typeArgs: [string, string], args: LockArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk_extension::lock`, + typeArguments: typeArgs, + arguments: [ + generic(tx, `${typeArgs[0]}`, args.ext), + obj(tx, args.self), + generic(tx, `${typeArgs[1]}`, args.item), + obj(tx, args.policy), + ], + }); +} + +export interface PlaceArgs { + ext: GenericArg; + self: TransactionObjectInput; + item: GenericArg; + policy: TransactionObjectInput; +} + +export function place(tx: Transaction, typeArgs: [string, string], args: PlaceArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk_extension::place`, + typeArguments: typeArgs, + arguments: [ + generic(tx, `${typeArgs[0]}`, args.ext), + obj(tx, args.self), + generic(tx, `${typeArgs[1]}`, args.item), + obj(tx, args.policy), + ], + }); +} + +export function canLock(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk_extension::can_lock`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function canPlace(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk_extension::can_place`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export interface DisableArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; +} + +export function disable(tx: Transaction, typeArg: string, args: DisableArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk_extension::disable`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.cap)], + }); +} + +export interface EnableArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; +} + +export function enable(tx: Transaction, typeArg: string, args: EnableArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk_extension::enable`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.cap)], + }); +} + +export function extension(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk_extension::extension`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function extensionMut(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk_extension::extension_mut`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function isEnabled(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk_extension::is_enabled`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function isInstalled(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk_extension::is_installed`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export interface StorageArgs { + ext: GenericArg; + self: TransactionObjectInput; +} + +export function storage(tx: Transaction, typeArg: string, args: StorageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk_extension::storage`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, args.ext), obj(tx, args.self)], + }); +} + +export interface StorageMutArgs { + ext: GenericArg; + self: TransactionObjectInput; +} + +export function storageMut(tx: Transaction, typeArg: string, args: StorageMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk_extension::storage_mut`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, args.ext), obj(tx, args.self)], + }); +} diff --git a/src/services/models/sui/sui/kiosk-extension/structs.ts b/src/services/models/sui/sui/kiosk-extension/structs.ts new file mode 100644 index 00000000..dbb2f70c --- /dev/null +++ b/src/services/models/sui/sui/kiosk-extension/structs.ts @@ -0,0 +1,407 @@ +// @ts-nocheck +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { Bag } from "../bag/structs"; +import { PKG_V26 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Extension =============================== */ + +export function isExtension(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::kiosk_extension::Extension`; +} + +export interface ExtensionFields { + storage: ToField; + permissions: ToField<"u128">; + isEnabled: ToField<"bool">; +} + +export type ExtensionReified = Reified; + +export class Extension implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::kiosk_extension::Extension`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Extension.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Extension.$isPhantom; + + readonly storage: ToField; + readonly permissions: ToField<"u128">; + readonly isEnabled: ToField<"bool">; + + private constructor(typeArgs: [], fields: ExtensionFields) { + this.$fullTypeName = composeSuiType(Extension.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.storage = fields.storage; + this.permissions = fields.permissions; + this.isEnabled = fields.isEnabled; + } + + static reified(): ExtensionReified { + return { + typeName: Extension.$typeName, + fullTypeName: composeSuiType(Extension.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Extension.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Extension.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Extension.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Extension.fromBcs(data), + bcs: Extension.bcs, + fromJSONField: (field: any) => Extension.fromJSONField(field), + fromJSON: (json: Record) => Extension.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Extension.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Extension.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Extension.fetch(client, id), + new: (fields: ExtensionFields) => { + return new Extension([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Extension.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Extension.reified()); + } + static get p() { + return Extension.phantom(); + } + + static get bcs() { + return bcs.struct("Extension", { + storage: Bag.bcs, + permissions: bcs.u128(), + is_enabled: bcs.bool(), + }); + } + + static fromFields(fields: Record): Extension { + return Extension.reified().new({ + storage: decodeFromFields(Bag.reified(), fields.storage), + permissions: decodeFromFields("u128", fields.permissions), + isEnabled: decodeFromFields("bool", fields.is_enabled), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Extension { + if (!isExtension(item.type)) { + throw new Error("not a Extension type"); + } + + return Extension.reified().new({ + storage: decodeFromFieldsWithTypes(Bag.reified(), item.fields.storage), + permissions: decodeFromFieldsWithTypes("u128", item.fields.permissions), + isEnabled: decodeFromFieldsWithTypes("bool", item.fields.is_enabled), + }); + } + + static fromBcs(data: Uint8Array): Extension { + return Extension.fromFields(Extension.bcs.parse(data)); + } + + toJSONField() { + return { + storage: this.storage.toJSONField(), + permissions: this.permissions.toString(), + isEnabled: this.isEnabled, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Extension { + return Extension.reified().new({ + storage: decodeFromJSONField(Bag.reified(), field.storage), + permissions: decodeFromJSONField("u128", field.permissions), + isEnabled: decodeFromJSONField("bool", field.isEnabled), + }); + } + + static fromJSON(json: Record): Extension { + if (json.$typeName !== Extension.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Extension.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Extension { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isExtension(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Extension object`); + } + return Extension.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Extension { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isExtension(data.bcs.type)) { + throw new Error(`object at is not a Extension object`); + } + + return Extension.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Extension.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Extension object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isExtension(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Extension object`); + } + + return Extension.fromSuiObjectData(res.data); + } +} + +/* ============================== ExtensionKey =============================== */ + +export function isExtensionKey(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::kiosk_extension::ExtensionKey` + "<"); +} + +export interface ExtensionKeyFields { + dummyField: ToField<"bool">; +} + +export type ExtensionKeyReified = Reified, ExtensionKeyFields>; + +export class ExtensionKey implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::kiosk_extension::ExtensionKey`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = ExtensionKey.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = ExtensionKey.$isPhantom; + + readonly dummyField: ToField<"bool">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: ExtensionKeyFields) { + this.$fullTypeName = composeSuiType(ExtensionKey.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.dummyField = fields.dummyField; + } + + static reified>( + Ext: Ext + ): ExtensionKeyReified> { + return { + typeName: ExtensionKey.$typeName, + fullTypeName: composeSuiType(ExtensionKey.$typeName, ...[extractType(Ext)]) as string, + typeArgs: [extractType(Ext)] as [PhantomToTypeStr>], + isPhantom: ExtensionKey.$isPhantom, + reifiedTypeArgs: [Ext], + fromFields: (fields: Record) => ExtensionKey.fromFields(Ext, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => ExtensionKey.fromFieldsWithTypes(Ext, item), + fromBcs: (data: Uint8Array) => ExtensionKey.fromBcs(Ext, data), + bcs: ExtensionKey.bcs, + fromJSONField: (field: any) => ExtensionKey.fromJSONField(Ext, field), + fromJSON: (json: Record) => ExtensionKey.fromJSON(Ext, json), + fromSuiParsedData: (content: SuiParsedData) => ExtensionKey.fromSuiParsedData(Ext, content), + fromSuiObjectData: (content: SuiObjectData) => ExtensionKey.fromSuiObjectData(Ext, content), + fetch: async (client: SuiClient, id: string) => ExtensionKey.fetch(client, Ext, id), + new: (fields: ExtensionKeyFields>) => { + return new ExtensionKey([extractType(Ext)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return ExtensionKey.reified; + } + + static phantom>( + Ext: Ext + ): PhantomReified>>> { + return phantom(ExtensionKey.reified(Ext)); + } + static get p() { + return ExtensionKey.phantom; + } + + static get bcs() { + return bcs.struct("ExtensionKey", { + dummy_field: bcs.bool(), + }); + } + + static fromFields>( + typeArg: Ext, + fields: Record + ): ExtensionKey> { + return ExtensionKey.reified(typeArg).new({ + dummyField: decodeFromFields("bool", fields.dummy_field), + }); + } + + static fromFieldsWithTypes>( + typeArg: Ext, + item: FieldsWithTypes + ): ExtensionKey> { + if (!isExtensionKey(item.type)) { + throw new Error("not a ExtensionKey type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return ExtensionKey.reified(typeArg).new({ + dummyField: decodeFromFieldsWithTypes("bool", item.fields.dummy_field), + }); + } + + static fromBcs>( + typeArg: Ext, + data: Uint8Array + ): ExtensionKey> { + return ExtensionKey.fromFields(typeArg, ExtensionKey.bcs.parse(data)); + } + + toJSONField() { + return { + dummyField: this.dummyField, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: Ext, + field: any + ): ExtensionKey> { + return ExtensionKey.reified(typeArg).new({ + dummyField: decodeFromJSONField("bool", field.dummyField), + }); + } + + static fromJSON>( + typeArg: Ext, + json: Record + ): ExtensionKey> { + if (json.$typeName !== ExtensionKey.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(ExtensionKey.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return ExtensionKey.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: Ext, + content: SuiParsedData + ): ExtensionKey> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isExtensionKey(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a ExtensionKey object`); + } + return ExtensionKey.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: Ext, + data: SuiObjectData + ): ExtensionKey> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isExtensionKey(data.bcs.type)) { + throw new Error(`object at is not a ExtensionKey object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return ExtensionKey.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return ExtensionKey.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: Ext, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching ExtensionKey object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isExtensionKey(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a ExtensionKey object`); + } + + return ExtensionKey.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/sui/kiosk/functions.ts b/src/services/models/sui/sui/kiosk/functions.ts new file mode 100644 index 00000000..cc02fad2 --- /dev/null +++ b/src/services/models/sui/sui/kiosk/functions.ts @@ -0,0 +1,490 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { Option } from "../../_dependencies/source/0x1/option/structs"; +import { GenericArg, generic, obj, pure } from "../../_framework/util"; +import { ID } from "../object/structs"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface BorrowArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; + id: string | TransactionArgument; +} + +export function borrow(tx: Transaction, typeArg: string, args: BorrowArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::borrow`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.cap), pure(tx, args.id, `${ID.$typeName}`)], + }); +} + +export interface BorrowMutArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; + id: string | TransactionArgument; +} + +export function borrowMut(tx: Transaction, typeArg: string, args: BorrowMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::borrow_mut`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.cap), pure(tx, args.id, `${ID.$typeName}`)], + }); +} + +export function default_(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::default`, + arguments: [], + }); +} + +export function new_(tx: Transaction) { + return tx.moveCall({ target: `${PUBLISHED_AT}::kiosk::new`, arguments: [] }); +} + +export function uid(tx: Transaction, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::uid`, + arguments: [obj(tx, self)], + }); +} + +export interface TakeArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; + id: string | TransactionArgument; +} + +export function take(tx: Transaction, typeArg: string, args: TakeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::take`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.cap), pure(tx, args.id, `${ID.$typeName}`)], + }); +} + +export function owner(tx: Transaction, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::owner`, + arguments: [obj(tx, self)], + }); +} + +export interface ListArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; + id: string | TransactionArgument; + price: bigint | TransactionArgument; +} + +export function list(tx: Transaction, typeArg: string, args: ListArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::list`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.self), + obj(tx, args.cap), + pure(tx, args.id, `${ID.$typeName}`), + pure(tx, args.price, `u64`), + ], + }); +} + +export interface WithdrawArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; + amount: bigint | TransactionArgument | TransactionArgument | null; +} + +export function withdraw(tx: Transaction, args: WithdrawArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::withdraw`, + arguments: [obj(tx, args.self), obj(tx, args.cap), pure(tx, args.amount, `${Option.$typeName}`)], + }); +} + +export interface UidMutAsOwnerArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; +} + +export function uidMutAsOwner(tx: Transaction, args: UidMutAsOwnerArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::uid_mut_as_owner`, + arguments: [obj(tx, args.self), obj(tx, args.cap)], + }); +} + +export interface BorrowValArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; + id: string | TransactionArgument; +} + +export function borrowVal(tx: Transaction, typeArg: string, args: BorrowValArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::borrow_val`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.cap), pure(tx, args.id, `${ID.$typeName}`)], + }); +} + +export interface CloseAndWithdrawArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; +} + +export function closeAndWithdraw(tx: Transaction, args: CloseAndWithdrawArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::close_and_withdraw`, + arguments: [obj(tx, args.self), obj(tx, args.cap)], + }); +} + +export interface DelistArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; + id: string | TransactionArgument; +} + +export function delist(tx: Transaction, typeArg: string, args: DelistArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::delist`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.cap), pure(tx, args.id, `${ID.$typeName}`)], + }); +} + +export interface HasAccessArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; +} + +export function hasAccess(tx: Transaction, args: HasAccessArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::has_access`, + arguments: [obj(tx, args.self), obj(tx, args.cap)], + }); +} + +export interface HasItemArgs { + self: TransactionObjectInput; + id: string | TransactionArgument; +} + +export function hasItem(tx: Transaction, args: HasItemArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::has_item`, + arguments: [obj(tx, args.self), pure(tx, args.id, `${ID.$typeName}`)], + }); +} + +export interface HasItemWithTypeArgs { + self: TransactionObjectInput; + id: string | TransactionArgument; +} + +export function hasItemWithType(tx: Transaction, typeArg: string, args: HasItemWithTypeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::has_item_with_type`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), pure(tx, args.id, `${ID.$typeName}`)], + }); +} + +export interface IsListedArgs { + self: TransactionObjectInput; + id: string | TransactionArgument; +} + +export function isListed(tx: Transaction, args: IsListedArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::is_listed`, + arguments: [obj(tx, args.self), pure(tx, args.id, `${ID.$typeName}`)], + }); +} + +export interface IsListedExclusivelyArgs { + self: TransactionObjectInput; + id: string | TransactionArgument; +} + +export function isListedExclusively(tx: Transaction, args: IsListedExclusivelyArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::is_listed_exclusively`, + arguments: [obj(tx, args.self), pure(tx, args.id, `${ID.$typeName}`)], + }); +} + +export interface IsLockedArgs { + self: TransactionObjectInput; + id: string | TransactionArgument; +} + +export function isLocked(tx: Transaction, args: IsLockedArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::is_locked`, + arguments: [obj(tx, args.self), pure(tx, args.id, `${ID.$typeName}`)], + }); +} + +export function itemCount(tx: Transaction, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::item_count`, + arguments: [obj(tx, self)], + }); +} + +export function kioskOwnerCapFor(tx: Transaction, cap: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::kiosk_owner_cap_for`, + arguments: [obj(tx, cap)], + }); +} + +export interface ListWithPurchaseCapArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; + id: string | TransactionArgument; + minPrice: bigint | TransactionArgument; +} + +export function listWithPurchaseCap(tx: Transaction, typeArg: string, args: ListWithPurchaseCapArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::list_with_purchase_cap`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.self), + obj(tx, args.cap), + pure(tx, args.id, `${ID.$typeName}`), + pure(tx, args.minPrice, `u64`), + ], + }); +} + +export interface LockArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; + policy: TransactionObjectInput; + item: GenericArg; +} + +export function lock(tx: Transaction, typeArg: string, args: LockArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::lock`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.cap), obj(tx, args.policy), generic(tx, `${typeArg}`, args.item)], + }); +} + +export interface LockInternalArgs { + self: TransactionObjectInput; + item: GenericArg; +} + +export function lockInternal(tx: Transaction, typeArg: string, args: LockInternalArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::lock_internal`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), generic(tx, `${typeArg}`, args.item)], + }); +} + +export interface PlaceArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; + item: GenericArg; +} + +export function place(tx: Transaction, typeArg: string, args: PlaceArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::place`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.cap), generic(tx, `${typeArg}`, args.item)], + }); +} + +export interface PlaceAndListArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; + item: GenericArg; + price: bigint | TransactionArgument; +} + +export function placeAndList(tx: Transaction, typeArg: string, args: PlaceAndListArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::place_and_list`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.self), + obj(tx, args.cap), + generic(tx, `${typeArg}`, args.item), + pure(tx, args.price, `u64`), + ], + }); +} + +export interface PlaceInternalArgs { + self: TransactionObjectInput; + item: GenericArg; +} + +export function placeInternal(tx: Transaction, typeArg: string, args: PlaceInternalArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::place_internal`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), generic(tx, `${typeArg}`, args.item)], + }); +} + +export function profitsAmount(tx: Transaction, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::profits_amount`, + arguments: [obj(tx, self)], + }); +} + +export interface ProfitsMutArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; +} + +export function profitsMut(tx: Transaction, args: ProfitsMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::profits_mut`, + arguments: [obj(tx, args.self), obj(tx, args.cap)], + }); +} + +export interface PurchaseArgs { + self: TransactionObjectInput; + id: string | TransactionArgument; + payment: TransactionObjectInput; +} + +export function purchase(tx: Transaction, typeArg: string, args: PurchaseArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::purchase`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), pure(tx, args.id, `${ID.$typeName}`), obj(tx, args.payment)], + }); +} + +export function purchaseCapItem(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::purchase_cap_item`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function purchaseCapKiosk(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::purchase_cap_kiosk`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function purchaseCapMinPrice(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::purchase_cap_min_price`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export interface PurchaseWithCapArgs { + self: TransactionObjectInput; + purchaseCap: TransactionObjectInput; + payment: TransactionObjectInput; +} + +export function purchaseWithCap(tx: Transaction, typeArg: string, args: PurchaseWithCapArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::purchase_with_cap`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.purchaseCap), obj(tx, args.payment)], + }); +} + +export interface ReturnPurchaseCapArgs { + self: TransactionObjectInput; + purchaseCap: TransactionObjectInput; +} + +export function returnPurchaseCap(tx: Transaction, typeArg: string, args: ReturnPurchaseCapArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::return_purchase_cap`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.purchaseCap)], + }); +} + +export interface ReturnValArgs { + self: TransactionObjectInput; + item: GenericArg; + borrow: TransactionObjectInput; +} + +export function returnVal(tx: Transaction, typeArg: string, args: ReturnValArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::return_val`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), generic(tx, `${typeArg}`, args.item), obj(tx, args.borrow)], + }); +} + +export interface SetAllowExtensionsArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; + allowExtensions: boolean | TransactionArgument; +} + +export function setAllowExtensions(tx: Transaction, args: SetAllowExtensionsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::set_allow_extensions`, + arguments: [obj(tx, args.self), obj(tx, args.cap), pure(tx, args.allowExtensions, `bool`)], + }); +} + +export interface SetOwnerArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; +} + +export function setOwner(tx: Transaction, args: SetOwnerArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::set_owner`, + arguments: [obj(tx, args.self), obj(tx, args.cap)], + }); +} + +export interface SetOwnerCustomArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; + owner: string | TransactionArgument; +} + +export function setOwnerCustom(tx: Transaction, args: SetOwnerCustomArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::set_owner_custom`, + arguments: [obj(tx, args.self), obj(tx, args.cap), pure(tx, args.owner, `address`)], + }); +} + +export function uidMut(tx: Transaction, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::uid_mut`, + arguments: [obj(tx, self)], + }); +} + +export function uidMutInternal(tx: Transaction, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::kiosk::uid_mut_internal`, + arguments: [obj(tx, self)], + }); +} diff --git a/src/services/models/sui/sui/kiosk/structs.ts b/src/services/models/sui/sui/kiosk/structs.ts new file mode 100644 index 00000000..b5524bac --- /dev/null +++ b/src/services/models/sui/sui/kiosk/structs.ts @@ -0,0 +1,1939 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, + ToTypeStr as ToPhantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { Balance } from "../balance/structs"; +import { PKG_V26 } from "../index"; +import { ID, UID } from "../object/structs"; +import { SUI } from "../sui/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64, fromHEX, toHEX } from "@mysten/sui/utils"; + +/* ============================== Borrow =============================== */ + +export function isBorrow(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::kiosk::Borrow`; +} + +export interface BorrowFields { + kioskId: ToField; + itemId: ToField; +} + +export type BorrowReified = Reified; + +export class Borrow implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::kiosk::Borrow`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Borrow.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Borrow.$isPhantom; + + readonly kioskId: ToField; + readonly itemId: ToField; + + private constructor(typeArgs: [], fields: BorrowFields) { + this.$fullTypeName = composeSuiType(Borrow.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.kioskId = fields.kioskId; + this.itemId = fields.itemId; + } + + static reified(): BorrowReified { + return { + typeName: Borrow.$typeName, + fullTypeName: composeSuiType(Borrow.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Borrow.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Borrow.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Borrow.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Borrow.fromBcs(data), + bcs: Borrow.bcs, + fromJSONField: (field: any) => Borrow.fromJSONField(field), + fromJSON: (json: Record) => Borrow.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Borrow.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Borrow.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Borrow.fetch(client, id), + new: (fields: BorrowFields) => { + return new Borrow([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Borrow.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Borrow.reified()); + } + static get p() { + return Borrow.phantom(); + } + + static get bcs() { + return bcs.struct("Borrow", { + kiosk_id: ID.bcs, + item_id: ID.bcs, + }); + } + + static fromFields(fields: Record): Borrow { + return Borrow.reified().new({ + kioskId: decodeFromFields(ID.reified(), fields.kiosk_id), + itemId: decodeFromFields(ID.reified(), fields.item_id), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Borrow { + if (!isBorrow(item.type)) { + throw new Error("not a Borrow type"); + } + + return Borrow.reified().new({ + kioskId: decodeFromFieldsWithTypes(ID.reified(), item.fields.kiosk_id), + itemId: decodeFromFieldsWithTypes(ID.reified(), item.fields.item_id), + }); + } + + static fromBcs(data: Uint8Array): Borrow { + return Borrow.fromFields(Borrow.bcs.parse(data)); + } + + toJSONField() { + return { + kioskId: this.kioskId, + itemId: this.itemId, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Borrow { + return Borrow.reified().new({ + kioskId: decodeFromJSONField(ID.reified(), field.kioskId), + itemId: decodeFromJSONField(ID.reified(), field.itemId), + }); + } + + static fromJSON(json: Record): Borrow { + if (json.$typeName !== Borrow.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Borrow.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Borrow { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isBorrow(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Borrow object`); + } + return Borrow.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Borrow { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isBorrow(data.bcs.type)) { + throw new Error(`object at is not a Borrow object`); + } + + return Borrow.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Borrow.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Borrow object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isBorrow(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Borrow object`); + } + + return Borrow.fromSuiObjectData(res.data); + } +} + +/* ============================== Item =============================== */ + +export function isItem(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::kiosk::Item`; +} + +export interface ItemFields { + id: ToField; +} + +export type ItemReified = Reified; + +export class Item implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::kiosk::Item`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Item.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Item.$isPhantom; + + readonly id: ToField; + + private constructor(typeArgs: [], fields: ItemFields) { + this.$fullTypeName = composeSuiType(Item.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified(): ItemReified { + return { + typeName: Item.$typeName, + fullTypeName: composeSuiType(Item.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Item.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Item.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Item.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Item.fromBcs(data), + bcs: Item.bcs, + fromJSONField: (field: any) => Item.fromJSONField(field), + fromJSON: (json: Record) => Item.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Item.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Item.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Item.fetch(client, id), + new: (fields: ItemFields) => { + return new Item([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Item.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Item.reified()); + } + static get p() { + return Item.phantom(); + } + + static get bcs() { + return bcs.struct("Item", { + id: ID.bcs, + }); + } + + static fromFields(fields: Record): Item { + return Item.reified().new({ + id: decodeFromFields(ID.reified(), fields.id), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Item { + if (!isItem(item.type)) { + throw new Error("not a Item type"); + } + + return Item.reified().new({ + id: decodeFromFieldsWithTypes(ID.reified(), item.fields.id), + }); + } + + static fromBcs(data: Uint8Array): Item { + return Item.fromFields(Item.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Item { + return Item.reified().new({ + id: decodeFromJSONField(ID.reified(), field.id), + }); + } + + static fromJSON(json: Record): Item { + if (json.$typeName !== Item.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Item.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Item { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isItem(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Item object`); + } + return Item.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Item { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isItem(data.bcs.type)) { + throw new Error(`object at is not a Item object`); + } + + return Item.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Item.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Item object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isItem(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Item object`); + } + + return Item.fromSuiObjectData(res.data); + } +} + +/* ============================== ItemDelisted =============================== */ + +export function isItemDelisted(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::kiosk::ItemDelisted` + "<"); +} + +export interface ItemDelistedFields { + kiosk: ToField; + id: ToField; +} + +export type ItemDelistedReified = Reified, ItemDelistedFields>; + +export class ItemDelisted implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::kiosk::ItemDelisted`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = ItemDelisted.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = ItemDelisted.$isPhantom; + + readonly kiosk: ToField; + readonly id: ToField; + + private constructor(typeArgs: [PhantomToTypeStr], fields: ItemDelistedFields) { + this.$fullTypeName = composeSuiType(ItemDelisted.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.kiosk = fields.kiosk; + this.id = fields.id; + } + + static reified>(T: T): ItemDelistedReified> { + return { + typeName: ItemDelisted.$typeName, + fullTypeName: composeSuiType(ItemDelisted.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: ItemDelisted.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => ItemDelisted.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => ItemDelisted.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => ItemDelisted.fromBcs(T, data), + bcs: ItemDelisted.bcs, + fromJSONField: (field: any) => ItemDelisted.fromJSONField(T, field), + fromJSON: (json: Record) => ItemDelisted.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => ItemDelisted.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => ItemDelisted.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => ItemDelisted.fetch(client, T, id), + new: (fields: ItemDelistedFields>) => { + return new ItemDelisted([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return ItemDelisted.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(ItemDelisted.reified(T)); + } + static get p() { + return ItemDelisted.phantom; + } + + static get bcs() { + return bcs.struct("ItemDelisted", { + kiosk: ID.bcs, + id: ID.bcs, + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): ItemDelisted> { + return ItemDelisted.reified(typeArg).new({ + kiosk: decodeFromFields(ID.reified(), fields.kiosk), + id: decodeFromFields(ID.reified(), fields.id), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): ItemDelisted> { + if (!isItemDelisted(item.type)) { + throw new Error("not a ItemDelisted type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return ItemDelisted.reified(typeArg).new({ + kiosk: decodeFromFieldsWithTypes(ID.reified(), item.fields.kiosk), + id: decodeFromFieldsWithTypes(ID.reified(), item.fields.id), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): ItemDelisted> { + return ItemDelisted.fromFields(typeArg, ItemDelisted.bcs.parse(data)); + } + + toJSONField() { + return { + kiosk: this.kiosk, + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): ItemDelisted> { + return ItemDelisted.reified(typeArg).new({ + kiosk: decodeFromJSONField(ID.reified(), field.kiosk), + id: decodeFromJSONField(ID.reified(), field.id), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): ItemDelisted> { + if (json.$typeName !== ItemDelisted.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(ItemDelisted.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return ItemDelisted.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): ItemDelisted> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isItemDelisted(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a ItemDelisted object`); + } + return ItemDelisted.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): ItemDelisted> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isItemDelisted(data.bcs.type)) { + throw new Error(`object at is not a ItemDelisted object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return ItemDelisted.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return ItemDelisted.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching ItemDelisted object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isItemDelisted(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a ItemDelisted object`); + } + + return ItemDelisted.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== ItemListed =============================== */ + +export function isItemListed(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::kiosk::ItemListed` + "<"); +} + +export interface ItemListedFields { + kiosk: ToField; + id: ToField; + price: ToField<"u64">; +} + +export type ItemListedReified = Reified, ItemListedFields>; + +export class ItemListed implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::kiosk::ItemListed`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = ItemListed.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = ItemListed.$isPhantom; + + readonly kiosk: ToField; + readonly id: ToField; + readonly price: ToField<"u64">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: ItemListedFields) { + this.$fullTypeName = composeSuiType(ItemListed.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.kiosk = fields.kiosk; + this.id = fields.id; + this.price = fields.price; + } + + static reified>(T: T): ItemListedReified> { + return { + typeName: ItemListed.$typeName, + fullTypeName: composeSuiType(ItemListed.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: ItemListed.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => ItemListed.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => ItemListed.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => ItemListed.fromBcs(T, data), + bcs: ItemListed.bcs, + fromJSONField: (field: any) => ItemListed.fromJSONField(T, field), + fromJSON: (json: Record) => ItemListed.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => ItemListed.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => ItemListed.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => ItemListed.fetch(client, T, id), + new: (fields: ItemListedFields>) => { + return new ItemListed([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return ItemListed.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(ItemListed.reified(T)); + } + static get p() { + return ItemListed.phantom; + } + + static get bcs() { + return bcs.struct("ItemListed", { + kiosk: ID.bcs, + id: ID.bcs, + price: bcs.u64(), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): ItemListed> { + return ItemListed.reified(typeArg).new({ + kiosk: decodeFromFields(ID.reified(), fields.kiosk), + id: decodeFromFields(ID.reified(), fields.id), + price: decodeFromFields("u64", fields.price), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): ItemListed> { + if (!isItemListed(item.type)) { + throw new Error("not a ItemListed type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return ItemListed.reified(typeArg).new({ + kiosk: decodeFromFieldsWithTypes(ID.reified(), item.fields.kiosk), + id: decodeFromFieldsWithTypes(ID.reified(), item.fields.id), + price: decodeFromFieldsWithTypes("u64", item.fields.price), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): ItemListed> { + return ItemListed.fromFields(typeArg, ItemListed.bcs.parse(data)); + } + + toJSONField() { + return { + kiosk: this.kiosk, + id: this.id, + price: this.price.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): ItemListed> { + return ItemListed.reified(typeArg).new({ + kiosk: decodeFromJSONField(ID.reified(), field.kiosk), + id: decodeFromJSONField(ID.reified(), field.id), + price: decodeFromJSONField("u64", field.price), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): ItemListed> { + if (json.$typeName !== ItemListed.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(ItemListed.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return ItemListed.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): ItemListed> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isItemListed(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a ItemListed object`); + } + return ItemListed.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): ItemListed> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isItemListed(data.bcs.type)) { + throw new Error(`object at is not a ItemListed object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return ItemListed.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return ItemListed.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching ItemListed object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isItemListed(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a ItemListed object`); + } + + return ItemListed.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== ItemPurchased =============================== */ + +export function isItemPurchased(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::kiosk::ItemPurchased` + "<"); +} + +export interface ItemPurchasedFields { + kiosk: ToField; + id: ToField; + price: ToField<"u64">; +} + +export type ItemPurchasedReified = Reified, ItemPurchasedFields>; + +export class ItemPurchased implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::kiosk::ItemPurchased`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = ItemPurchased.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = ItemPurchased.$isPhantom; + + readonly kiosk: ToField; + readonly id: ToField; + readonly price: ToField<"u64">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: ItemPurchasedFields) { + this.$fullTypeName = composeSuiType(ItemPurchased.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.kiosk = fields.kiosk; + this.id = fields.id; + this.price = fields.price; + } + + static reified>(T: T): ItemPurchasedReified> { + return { + typeName: ItemPurchased.$typeName, + fullTypeName: composeSuiType(ItemPurchased.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: ItemPurchased.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => ItemPurchased.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => ItemPurchased.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => ItemPurchased.fromBcs(T, data), + bcs: ItemPurchased.bcs, + fromJSONField: (field: any) => ItemPurchased.fromJSONField(T, field), + fromJSON: (json: Record) => ItemPurchased.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => ItemPurchased.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => ItemPurchased.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => ItemPurchased.fetch(client, T, id), + new: (fields: ItemPurchasedFields>) => { + return new ItemPurchased([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return ItemPurchased.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(ItemPurchased.reified(T)); + } + static get p() { + return ItemPurchased.phantom; + } + + static get bcs() { + return bcs.struct("ItemPurchased", { + kiosk: ID.bcs, + id: ID.bcs, + price: bcs.u64(), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): ItemPurchased> { + return ItemPurchased.reified(typeArg).new({ + kiosk: decodeFromFields(ID.reified(), fields.kiosk), + id: decodeFromFields(ID.reified(), fields.id), + price: decodeFromFields("u64", fields.price), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): ItemPurchased> { + if (!isItemPurchased(item.type)) { + throw new Error("not a ItemPurchased type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return ItemPurchased.reified(typeArg).new({ + kiosk: decodeFromFieldsWithTypes(ID.reified(), item.fields.kiosk), + id: decodeFromFieldsWithTypes(ID.reified(), item.fields.id), + price: decodeFromFieldsWithTypes("u64", item.fields.price), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): ItemPurchased> { + return ItemPurchased.fromFields(typeArg, ItemPurchased.bcs.parse(data)); + } + + toJSONField() { + return { + kiosk: this.kiosk, + id: this.id, + price: this.price.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): ItemPurchased> { + return ItemPurchased.reified(typeArg).new({ + kiosk: decodeFromJSONField(ID.reified(), field.kiosk), + id: decodeFromJSONField(ID.reified(), field.id), + price: decodeFromJSONField("u64", field.price), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): ItemPurchased> { + if (json.$typeName !== ItemPurchased.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(ItemPurchased.$typeName, extractType(typeArg)), json.$typeArgs, [ + typeArg, + ]); + + return ItemPurchased.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): ItemPurchased> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isItemPurchased(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a ItemPurchased object`); + } + return ItemPurchased.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): ItemPurchased> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isItemPurchased(data.bcs.type)) { + throw new Error(`object at is not a ItemPurchased object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return ItemPurchased.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return ItemPurchased.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching ItemPurchased object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isItemPurchased(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a ItemPurchased object`); + } + + return ItemPurchased.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== Kiosk =============================== */ + +export function isKiosk(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::kiosk::Kiosk`; +} + +export interface KioskFields { + id: ToField; + profits: ToField>>; + owner: ToField<"address">; + itemCount: ToField<"u32">; + allowExtensions: ToField<"bool">; +} + +export type KioskReified = Reified; + +export class Kiosk implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::kiosk::Kiosk`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Kiosk.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Kiosk.$isPhantom; + + readonly id: ToField; + readonly profits: ToField>>; + readonly owner: ToField<"address">; + readonly itemCount: ToField<"u32">; + readonly allowExtensions: ToField<"bool">; + + private constructor(typeArgs: [], fields: KioskFields) { + this.$fullTypeName = composeSuiType(Kiosk.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.profits = fields.profits; + this.owner = fields.owner; + this.itemCount = fields.itemCount; + this.allowExtensions = fields.allowExtensions; + } + + static reified(): KioskReified { + return { + typeName: Kiosk.$typeName, + fullTypeName: composeSuiType(Kiosk.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Kiosk.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Kiosk.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Kiosk.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Kiosk.fromBcs(data), + bcs: Kiosk.bcs, + fromJSONField: (field: any) => Kiosk.fromJSONField(field), + fromJSON: (json: Record) => Kiosk.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Kiosk.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Kiosk.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Kiosk.fetch(client, id), + new: (fields: KioskFields) => { + return new Kiosk([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Kiosk.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Kiosk.reified()); + } + static get p() { + return Kiosk.phantom(); + } + + static get bcs() { + return bcs.struct("Kiosk", { + id: UID.bcs, + profits: Balance.bcs, + owner: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + item_count: bcs.u32(), + allow_extensions: bcs.bool(), + }); + } + + static fromFields(fields: Record): Kiosk { + return Kiosk.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + profits: decodeFromFields(Balance.reified(reified.phantom(SUI.reified())), fields.profits), + owner: decodeFromFields("address", fields.owner), + itemCount: decodeFromFields("u32", fields.item_count), + allowExtensions: decodeFromFields("bool", fields.allow_extensions), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Kiosk { + if (!isKiosk(item.type)) { + throw new Error("not a Kiosk type"); + } + + return Kiosk.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + profits: decodeFromFieldsWithTypes(Balance.reified(reified.phantom(SUI.reified())), item.fields.profits), + owner: decodeFromFieldsWithTypes("address", item.fields.owner), + itemCount: decodeFromFieldsWithTypes("u32", item.fields.item_count), + allowExtensions: decodeFromFieldsWithTypes("bool", item.fields.allow_extensions), + }); + } + + static fromBcs(data: Uint8Array): Kiosk { + return Kiosk.fromFields(Kiosk.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + profits: this.profits.toJSONField(), + owner: this.owner, + itemCount: this.itemCount, + allowExtensions: this.allowExtensions, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Kiosk { + return Kiosk.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + profits: decodeFromJSONField(Balance.reified(reified.phantom(SUI.reified())), field.profits), + owner: decodeFromJSONField("address", field.owner), + itemCount: decodeFromJSONField("u32", field.itemCount), + allowExtensions: decodeFromJSONField("bool", field.allowExtensions), + }); + } + + static fromJSON(json: Record): Kiosk { + if (json.$typeName !== Kiosk.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Kiosk.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Kiosk { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isKiosk(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Kiosk object`); + } + return Kiosk.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Kiosk { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isKiosk(data.bcs.type)) { + throw new Error(`object at is not a Kiosk object`); + } + + return Kiosk.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Kiosk.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Kiosk object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isKiosk(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Kiosk object`); + } + + return Kiosk.fromSuiObjectData(res.data); + } +} + +/* ============================== KioskOwnerCap =============================== */ + +export function isKioskOwnerCap(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::kiosk::KioskOwnerCap`; +} + +export interface KioskOwnerCapFields { + id: ToField; + for: ToField; +} + +export type KioskOwnerCapReified = Reified; + +export class KioskOwnerCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::kiosk::KioskOwnerCap`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = KioskOwnerCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = KioskOwnerCap.$isPhantom; + + readonly id: ToField; + readonly for: ToField; + + private constructor(typeArgs: [], fields: KioskOwnerCapFields) { + this.$fullTypeName = composeSuiType(KioskOwnerCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.for = fields.for; + } + + static reified(): KioskOwnerCapReified { + return { + typeName: KioskOwnerCap.$typeName, + fullTypeName: composeSuiType(KioskOwnerCap.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: KioskOwnerCap.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => KioskOwnerCap.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => KioskOwnerCap.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => KioskOwnerCap.fromBcs(data), + bcs: KioskOwnerCap.bcs, + fromJSONField: (field: any) => KioskOwnerCap.fromJSONField(field), + fromJSON: (json: Record) => KioskOwnerCap.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => KioskOwnerCap.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => KioskOwnerCap.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => KioskOwnerCap.fetch(client, id), + new: (fields: KioskOwnerCapFields) => { + return new KioskOwnerCap([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return KioskOwnerCap.reified(); + } + + static phantom(): PhantomReified> { + return phantom(KioskOwnerCap.reified()); + } + static get p() { + return KioskOwnerCap.phantom(); + } + + static get bcs() { + return bcs.struct("KioskOwnerCap", { + id: UID.bcs, + for: ID.bcs, + }); + } + + static fromFields(fields: Record): KioskOwnerCap { + return KioskOwnerCap.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + for: decodeFromFields(ID.reified(), fields.for), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): KioskOwnerCap { + if (!isKioskOwnerCap(item.type)) { + throw new Error("not a KioskOwnerCap type"); + } + + return KioskOwnerCap.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + for: decodeFromFieldsWithTypes(ID.reified(), item.fields.for), + }); + } + + static fromBcs(data: Uint8Array): KioskOwnerCap { + return KioskOwnerCap.fromFields(KioskOwnerCap.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + for: this.for, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): KioskOwnerCap { + return KioskOwnerCap.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + for: decodeFromJSONField(ID.reified(), field.for), + }); + } + + static fromJSON(json: Record): KioskOwnerCap { + if (json.$typeName !== KioskOwnerCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return KioskOwnerCap.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): KioskOwnerCap { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isKioskOwnerCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a KioskOwnerCap object`); + } + return KioskOwnerCap.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): KioskOwnerCap { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isKioskOwnerCap(data.bcs.type)) { + throw new Error(`object at is not a KioskOwnerCap object`); + } + + return KioskOwnerCap.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return KioskOwnerCap.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching KioskOwnerCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isKioskOwnerCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a KioskOwnerCap object`); + } + + return KioskOwnerCap.fromSuiObjectData(res.data); + } +} + +/* ============================== Listing =============================== */ + +export function isListing(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::kiosk::Listing`; +} + +export interface ListingFields { + id: ToField; + isExclusive: ToField<"bool">; +} + +export type ListingReified = Reified; + +export class Listing implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::kiosk::Listing`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Listing.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Listing.$isPhantom; + + readonly id: ToField; + readonly isExclusive: ToField<"bool">; + + private constructor(typeArgs: [], fields: ListingFields) { + this.$fullTypeName = composeSuiType(Listing.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.isExclusive = fields.isExclusive; + } + + static reified(): ListingReified { + return { + typeName: Listing.$typeName, + fullTypeName: composeSuiType(Listing.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Listing.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Listing.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Listing.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Listing.fromBcs(data), + bcs: Listing.bcs, + fromJSONField: (field: any) => Listing.fromJSONField(field), + fromJSON: (json: Record) => Listing.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Listing.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Listing.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Listing.fetch(client, id), + new: (fields: ListingFields) => { + return new Listing([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Listing.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Listing.reified()); + } + static get p() { + return Listing.phantom(); + } + + static get bcs() { + return bcs.struct("Listing", { + id: ID.bcs, + is_exclusive: bcs.bool(), + }); + } + + static fromFields(fields: Record): Listing { + return Listing.reified().new({ + id: decodeFromFields(ID.reified(), fields.id), + isExclusive: decodeFromFields("bool", fields.is_exclusive), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Listing { + if (!isListing(item.type)) { + throw new Error("not a Listing type"); + } + + return Listing.reified().new({ + id: decodeFromFieldsWithTypes(ID.reified(), item.fields.id), + isExclusive: decodeFromFieldsWithTypes("bool", item.fields.is_exclusive), + }); + } + + static fromBcs(data: Uint8Array): Listing { + return Listing.fromFields(Listing.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + isExclusive: this.isExclusive, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Listing { + return Listing.reified().new({ + id: decodeFromJSONField(ID.reified(), field.id), + isExclusive: decodeFromJSONField("bool", field.isExclusive), + }); + } + + static fromJSON(json: Record): Listing { + if (json.$typeName !== Listing.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Listing.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Listing { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isListing(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Listing object`); + } + return Listing.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Listing { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isListing(data.bcs.type)) { + throw new Error(`object at is not a Listing object`); + } + + return Listing.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Listing.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise

{ + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Listing object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isListing(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Listing object`); + } + + return Listing.fromSuiObjectData(res.data); + } +} + +/* ============================== Lock =============================== */ + +export function isLock(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::kiosk::Lock`; +} + +export interface LockFields { + id: ToField; +} + +export type LockReified = Reified; + +export class Lock implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::kiosk::Lock`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Lock.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Lock.$isPhantom; + + readonly id: ToField; + + private constructor(typeArgs: [], fields: LockFields) { + this.$fullTypeName = composeSuiType(Lock.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified(): LockReified { + return { + typeName: Lock.$typeName, + fullTypeName: composeSuiType(Lock.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Lock.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Lock.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Lock.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Lock.fromBcs(data), + bcs: Lock.bcs, + fromJSONField: (field: any) => Lock.fromJSONField(field), + fromJSON: (json: Record) => Lock.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Lock.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Lock.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Lock.fetch(client, id), + new: (fields: LockFields) => { + return new Lock([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Lock.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Lock.reified()); + } + static get p() { + return Lock.phantom(); + } + + static get bcs() { + return bcs.struct("Lock", { + id: ID.bcs, + }); + } + + static fromFields(fields: Record): Lock { + return Lock.reified().new({ + id: decodeFromFields(ID.reified(), fields.id), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Lock { + if (!isLock(item.type)) { + throw new Error("not a Lock type"); + } + + return Lock.reified().new({ + id: decodeFromFieldsWithTypes(ID.reified(), item.fields.id), + }); + } + + static fromBcs(data: Uint8Array): Lock { + return Lock.fromFields(Lock.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Lock { + return Lock.reified().new({ + id: decodeFromJSONField(ID.reified(), field.id), + }); + } + + static fromJSON(json: Record): Lock { + if (json.$typeName !== Lock.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Lock.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Lock { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isLock(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Lock object`); + } + return Lock.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Lock { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isLock(data.bcs.type)) { + throw new Error(`object at is not a Lock object`); + } + + return Lock.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Lock.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Lock object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isLock(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Lock object`); + } + + return Lock.fromSuiObjectData(res.data); + } +} + +/* ============================== PurchaseCap =============================== */ + +export function isPurchaseCap(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::kiosk::PurchaseCap` + "<"); +} + +export interface PurchaseCapFields { + id: ToField; + kioskId: ToField; + itemId: ToField; + minPrice: ToField<"u64">; +} + +export type PurchaseCapReified = Reified, PurchaseCapFields>; + +export class PurchaseCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::kiosk::PurchaseCap`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = PurchaseCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = PurchaseCap.$isPhantom; + + readonly id: ToField; + readonly kioskId: ToField; + readonly itemId: ToField; + readonly minPrice: ToField<"u64">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: PurchaseCapFields) { + this.$fullTypeName = composeSuiType(PurchaseCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.kioskId = fields.kioskId; + this.itemId = fields.itemId; + this.minPrice = fields.minPrice; + } + + static reified>(T: T): PurchaseCapReified> { + return { + typeName: PurchaseCap.$typeName, + fullTypeName: composeSuiType(PurchaseCap.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: PurchaseCap.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => PurchaseCap.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => PurchaseCap.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => PurchaseCap.fromBcs(T, data), + bcs: PurchaseCap.bcs, + fromJSONField: (field: any) => PurchaseCap.fromJSONField(T, field), + fromJSON: (json: Record) => PurchaseCap.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => PurchaseCap.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => PurchaseCap.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => PurchaseCap.fetch(client, T, id), + new: (fields: PurchaseCapFields>) => { + return new PurchaseCap([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return PurchaseCap.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(PurchaseCap.reified(T)); + } + static get p() { + return PurchaseCap.phantom; + } + + static get bcs() { + return bcs.struct("PurchaseCap", { + id: UID.bcs, + kiosk_id: ID.bcs, + item_id: ID.bcs, + min_price: bcs.u64(), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): PurchaseCap> { + return PurchaseCap.reified(typeArg).new({ + id: decodeFromFields(UID.reified(), fields.id), + kioskId: decodeFromFields(ID.reified(), fields.kiosk_id), + itemId: decodeFromFields(ID.reified(), fields.item_id), + minPrice: decodeFromFields("u64", fields.min_price), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): PurchaseCap> { + if (!isPurchaseCap(item.type)) { + throw new Error("not a PurchaseCap type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return PurchaseCap.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + kioskId: decodeFromFieldsWithTypes(ID.reified(), item.fields.kiosk_id), + itemId: decodeFromFieldsWithTypes(ID.reified(), item.fields.item_id), + minPrice: decodeFromFieldsWithTypes("u64", item.fields.min_price), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): PurchaseCap> { + return PurchaseCap.fromFields(typeArg, PurchaseCap.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + kioskId: this.kioskId, + itemId: this.itemId, + minPrice: this.minPrice.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): PurchaseCap> { + return PurchaseCap.reified(typeArg).new({ + id: decodeFromJSONField(UID.reified(), field.id), + kioskId: decodeFromJSONField(ID.reified(), field.kioskId), + itemId: decodeFromJSONField(ID.reified(), field.itemId), + minPrice: decodeFromJSONField("u64", field.minPrice), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): PurchaseCap> { + if (json.$typeName !== PurchaseCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(PurchaseCap.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return PurchaseCap.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): PurchaseCap> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isPurchaseCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a PurchaseCap object`); + } + return PurchaseCap.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): PurchaseCap> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isPurchaseCap(data.bcs.type)) { + throw new Error(`object at is not a PurchaseCap object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return PurchaseCap.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return PurchaseCap.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching PurchaseCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isPurchaseCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a PurchaseCap object`); + } + + return PurchaseCap.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/sui/linked-table/functions.ts b/src/services/models/sui/sui/linked-table/functions.ts new file mode 100644 index 00000000..9009b14a --- /dev/null +++ b/src/services/models/sui/sui/linked-table/functions.ts @@ -0,0 +1,182 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj } from "../../_framework/util"; +import { Transaction, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface BorrowArgs { + table: TransactionObjectInput; + k: GenericArg; +} + +export function borrow(tx: Transaction, typeArgs: [string, string], args: BorrowArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::linked_table::borrow`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export interface BorrowMutArgs { + table: TransactionObjectInput; + k: GenericArg; +} + +export function borrowMut(tx: Transaction, typeArgs: [string, string], args: BorrowMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::linked_table::borrow_mut`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export interface ContainsArgs { + table: TransactionObjectInput; + k: GenericArg; +} + +export function contains(tx: Transaction, typeArgs: [string, string], args: ContainsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::linked_table::contains`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export function destroyEmpty(tx: Transaction, typeArgs: [string, string], table: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::linked_table::destroy_empty`, + typeArguments: typeArgs, + arguments: [obj(tx, table)], + }); +} + +export function isEmpty(tx: Transaction, typeArgs: [string, string], table: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::linked_table::is_empty`, + typeArguments: typeArgs, + arguments: [obj(tx, table)], + }); +} + +export function length(tx: Transaction, typeArgs: [string, string], table: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::linked_table::length`, + typeArguments: typeArgs, + arguments: [obj(tx, table)], + }); +} + +export function popBack(tx: Transaction, typeArgs: [string, string], table: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::linked_table::pop_back`, + typeArguments: typeArgs, + arguments: [obj(tx, table)], + }); +} + +export interface PushBackArgs { + table: TransactionObjectInput; + k: GenericArg; + value: GenericArg; +} + +export function pushBack(tx: Transaction, typeArgs: [string, string], args: PushBackArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::linked_table::push_back`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k), generic(tx, `${typeArgs[1]}`, args.value)], + }); +} + +export interface RemoveArgs { + table: TransactionObjectInput; + k: GenericArg; +} + +export function remove(tx: Transaction, typeArgs: [string, string], args: RemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::linked_table::remove`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export function new_(tx: Transaction, typeArgs: [string, string]) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::linked_table::new`, + typeArguments: typeArgs, + arguments: [], + }); +} + +export function drop(tx: Transaction, typeArgs: [string, string], table: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::linked_table::drop`, + typeArguments: typeArgs, + arguments: [obj(tx, table)], + }); +} + +export function back(tx: Transaction, typeArgs: [string, string], table: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::linked_table::back`, + typeArguments: typeArgs, + arguments: [obj(tx, table)], + }); +} + +export function front(tx: Transaction, typeArgs: [string, string], table: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::linked_table::front`, + typeArguments: typeArgs, + arguments: [obj(tx, table)], + }); +} + +export interface NextArgs { + table: TransactionObjectInput; + k: GenericArg; +} + +export function next(tx: Transaction, typeArgs: [string, string], args: NextArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::linked_table::next`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export function popFront(tx: Transaction, typeArgs: [string, string], table: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::linked_table::pop_front`, + typeArguments: typeArgs, + arguments: [obj(tx, table)], + }); +} + +export interface PrevArgs { + table: TransactionObjectInput; + k: GenericArg; +} + +export function prev(tx: Transaction, typeArgs: [string, string], args: PrevArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::linked_table::prev`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export interface PushFrontArgs { + table: TransactionObjectInput; + k: GenericArg; + value: GenericArg; +} + +export function pushFront(tx: Transaction, typeArgs: [string, string], args: PushFrontArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::linked_table::push_front`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k), generic(tx, `${typeArgs[1]}`, args.value)], + }); +} diff --git a/src/services/models/sui/sui/linked-table/structs.ts b/src/services/models/sui/sui/linked-table/structs.ts new file mode 100644 index 00000000..b8f9b933 --- /dev/null +++ b/src/services/models/sui/sui/linked-table/structs.ts @@ -0,0 +1,501 @@ +// @ts-nocheck +import { Option } from "../../_dependencies/source/0x1/option/structs"; +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeArgument, + ToTypeStr, + TypeArgument, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + fieldToJSON, + phantom, + toBcs, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { UID } from "../object/structs"; +import { BcsType, bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== LinkedTable =============================== */ + +export function isLinkedTable(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::linked_table::LinkedTable` + "<"); +} + +export interface LinkedTableFields { + id: ToField; + size: ToField<"u64">; + head: ToField>; + tail: ToField>; +} + +export type LinkedTableReified = Reified< + LinkedTable, + LinkedTableFields +>; + +export class LinkedTable implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::linked_table::LinkedTable`; + } + static readonly $numTypeParams = 2; + static readonly $isPhantom = [false, true] as const; + + readonly $typeName = LinkedTable.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [ToTypeStr, PhantomToTypeStr]; + readonly $isPhantom = LinkedTable.$isPhantom; + + readonly id: ToField; + readonly size: ToField<"u64">; + readonly head: ToField>; + readonly tail: ToField>; + + private constructor(typeArgs: [ToTypeStr, PhantomToTypeStr], fields: LinkedTableFields) { + this.$fullTypeName = composeSuiType(LinkedTable.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.size = fields.size; + this.head = fields.head; + this.tail = fields.tail; + } + + static reified, V extends PhantomReified>( + K: K, + V: V + ): LinkedTableReified, ToPhantomTypeArgument> { + return { + typeName: LinkedTable.$typeName, + fullTypeName: composeSuiType(LinkedTable.$typeName, ...[extractType(K), extractType(V)]) as string, + typeArgs: [extractType(K), extractType(V)] as [ + ToTypeStr>, + PhantomToTypeStr>, + ], + isPhantom: LinkedTable.$isPhantom, + reifiedTypeArgs: [K, V], + fromFields: (fields: Record) => LinkedTable.fromFields([K, V], fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => LinkedTable.fromFieldsWithTypes([K, V], item), + fromBcs: (data: Uint8Array) => LinkedTable.fromBcs([K, V], data), + bcs: LinkedTable.bcs(toBcs(K)), + fromJSONField: (field: any) => LinkedTable.fromJSONField([K, V], field), + fromJSON: (json: Record) => LinkedTable.fromJSON([K, V], json), + fromSuiParsedData: (content: SuiParsedData) => LinkedTable.fromSuiParsedData([K, V], content), + fromSuiObjectData: (content: SuiObjectData) => LinkedTable.fromSuiObjectData([K, V], content), + fetch: async (client: SuiClient, id: string) => LinkedTable.fetch(client, [K, V], id), + new: (fields: LinkedTableFields, ToPhantomTypeArgument>) => { + return new LinkedTable([extractType(K), extractType(V)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return LinkedTable.reified; + } + + static phantom, V extends PhantomReified>( + K: K, + V: V + ): PhantomReified, ToPhantomTypeArgument>>> { + return phantom(LinkedTable.reified(K, V)); + } + static get p() { + return LinkedTable.phantom; + } + + static get bcs() { + return >(K: K) => + bcs.struct(`LinkedTable<${K.name}>`, { + id: UID.bcs, + size: bcs.u64(), + head: Option.bcs(K), + tail: Option.bcs(K), + }); + } + + static fromFields, V extends PhantomReified>( + typeArgs: [K, V], + fields: Record + ): LinkedTable, ToPhantomTypeArgument> { + return LinkedTable.reified(typeArgs[0], typeArgs[1]).new({ + id: decodeFromFields(UID.reified(), fields.id), + size: decodeFromFields("u64", fields.size), + head: decodeFromFields(Option.reified(typeArgs[0]), fields.head), + tail: decodeFromFields(Option.reified(typeArgs[0]), fields.tail), + }); + } + + static fromFieldsWithTypes, V extends PhantomReified>( + typeArgs: [K, V], + item: FieldsWithTypes + ): LinkedTable, ToPhantomTypeArgument> { + if (!isLinkedTable(item.type)) { + throw new Error("not a LinkedTable type"); + } + assertFieldsWithTypesArgsMatch(item, typeArgs); + + return LinkedTable.reified(typeArgs[0], typeArgs[1]).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + size: decodeFromFieldsWithTypes("u64", item.fields.size), + head: decodeFromFieldsWithTypes(Option.reified(typeArgs[0]), item.fields.head), + tail: decodeFromFieldsWithTypes(Option.reified(typeArgs[0]), item.fields.tail), + }); + } + + static fromBcs, V extends PhantomReified>( + typeArgs: [K, V], + data: Uint8Array + ): LinkedTable, ToPhantomTypeArgument> { + return LinkedTable.fromFields(typeArgs, LinkedTable.bcs(toBcs(typeArgs[0])).parse(data)); + } + + toJSONField() { + return { + id: this.id, + size: this.size.toString(), + head: fieldToJSON>(`${Option.$typeName}<${this.$typeArgs[0]}>`, this.head), + tail: fieldToJSON>(`${Option.$typeName}<${this.$typeArgs[0]}>`, this.tail), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField, V extends PhantomReified>( + typeArgs: [K, V], + field: any + ): LinkedTable, ToPhantomTypeArgument> { + return LinkedTable.reified(typeArgs[0], typeArgs[1]).new({ + id: decodeFromJSONField(UID.reified(), field.id), + size: decodeFromJSONField("u64", field.size), + head: decodeFromJSONField(Option.reified(typeArgs[0]), field.head), + tail: decodeFromJSONField(Option.reified(typeArgs[0]), field.tail), + }); + } + + static fromJSON, V extends PhantomReified>( + typeArgs: [K, V], + json: Record + ): LinkedTable, ToPhantomTypeArgument> { + if (json.$typeName !== LinkedTable.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch( + composeSuiType(LinkedTable.$typeName, ...typeArgs.map(extractType)), + json.$typeArgs, + typeArgs + ); + + return LinkedTable.fromJSONField(typeArgs, json); + } + + static fromSuiParsedData, V extends PhantomReified>( + typeArgs: [K, V], + content: SuiParsedData + ): LinkedTable, ToPhantomTypeArgument> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isLinkedTable(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a LinkedTable object`); + } + return LinkedTable.fromFieldsWithTypes(typeArgs, content); + } + + static fromSuiObjectData, V extends PhantomReified>( + typeArgs: [K, V], + data: SuiObjectData + ): LinkedTable, ToPhantomTypeArgument> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isLinkedTable(data.bcs.type)) { + throw new Error(`object at is not a LinkedTable object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 2) { + throw new Error(`type argument mismatch: expected 2 type arguments but got ${gotTypeArgs.length}`); + } + for (let i = 0; i < 2; i++) { + const gotTypeArg = compressSuiType(gotTypeArgs[i]); + const expectedTypeArg = compressSuiType(extractType(typeArgs[i])); + if (gotTypeArg !== expectedTypeArg) { + throw new Error( + `type argument mismatch at position ${i}: expected '${expectedTypeArg}' but got '${gotTypeArg}'` + ); + } + } + + return LinkedTable.fromBcs(typeArgs, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return LinkedTable.fromSuiParsedData(typeArgs, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch, V extends PhantomReified>( + client: SuiClient, + typeArgs: [K, V], + id: string + ): Promise, ToPhantomTypeArgument>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching LinkedTable object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isLinkedTable(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a LinkedTable object`); + } + + return LinkedTable.fromSuiObjectData(typeArgs, res.data); + } +} + +/* ============================== Node =============================== */ + +export function isNode(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::linked_table::Node` + "<"); +} + +export interface NodeFields { + prev: ToField>; + next: ToField>; + value: ToField; +} + +export type NodeReified = Reified, NodeFields>; + +export class Node implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::linked_table::Node`; + } + static readonly $numTypeParams = 2; + static readonly $isPhantom = [false, false] as const; + + readonly $typeName = Node.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [ToTypeStr, ToTypeStr]; + readonly $isPhantom = Node.$isPhantom; + + readonly prev: ToField>; + readonly next: ToField>; + readonly value: ToField; + + private constructor(typeArgs: [ToTypeStr, ToTypeStr], fields: NodeFields) { + this.$fullTypeName = composeSuiType(Node.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.prev = fields.prev; + this.next = fields.next; + this.value = fields.value; + } + + static reified, V extends Reified>( + K: K, + V: V + ): NodeReified, ToTypeArgument> { + return { + typeName: Node.$typeName, + fullTypeName: composeSuiType(Node.$typeName, ...[extractType(K), extractType(V)]) as string, + typeArgs: [extractType(K), extractType(V)] as [ToTypeStr>, ToTypeStr>], + isPhantom: Node.$isPhantom, + reifiedTypeArgs: [K, V], + fromFields: (fields: Record) => Node.fromFields([K, V], fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Node.fromFieldsWithTypes([K, V], item), + fromBcs: (data: Uint8Array) => Node.fromBcs([K, V], data), + bcs: Node.bcs(toBcs(K), toBcs(V)), + fromJSONField: (field: any) => Node.fromJSONField([K, V], field), + fromJSON: (json: Record) => Node.fromJSON([K, V], json), + fromSuiParsedData: (content: SuiParsedData) => Node.fromSuiParsedData([K, V], content), + fromSuiObjectData: (content: SuiObjectData) => Node.fromSuiObjectData([K, V], content), + fetch: async (client: SuiClient, id: string) => Node.fetch(client, [K, V], id), + new: (fields: NodeFields, ToTypeArgument>) => { + return new Node([extractType(K), extractType(V)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Node.reified; + } + + static phantom, V extends Reified>( + K: K, + V: V + ): PhantomReified, ToTypeArgument>>> { + return phantom(Node.reified(K, V)); + } + static get p() { + return Node.phantom; + } + + static get bcs() { + return , V extends BcsType>(K: K, V: V) => + bcs.struct(`Node<${K.name}, ${V.name}>`, { + prev: Option.bcs(K), + next: Option.bcs(K), + value: V, + }); + } + + static fromFields, V extends Reified>( + typeArgs: [K, V], + fields: Record + ): Node, ToTypeArgument> { + return Node.reified(typeArgs[0], typeArgs[1]).new({ + prev: decodeFromFields(Option.reified(typeArgs[0]), fields.prev), + next: decodeFromFields(Option.reified(typeArgs[0]), fields.next), + value: decodeFromFields(typeArgs[1], fields.value), + }); + } + + static fromFieldsWithTypes, V extends Reified>( + typeArgs: [K, V], + item: FieldsWithTypes + ): Node, ToTypeArgument> { + if (!isNode(item.type)) { + throw new Error("not a Node type"); + } + assertFieldsWithTypesArgsMatch(item, typeArgs); + + return Node.reified(typeArgs[0], typeArgs[1]).new({ + prev: decodeFromFieldsWithTypes(Option.reified(typeArgs[0]), item.fields.prev), + next: decodeFromFieldsWithTypes(Option.reified(typeArgs[0]), item.fields.next), + value: decodeFromFieldsWithTypes(typeArgs[1], item.fields.value), + }); + } + + static fromBcs, V extends Reified>( + typeArgs: [K, V], + data: Uint8Array + ): Node, ToTypeArgument> { + return Node.fromFields(typeArgs, Node.bcs(toBcs(typeArgs[0]), toBcs(typeArgs[1])).parse(data)); + } + + toJSONField() { + return { + prev: fieldToJSON>(`${Option.$typeName}<${this.$typeArgs[0]}>`, this.prev), + next: fieldToJSON>(`${Option.$typeName}<${this.$typeArgs[0]}>`, this.next), + value: fieldToJSON(this.$typeArgs[1], this.value), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField, V extends Reified>( + typeArgs: [K, V], + field: any + ): Node, ToTypeArgument> { + return Node.reified(typeArgs[0], typeArgs[1]).new({ + prev: decodeFromJSONField(Option.reified(typeArgs[0]), field.prev), + next: decodeFromJSONField(Option.reified(typeArgs[0]), field.next), + value: decodeFromJSONField(typeArgs[1], field.value), + }); + } + + static fromJSON, V extends Reified>( + typeArgs: [K, V], + json: Record + ): Node, ToTypeArgument> { + if (json.$typeName !== Node.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Node.$typeName, ...typeArgs.map(extractType)), json.$typeArgs, typeArgs); + + return Node.fromJSONField(typeArgs, json); + } + + static fromSuiParsedData, V extends Reified>( + typeArgs: [K, V], + content: SuiParsedData + ): Node, ToTypeArgument> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isNode(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Node object`); + } + return Node.fromFieldsWithTypes(typeArgs, content); + } + + static fromSuiObjectData, V extends Reified>( + typeArgs: [K, V], + data: SuiObjectData + ): Node, ToTypeArgument> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isNode(data.bcs.type)) { + throw new Error(`object at is not a Node object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 2) { + throw new Error(`type argument mismatch: expected 2 type arguments but got ${gotTypeArgs.length}`); + } + for (let i = 0; i < 2; i++) { + const gotTypeArg = compressSuiType(gotTypeArgs[i]); + const expectedTypeArg = compressSuiType(extractType(typeArgs[i])); + if (gotTypeArg !== expectedTypeArg) { + throw new Error( + `type argument mismatch at position ${i}: expected '${expectedTypeArg}' but got '${gotTypeArg}'` + ); + } + } + + return Node.fromBcs(typeArgs, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Node.fromSuiParsedData(typeArgs, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch, V extends Reified>( + client: SuiClient, + typeArgs: [K, V], + id: string + ): Promise, ToTypeArgument>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Node object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isNode(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Node object`); + } + + return Node.fromSuiObjectData(typeArgs, res.data); + } +} diff --git a/src/services/models/sui/sui/math/functions.ts b/src/services/models/sui/sui/math/functions.ts new file mode 100644 index 00000000..49d01a8d --- /dev/null +++ b/src/services/models/sui/sui/math/functions.ts @@ -0,0 +1,78 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { pure } from "../../_framework/util"; +import { Transaction, TransactionArgument } from "@mysten/sui/transactions"; + +export interface MaxArgs { + x: bigint | TransactionArgument; + y: bigint | TransactionArgument; +} + +export function max(tx: Transaction, args: MaxArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::math::max`, + arguments: [pure(tx, args.x, `u64`), pure(tx, args.y, `u64`)], + }); +} + +export interface DiffArgs { + x: bigint | TransactionArgument; + y: bigint | TransactionArgument; +} + +export function diff(tx: Transaction, args: DiffArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::math::diff`, + arguments: [pure(tx, args.x, `u64`), pure(tx, args.y, `u64`)], + }); +} + +export interface DivideAndRoundUpArgs { + x: bigint | TransactionArgument; + y: bigint | TransactionArgument; +} + +export function divideAndRoundUp(tx: Transaction, args: DivideAndRoundUpArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::math::divide_and_round_up`, + arguments: [pure(tx, args.x, `u64`), pure(tx, args.y, `u64`)], + }); +} + +export interface MinArgs { + x: bigint | TransactionArgument; + y: bigint | TransactionArgument; +} + +export function min(tx: Transaction, args: MinArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::math::min`, + arguments: [pure(tx, args.x, `u64`), pure(tx, args.y, `u64`)], + }); +} + +export interface PowArgs { + base: bigint | TransactionArgument; + exponent: number | TransactionArgument; +} + +export function pow(tx: Transaction, args: PowArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::math::pow`, + arguments: [pure(tx, args.base, `u64`), pure(tx, args.exponent, `u8`)], + }); +} + +export function sqrt(tx: Transaction, x: bigint | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::math::sqrt`, + arguments: [pure(tx, x, `u64`)], + }); +} + +export function sqrtU128(tx: Transaction, x: bigint | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::math::sqrt_u128`, + arguments: [pure(tx, x, `u128`)], + }); +} diff --git a/src/services/models/sui/sui/object-bag/functions.ts b/src/services/models/sui/sui/object-bag/functions.ts new file mode 100644 index 00000000..9fe54c11 --- /dev/null +++ b/src/services/models/sui/sui/object-bag/functions.ts @@ -0,0 +1,124 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj } from "../../_framework/util"; +import { Transaction, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface AddArgs { + bag: TransactionObjectInput; + k: GenericArg; + v: GenericArg; +} + +export function add(tx: Transaction, typeArgs: [string, string], args: AddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_bag::add`, + typeArguments: typeArgs, + arguments: [obj(tx, args.bag), generic(tx, `${typeArgs[0]}`, args.k), generic(tx, `${typeArgs[1]}`, args.v)], + }); +} + +export interface BorrowArgs { + bag: TransactionObjectInput; + k: GenericArg; +} + +export function borrow(tx: Transaction, typeArgs: [string, string], args: BorrowArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_bag::borrow`, + typeArguments: typeArgs, + arguments: [obj(tx, args.bag), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export interface BorrowMutArgs { + bag: TransactionObjectInput; + k: GenericArg; +} + +export function borrowMut(tx: Transaction, typeArgs: [string, string], args: BorrowMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_bag::borrow_mut`, + typeArguments: typeArgs, + arguments: [obj(tx, args.bag), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export interface ContainsArgs { + bag: TransactionObjectInput; + k: GenericArg; +} + +export function contains(tx: Transaction, typeArg: string, args: ContainsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_bag::contains`, + typeArguments: [typeArg], + arguments: [obj(tx, args.bag), generic(tx, `${typeArg}`, args.k)], + }); +} + +export function destroyEmpty(tx: Transaction, bag: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_bag::destroy_empty`, + arguments: [obj(tx, bag)], + }); +} + +export function isEmpty(tx: Transaction, bag: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_bag::is_empty`, + arguments: [obj(tx, bag)], + }); +} + +export function length(tx: Transaction, bag: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_bag::length`, + arguments: [obj(tx, bag)], + }); +} + +export interface RemoveArgs { + bag: TransactionObjectInput; + k: GenericArg; +} + +export function remove(tx: Transaction, typeArgs: [string, string], args: RemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_bag::remove`, + typeArguments: typeArgs, + arguments: [obj(tx, args.bag), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export function new_(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_bag::new`, + arguments: [], + }); +} + +export interface ContainsWithTypeArgs { + bag: TransactionObjectInput; + k: GenericArg; +} + +export function containsWithType(tx: Transaction, typeArgs: [string, string], args: ContainsWithTypeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_bag::contains_with_type`, + typeArguments: typeArgs, + arguments: [obj(tx, args.bag), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export interface ValueIdArgs { + bag: TransactionObjectInput; + k: GenericArg; +} + +export function valueId(tx: Transaction, typeArg: string, args: ValueIdArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_bag::value_id`, + typeArguments: [typeArg], + arguments: [obj(tx, args.bag), generic(tx, `${typeArg}`, args.k)], + }); +} diff --git a/src/services/models/sui/sui/object-bag/structs.ts b/src/services/models/sui/sui/object-bag/structs.ts new file mode 100644 index 00000000..4ef35d25 --- /dev/null +++ b/src/services/models/sui/sui/object-bag/structs.ts @@ -0,0 +1,189 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { UID } from "../object/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== ObjectBag =============================== */ + +export function isObjectBag(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::object_bag::ObjectBag`; +} + +export interface ObjectBagFields { + id: ToField; + size: ToField<"u64">; +} + +export type ObjectBagReified = Reified; + +export class ObjectBag implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::object_bag::ObjectBag`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = ObjectBag.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = ObjectBag.$isPhantom; + + readonly id: ToField; + readonly size: ToField<"u64">; + + private constructor(typeArgs: [], fields: ObjectBagFields) { + this.$fullTypeName = composeSuiType(ObjectBag.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.size = fields.size; + } + + static reified(): ObjectBagReified { + return { + typeName: ObjectBag.$typeName, + fullTypeName: composeSuiType(ObjectBag.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: ObjectBag.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => ObjectBag.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => ObjectBag.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => ObjectBag.fromBcs(data), + bcs: ObjectBag.bcs, + fromJSONField: (field: any) => ObjectBag.fromJSONField(field), + fromJSON: (json: Record) => ObjectBag.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => ObjectBag.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => ObjectBag.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => ObjectBag.fetch(client, id), + new: (fields: ObjectBagFields) => { + return new ObjectBag([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return ObjectBag.reified(); + } + + static phantom(): PhantomReified> { + return phantom(ObjectBag.reified()); + } + static get p() { + return ObjectBag.phantom(); + } + + static get bcs() { + return bcs.struct("ObjectBag", { + id: UID.bcs, + size: bcs.u64(), + }); + } + + static fromFields(fields: Record): ObjectBag { + return ObjectBag.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + size: decodeFromFields("u64", fields.size), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): ObjectBag { + if (!isObjectBag(item.type)) { + throw new Error("not a ObjectBag type"); + } + + return ObjectBag.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + size: decodeFromFieldsWithTypes("u64", item.fields.size), + }); + } + + static fromBcs(data: Uint8Array): ObjectBag { + return ObjectBag.fromFields(ObjectBag.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + size: this.size.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): ObjectBag { + return ObjectBag.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + size: decodeFromJSONField("u64", field.size), + }); + } + + static fromJSON(json: Record): ObjectBag { + if (json.$typeName !== ObjectBag.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return ObjectBag.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): ObjectBag { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isObjectBag(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a ObjectBag object`); + } + return ObjectBag.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): ObjectBag { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isObjectBag(data.bcs.type)) { + throw new Error(`object at is not a ObjectBag object`); + } + + return ObjectBag.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return ObjectBag.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching ObjectBag object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isObjectBag(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a ObjectBag object`); + } + + return ObjectBag.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/sui/object-table/functions.ts b/src/services/models/sui/sui/object-table/functions.ts new file mode 100644 index 00000000..58e4e559 --- /dev/null +++ b/src/services/models/sui/sui/object-table/functions.ts @@ -0,0 +1,115 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj } from "../../_framework/util"; +import { Transaction, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface AddArgs { + table: TransactionObjectInput; + k: GenericArg; + v: GenericArg; +} + +export function add(tx: Transaction, typeArgs: [string, string], args: AddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_table::add`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k), generic(tx, `${typeArgs[1]}`, args.v)], + }); +} + +export interface BorrowArgs { + table: TransactionObjectInput; + k: GenericArg; +} + +export function borrow(tx: Transaction, typeArgs: [string, string], args: BorrowArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_table::borrow`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export interface BorrowMutArgs { + table: TransactionObjectInput; + k: GenericArg; +} + +export function borrowMut(tx: Transaction, typeArgs: [string, string], args: BorrowMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_table::borrow_mut`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export interface ContainsArgs { + table: TransactionObjectInput; + k: GenericArg; +} + +export function contains(tx: Transaction, typeArgs: [string, string], args: ContainsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_table::contains`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export function destroyEmpty(tx: Transaction, typeArgs: [string, string], table: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_table::destroy_empty`, + typeArguments: typeArgs, + arguments: [obj(tx, table)], + }); +} + +export function isEmpty(tx: Transaction, typeArgs: [string, string], table: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_table::is_empty`, + typeArguments: typeArgs, + arguments: [obj(tx, table)], + }); +} + +export function length(tx: Transaction, typeArgs: [string, string], table: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_table::length`, + typeArguments: typeArgs, + arguments: [obj(tx, table)], + }); +} + +export interface RemoveArgs { + table: TransactionObjectInput; + k: GenericArg; +} + +export function remove(tx: Transaction, typeArgs: [string, string], args: RemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_table::remove`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export function new_(tx: Transaction, typeArgs: [string, string]) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_table::new`, + typeArguments: typeArgs, + arguments: [], + }); +} + +export interface ValueIdArgs { + table: TransactionObjectInput; + k: GenericArg; +} + +export function valueId(tx: Transaction, typeArgs: [string, string], args: ValueIdArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object_table::value_id`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} diff --git a/src/services/models/sui/sui/object-table/structs.ts b/src/services/models/sui/sui/object-table/structs.ts new file mode 100644 index 00000000..a32e20e8 --- /dev/null +++ b/src/services/models/sui/sui/object-table/structs.ts @@ -0,0 +1,252 @@ +// @ts-nocheck +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { UID } from "../object/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== ObjectTable =============================== */ + +export function isObjectTable(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::object_table::ObjectTable` + "<"); +} + +export interface ObjectTableFields { + id: ToField; + size: ToField<"u64">; +} + +export type ObjectTableReified = Reified< + ObjectTable, + ObjectTableFields +>; + +export class ObjectTable implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::object_table::ObjectTable`; + } + static readonly $numTypeParams = 2; + static readonly $isPhantom = [true, true] as const; + + readonly $typeName = ObjectTable.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr, PhantomToTypeStr]; + readonly $isPhantom = ObjectTable.$isPhantom; + + readonly id: ToField; + readonly size: ToField<"u64">; + + private constructor(typeArgs: [PhantomToTypeStr, PhantomToTypeStr], fields: ObjectTableFields) { + this.$fullTypeName = composeSuiType(ObjectTable.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.size = fields.size; + } + + static reified, V extends PhantomReified>( + K: K, + V: V + ): ObjectTableReified, ToPhantomTypeArgument> { + return { + typeName: ObjectTable.$typeName, + fullTypeName: composeSuiType(ObjectTable.$typeName, ...[extractType(K), extractType(V)]) as string, + typeArgs: [extractType(K), extractType(V)] as [ + PhantomToTypeStr>, + PhantomToTypeStr>, + ], + isPhantom: ObjectTable.$isPhantom, + reifiedTypeArgs: [K, V], + fromFields: (fields: Record) => ObjectTable.fromFields([K, V], fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => ObjectTable.fromFieldsWithTypes([K, V], item), + fromBcs: (data: Uint8Array) => ObjectTable.fromBcs([K, V], data), + bcs: ObjectTable.bcs, + fromJSONField: (field: any) => ObjectTable.fromJSONField([K, V], field), + fromJSON: (json: Record) => ObjectTable.fromJSON([K, V], json), + fromSuiParsedData: (content: SuiParsedData) => ObjectTable.fromSuiParsedData([K, V], content), + fromSuiObjectData: (content: SuiObjectData) => ObjectTable.fromSuiObjectData([K, V], content), + fetch: async (client: SuiClient, id: string) => ObjectTable.fetch(client, [K, V], id), + new: (fields: ObjectTableFields, ToPhantomTypeArgument>) => { + return new ObjectTable([extractType(K), extractType(V)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return ObjectTable.reified; + } + + static phantom, V extends PhantomReified>( + K: K, + V: V + ): PhantomReified, ToPhantomTypeArgument>>> { + return phantom(ObjectTable.reified(K, V)); + } + static get p() { + return ObjectTable.phantom; + } + + static get bcs() { + return bcs.struct("ObjectTable", { + id: UID.bcs, + size: bcs.u64(), + }); + } + + static fromFields, V extends PhantomReified>( + typeArgs: [K, V], + fields: Record + ): ObjectTable, ToPhantomTypeArgument> { + return ObjectTable.reified(typeArgs[0], typeArgs[1]).new({ + id: decodeFromFields(UID.reified(), fields.id), + size: decodeFromFields("u64", fields.size), + }); + } + + static fromFieldsWithTypes< + K extends PhantomReified, + V extends PhantomReified, + >(typeArgs: [K, V], item: FieldsWithTypes): ObjectTable, ToPhantomTypeArgument> { + if (!isObjectTable(item.type)) { + throw new Error("not a ObjectTable type"); + } + assertFieldsWithTypesArgsMatch(item, typeArgs); + + return ObjectTable.reified(typeArgs[0], typeArgs[1]).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + size: decodeFromFieldsWithTypes("u64", item.fields.size), + }); + } + + static fromBcs, V extends PhantomReified>( + typeArgs: [K, V], + data: Uint8Array + ): ObjectTable, ToPhantomTypeArgument> { + return ObjectTable.fromFields(typeArgs, ObjectTable.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + size: this.size.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField, V extends PhantomReified>( + typeArgs: [K, V], + field: any + ): ObjectTable, ToPhantomTypeArgument> { + return ObjectTable.reified(typeArgs[0], typeArgs[1]).new({ + id: decodeFromJSONField(UID.reified(), field.id), + size: decodeFromJSONField("u64", field.size), + }); + } + + static fromJSON, V extends PhantomReified>( + typeArgs: [K, V], + json: Record + ): ObjectTable, ToPhantomTypeArgument> { + if (json.$typeName !== ObjectTable.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch( + composeSuiType(ObjectTable.$typeName, ...typeArgs.map(extractType)), + json.$typeArgs, + typeArgs + ); + + return ObjectTable.fromJSONField(typeArgs, json); + } + + static fromSuiParsedData< + K extends PhantomReified, + V extends PhantomReified, + >(typeArgs: [K, V], content: SuiParsedData): ObjectTable, ToPhantomTypeArgument> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isObjectTable(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a ObjectTable object`); + } + return ObjectTable.fromFieldsWithTypes(typeArgs, content); + } + + static fromSuiObjectData< + K extends PhantomReified, + V extends PhantomReified, + >(typeArgs: [K, V], data: SuiObjectData): ObjectTable, ToPhantomTypeArgument> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isObjectTable(data.bcs.type)) { + throw new Error(`object at is not a ObjectTable object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 2) { + throw new Error(`type argument mismatch: expected 2 type arguments but got ${gotTypeArgs.length}`); + } + for (let i = 0; i < 2; i++) { + const gotTypeArg = compressSuiType(gotTypeArgs[i]); + const expectedTypeArg = compressSuiType(extractType(typeArgs[i])); + if (gotTypeArg !== expectedTypeArg) { + throw new Error( + `type argument mismatch at position ${i}: expected '${expectedTypeArg}' but got '${gotTypeArg}'` + ); + } + } + + return ObjectTable.fromBcs(typeArgs, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return ObjectTable.fromSuiParsedData(typeArgs, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch, V extends PhantomReified>( + client: SuiClient, + typeArgs: [K, V], + id: string + ): Promise, ToPhantomTypeArgument>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching ObjectTable object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isObjectTable(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a ObjectTable object`); + } + + return ObjectTable.fromSuiObjectData(typeArgs, res.data); + } +} diff --git a/src/services/models/sui/sui/object/functions.ts b/src/services/models/sui/sui/object/functions.ts new file mode 100644 index 00000000..06a78456 --- /dev/null +++ b/src/services/models/sui/sui/object/functions.ts @@ -0,0 +1,175 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj, pure } from "../../_framework/util"; +import { ID } from "./structs"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function bridge(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::bridge`, + arguments: [], + }); +} + +export function id(tx: Transaction, typeArg: string, obj: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::id`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, obj)], + }); +} + +export function authenticatorState(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::authenticator_state`, + arguments: [], + }); +} + +export function borrowId(tx: Transaction, typeArg: string, obj: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::borrow_id`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, obj)], + }); +} + +export function borrowUid(tx: Transaction, typeArg: string, obj: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::borrow_uid`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, obj)], + }); +} + +export function clock(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::clock`, + arguments: [], + }); +} + +export function delete_(tx: Transaction, id: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::delete`, + arguments: [obj(tx, id)], + }); +} + +export function deleteImpl(tx: Transaction, id: string | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::delete_impl`, + arguments: [pure(tx, id, `address`)], + }); +} + +export function idAddress(tx: Transaction, typeArg: string, obj: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::id_address`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, obj)], + }); +} + +export function idBytes(tx: Transaction, typeArg: string, obj: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::id_bytes`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, obj)], + }); +} + +export function idFromAddress(tx: Transaction, bytes: string | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::id_from_address`, + arguments: [pure(tx, bytes, `address`)], + }); +} + +export function idFromBytes(tx: Transaction, bytes: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::id_from_bytes`, + arguments: [pure(tx, bytes, `vector`)], + }); +} + +export function idToAddress(tx: Transaction, id: string | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::id_to_address`, + arguments: [pure(tx, id, `${ID.$typeName}`)], + }); +} + +export function idToBytes(tx: Transaction, id: string | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::id_to_bytes`, + arguments: [pure(tx, id, `${ID.$typeName}`)], + }); +} + +export function new_(tx: Transaction) { + return tx.moveCall({ target: `${PUBLISHED_AT}::object::new`, arguments: [] }); +} + +export function newUidFromHash(tx: Transaction, bytes: string | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::new_uid_from_hash`, + arguments: [pure(tx, bytes, `address`)], + }); +} + +export function randomnessState(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::randomness_state`, + arguments: [], + }); +} + +export function recordNewUid(tx: Transaction, id: string | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::record_new_uid`, + arguments: [pure(tx, id, `address`)], + }); +} + +export function suiDenyListObjectId(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::sui_deny_list_object_id`, + arguments: [], + }); +} + +export function suiSystemState(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::sui_system_state`, + arguments: [], + }); +} + +export function uidAsInner(tx: Transaction, uid: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::uid_as_inner`, + arguments: [obj(tx, uid)], + }); +} + +export function uidToAddress(tx: Transaction, uid: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::uid_to_address`, + arguments: [obj(tx, uid)], + }); +} + +export function uidToBytes(tx: Transaction, uid: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::uid_to_bytes`, + arguments: [obj(tx, uid)], + }); +} + +export function uidToInner(tx: Transaction, uid: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::object::uid_to_inner`, + arguments: [obj(tx, uid)], + }); +} diff --git a/src/services/models/sui/sui/object/structs.ts b/src/services/models/sui/sui/object/structs.ts new file mode 100644 index 00000000..aebb85f4 --- /dev/null +++ b/src/services/models/sui/sui/object/structs.ts @@ -0,0 +1,344 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64, fromHEX, toHEX } from "@mysten/sui/utils"; + +/* ============================== ID =============================== */ + +export function isID(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::object::ID`; +} + +export interface IDFields { + bytes: ToField<"address">; +} + +export type IDReified = Reified; + +export class ID implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::object::ID`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = ID.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = ID.$isPhantom; + + readonly bytes: ToField<"address">; + + private constructor(typeArgs: [], fields: IDFields) { + this.$fullTypeName = composeSuiType(ID.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.bytes = fields.bytes; + } + + static reified(): IDReified { + return { + typeName: ID.$typeName, + fullTypeName: composeSuiType(ID.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: ID.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => ID.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => ID.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => ID.fromBcs(data), + bcs: ID.bcs, + fromJSONField: (field: any) => ID.fromJSONField(field), + fromJSON: (json: Record) => ID.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => ID.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => ID.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => ID.fetch(client, id), + new: (fields: IDFields) => { + return new ID([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return ID.reified(); + } + + static phantom(): PhantomReified> { + return phantom(ID.reified()); + } + static get p() { + return ID.phantom(); + } + + static get bcs() { + return bcs.struct("ID", { + bytes: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + }); + } + + static fromFields(fields: Record): ID { + return ID.reified().new({ + bytes: decodeFromFields("address", fields.bytes), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): ID { + if (!isID(item.type)) { + throw new Error("not a ID type"); + } + + return ID.reified().new({ + bytes: decodeFromFieldsWithTypes("address", item.fields.bytes), + }); + } + + static fromBcs(data: Uint8Array): ID { + return ID.fromFields(ID.bcs.parse(data)); + } + + toJSONField() { + return { + bytes: this.bytes, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): ID { + return ID.reified().new({ + bytes: decodeFromJSONField("address", field.bytes), + }); + } + + static fromJSON(json: Record): ID { + if (json.$typeName !== ID.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return ID.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): ID { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isID(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a ID object`); + } + return ID.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): ID { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isID(data.bcs.type)) { + throw new Error(`object at is not a ID object`); + } + + return ID.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return ID.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching ID object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isID(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a ID object`); + } + + return ID.fromSuiObjectData(res.data); + } +} + +/* ============================== UID =============================== */ + +export function isUID(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::object::UID`; +} + +export interface UIDFields { + id: ToField; +} + +export type UIDReified = Reified; + +export class UID implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::object::UID`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = UID.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = UID.$isPhantom; + + readonly id: ToField; + + private constructor(typeArgs: [], fields: UIDFields) { + this.$fullTypeName = composeSuiType(UID.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified(): UIDReified { + return { + typeName: UID.$typeName, + fullTypeName: composeSuiType(UID.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: UID.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => UID.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => UID.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => UID.fromBcs(data), + bcs: UID.bcs, + fromJSONField: (field: any) => UID.fromJSONField(field), + fromJSON: (json: Record) => UID.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => UID.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => UID.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => UID.fetch(client, id), + new: (fields: UIDFields) => { + return new UID([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return UID.reified(); + } + + static phantom(): PhantomReified> { + return phantom(UID.reified()); + } + static get p() { + return UID.phantom(); + } + + static get bcs() { + return bcs.struct("UID", { + id: ID.bcs, + }); + } + + static fromFields(fields: Record): UID { + return UID.reified().new({ id: decodeFromFields(ID.reified(), fields.id) }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): UID { + if (!isUID(item.type)) { + throw new Error("not a UID type"); + } + + return UID.reified().new({ + id: decodeFromFieldsWithTypes(ID.reified(), item.fields.id), + }); + } + + static fromBcs(data: Uint8Array): UID { + return UID.fromFields(UID.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): UID { + return UID.reified().new({ + id: decodeFromJSONField(ID.reified(), field.id), + }); + } + + static fromJSON(json: Record): UID { + if (json.$typeName !== UID.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return UID.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): UID { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isUID(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a UID object`); + } + return UID.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): UID { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isUID(data.bcs.type)) { + throw new Error(`object at is not a UID object`); + } + + return UID.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return UID.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching UID object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isUID(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a UID object`); + } + + return UID.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/sui/package/functions.ts b/src/services/models/sui/sui/package/functions.ts new file mode 100644 index 00000000..9420cc7b --- /dev/null +++ b/src/services/models/sui/sui/package/functions.ts @@ -0,0 +1,192 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function version(tx: Transaction, cap: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::version`, + arguments: [obj(tx, cap)], + }); +} + +export function additivePolicy(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::additive_policy`, + arguments: [], + }); +} + +export interface AuthorizeUpgradeArgs { + cap: TransactionObjectInput; + policy: number | TransactionArgument; + digest: Array | TransactionArgument; +} + +export function authorizeUpgrade(tx: Transaction, args: AuthorizeUpgradeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::authorize_upgrade`, + arguments: [obj(tx, args.cap), pure(tx, args.policy, `u8`), pure(tx, args.digest, `vector`)], + }); +} + +export function burnPublisher(tx: Transaction, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::burn_publisher`, + arguments: [obj(tx, self)], + }); +} + +export function claim(tx: Transaction, typeArg: string, otw: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::claim`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, otw)], + }); +} + +export function claimAndKeep(tx: Transaction, typeArg: string, otw: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::claim_and_keep`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, otw)], + }); +} + +export interface CommitUpgradeArgs { + cap: TransactionObjectInput; + receipt: TransactionObjectInput; +} + +export function commitUpgrade(tx: Transaction, args: CommitUpgradeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::commit_upgrade`, + arguments: [obj(tx, args.cap), obj(tx, args.receipt)], + }); +} + +export function compatiblePolicy(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::compatible_policy`, + arguments: [], + }); +} + +export function depOnlyPolicy(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::dep_only_policy`, + arguments: [], + }); +} + +export function fromModule(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::from_module`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function fromPackage(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::from_package`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function makeImmutable(tx: Transaction, cap: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::make_immutable`, + arguments: [obj(tx, cap)], + }); +} + +export function onlyAdditiveUpgrades(tx: Transaction, cap: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::only_additive_upgrades`, + arguments: [obj(tx, cap)], + }); +} + +export function onlyDepUpgrades(tx: Transaction, cap: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::only_dep_upgrades`, + arguments: [obj(tx, cap)], + }); +} + +export function publishedModule(tx: Transaction, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::published_module`, + arguments: [obj(tx, self)], + }); +} + +export function publishedPackage(tx: Transaction, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::published_package`, + arguments: [obj(tx, self)], + }); +} + +export function receiptCap(tx: Transaction, receipt: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::receipt_cap`, + arguments: [obj(tx, receipt)], + }); +} + +export function receiptPackage(tx: Transaction, receipt: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::receipt_package`, + arguments: [obj(tx, receipt)], + }); +} + +export interface RestrictArgs { + cap: TransactionObjectInput; + policy: number | TransactionArgument; +} + +export function restrict(tx: Transaction, args: RestrictArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::restrict`, + arguments: [obj(tx, args.cap), pure(tx, args.policy, `u8`)], + }); +} + +export function ticketDigest(tx: Transaction, ticket: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::ticket_digest`, + arguments: [obj(tx, ticket)], + }); +} + +export function ticketPackage(tx: Transaction, ticket: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::ticket_package`, + arguments: [obj(tx, ticket)], + }); +} + +export function ticketPolicy(tx: Transaction, ticket: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::ticket_policy`, + arguments: [obj(tx, ticket)], + }); +} + +export function upgradePackage(tx: Transaction, cap: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::upgrade_package`, + arguments: [obj(tx, cap)], + }); +} + +export function upgradePolicy(tx: Transaction, cap: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::package::upgrade_policy`, + arguments: [obj(tx, cap)], + }); +} diff --git a/src/services/models/sui/sui/package/structs.ts b/src/services/models/sui/sui/package/structs.ts new file mode 100644 index 00000000..b563983f --- /dev/null +++ b/src/services/models/sui/sui/package/structs.ts @@ -0,0 +1,746 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { String } from "../../_dependencies/source/0x1/ascii/structs"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { Vector } from "../../_framework/vector"; +import { PKG_V26 } from "../index"; +import { ID, UID } from "../object/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Publisher =============================== */ + +export function isPublisher(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::package::Publisher`; +} + +export interface PublisherFields { + id: ToField; + package: ToField; + moduleName: ToField; +} + +export type PublisherReified = Reified; + +export class Publisher implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::package::Publisher`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Publisher.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Publisher.$isPhantom; + + readonly id: ToField; + readonly package: ToField; + readonly moduleName: ToField; + + private constructor(typeArgs: [], fields: PublisherFields) { + this.$fullTypeName = composeSuiType(Publisher.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.package = fields.package; + this.moduleName = fields.moduleName; + } + + static reified(): PublisherReified { + return { + typeName: Publisher.$typeName, + fullTypeName: composeSuiType(Publisher.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Publisher.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Publisher.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Publisher.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Publisher.fromBcs(data), + bcs: Publisher.bcs, + fromJSONField: (field: any) => Publisher.fromJSONField(field), + fromJSON: (json: Record) => Publisher.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Publisher.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Publisher.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Publisher.fetch(client, id), + new: (fields: PublisherFields) => { + return new Publisher([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Publisher.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Publisher.reified()); + } + static get p() { + return Publisher.phantom(); + } + + static get bcs() { + return bcs.struct("Publisher", { + id: UID.bcs, + package: String.bcs, + module_name: String.bcs, + }); + } + + static fromFields(fields: Record): Publisher { + return Publisher.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + package: decodeFromFields(String.reified(), fields.package), + moduleName: decodeFromFields(String.reified(), fields.module_name), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Publisher { + if (!isPublisher(item.type)) { + throw new Error("not a Publisher type"); + } + + return Publisher.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + package: decodeFromFieldsWithTypes(String.reified(), item.fields.package), + moduleName: decodeFromFieldsWithTypes(String.reified(), item.fields.module_name), + }); + } + + static fromBcs(data: Uint8Array): Publisher { + return Publisher.fromFields(Publisher.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + package: this.package, + moduleName: this.moduleName, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Publisher { + return Publisher.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + package: decodeFromJSONField(String.reified(), field.package), + moduleName: decodeFromJSONField(String.reified(), field.moduleName), + }); + } + + static fromJSON(json: Record): Publisher { + if (json.$typeName !== Publisher.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Publisher.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Publisher { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isPublisher(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Publisher object`); + } + return Publisher.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Publisher { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isPublisher(data.bcs.type)) { + throw new Error(`object at is not a Publisher object`); + } + + return Publisher.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Publisher.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Publisher object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isPublisher(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Publisher object`); + } + + return Publisher.fromSuiObjectData(res.data); + } +} + +/* ============================== UpgradeCap =============================== */ + +export function isUpgradeCap(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::package::UpgradeCap`; +} + +export interface UpgradeCapFields { + id: ToField; + package: ToField; + version: ToField<"u64">; + policy: ToField<"u8">; +} + +export type UpgradeCapReified = Reified; + +export class UpgradeCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::package::UpgradeCap`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = UpgradeCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = UpgradeCap.$isPhantom; + + readonly id: ToField; + readonly package: ToField; + readonly version: ToField<"u64">; + readonly policy: ToField<"u8">; + + private constructor(typeArgs: [], fields: UpgradeCapFields) { + this.$fullTypeName = composeSuiType(UpgradeCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.package = fields.package; + this.version = fields.version; + this.policy = fields.policy; + } + + static reified(): UpgradeCapReified { + return { + typeName: UpgradeCap.$typeName, + fullTypeName: composeSuiType(UpgradeCap.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: UpgradeCap.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => UpgradeCap.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => UpgradeCap.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => UpgradeCap.fromBcs(data), + bcs: UpgradeCap.bcs, + fromJSONField: (field: any) => UpgradeCap.fromJSONField(field), + fromJSON: (json: Record) => UpgradeCap.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => UpgradeCap.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => UpgradeCap.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => UpgradeCap.fetch(client, id), + new: (fields: UpgradeCapFields) => { + return new UpgradeCap([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return UpgradeCap.reified(); + } + + static phantom(): PhantomReified> { + return phantom(UpgradeCap.reified()); + } + static get p() { + return UpgradeCap.phantom(); + } + + static get bcs() { + return bcs.struct("UpgradeCap", { + id: UID.bcs, + package: ID.bcs, + version: bcs.u64(), + policy: bcs.u8(), + }); + } + + static fromFields(fields: Record): UpgradeCap { + return UpgradeCap.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + package: decodeFromFields(ID.reified(), fields.package), + version: decodeFromFields("u64", fields.version), + policy: decodeFromFields("u8", fields.policy), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): UpgradeCap { + if (!isUpgradeCap(item.type)) { + throw new Error("not a UpgradeCap type"); + } + + return UpgradeCap.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + package: decodeFromFieldsWithTypes(ID.reified(), item.fields.package), + version: decodeFromFieldsWithTypes("u64", item.fields.version), + policy: decodeFromFieldsWithTypes("u8", item.fields.policy), + }); + } + + static fromBcs(data: Uint8Array): UpgradeCap { + return UpgradeCap.fromFields(UpgradeCap.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + package: this.package, + version: this.version.toString(), + policy: this.policy, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): UpgradeCap { + return UpgradeCap.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + package: decodeFromJSONField(ID.reified(), field.package), + version: decodeFromJSONField("u64", field.version), + policy: decodeFromJSONField("u8", field.policy), + }); + } + + static fromJSON(json: Record): UpgradeCap { + if (json.$typeName !== UpgradeCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return UpgradeCap.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): UpgradeCap { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isUpgradeCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a UpgradeCap object`); + } + return UpgradeCap.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): UpgradeCap { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isUpgradeCap(data.bcs.type)) { + throw new Error(`object at is not a UpgradeCap object`); + } + + return UpgradeCap.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return UpgradeCap.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching UpgradeCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isUpgradeCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a UpgradeCap object`); + } + + return UpgradeCap.fromSuiObjectData(res.data); + } +} + +/* ============================== UpgradeReceipt =============================== */ + +export function isUpgradeReceipt(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::package::UpgradeReceipt`; +} + +export interface UpgradeReceiptFields { + cap: ToField; + package: ToField; +} + +export type UpgradeReceiptReified = Reified; + +export class UpgradeReceipt implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::package::UpgradeReceipt`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = UpgradeReceipt.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = UpgradeReceipt.$isPhantom; + + readonly cap: ToField; + readonly package: ToField; + + private constructor(typeArgs: [], fields: UpgradeReceiptFields) { + this.$fullTypeName = composeSuiType(UpgradeReceipt.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.cap = fields.cap; + this.package = fields.package; + } + + static reified(): UpgradeReceiptReified { + return { + typeName: UpgradeReceipt.$typeName, + fullTypeName: composeSuiType(UpgradeReceipt.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: UpgradeReceipt.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => UpgradeReceipt.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => UpgradeReceipt.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => UpgradeReceipt.fromBcs(data), + bcs: UpgradeReceipt.bcs, + fromJSONField: (field: any) => UpgradeReceipt.fromJSONField(field), + fromJSON: (json: Record) => UpgradeReceipt.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => UpgradeReceipt.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => UpgradeReceipt.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => UpgradeReceipt.fetch(client, id), + new: (fields: UpgradeReceiptFields) => { + return new UpgradeReceipt([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return UpgradeReceipt.reified(); + } + + static phantom(): PhantomReified> { + return phantom(UpgradeReceipt.reified()); + } + static get p() { + return UpgradeReceipt.phantom(); + } + + static get bcs() { + return bcs.struct("UpgradeReceipt", { + cap: ID.bcs, + package: ID.bcs, + }); + } + + static fromFields(fields: Record): UpgradeReceipt { + return UpgradeReceipt.reified().new({ + cap: decodeFromFields(ID.reified(), fields.cap), + package: decodeFromFields(ID.reified(), fields.package), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): UpgradeReceipt { + if (!isUpgradeReceipt(item.type)) { + throw new Error("not a UpgradeReceipt type"); + } + + return UpgradeReceipt.reified().new({ + cap: decodeFromFieldsWithTypes(ID.reified(), item.fields.cap), + package: decodeFromFieldsWithTypes(ID.reified(), item.fields.package), + }); + } + + static fromBcs(data: Uint8Array): UpgradeReceipt { + return UpgradeReceipt.fromFields(UpgradeReceipt.bcs.parse(data)); + } + + toJSONField() { + return { + cap: this.cap, + package: this.package, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): UpgradeReceipt { + return UpgradeReceipt.reified().new({ + cap: decodeFromJSONField(ID.reified(), field.cap), + package: decodeFromJSONField(ID.reified(), field.package), + }); + } + + static fromJSON(json: Record): UpgradeReceipt { + if (json.$typeName !== UpgradeReceipt.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return UpgradeReceipt.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): UpgradeReceipt { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isUpgradeReceipt(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a UpgradeReceipt object`); + } + return UpgradeReceipt.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): UpgradeReceipt { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isUpgradeReceipt(data.bcs.type)) { + throw new Error(`object at is not a UpgradeReceipt object`); + } + + return UpgradeReceipt.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return UpgradeReceipt.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching UpgradeReceipt object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isUpgradeReceipt(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a UpgradeReceipt object`); + } + + return UpgradeReceipt.fromSuiObjectData(res.data); + } +} + +/* ============================== UpgradeTicket =============================== */ + +export function isUpgradeTicket(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::package::UpgradeTicket`; +} + +export interface UpgradeTicketFields { + cap: ToField; + package: ToField; + policy: ToField<"u8">; + digest: ToField>; +} + +export type UpgradeTicketReified = Reified; + +export class UpgradeTicket implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::package::UpgradeTicket`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = UpgradeTicket.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = UpgradeTicket.$isPhantom; + + readonly cap: ToField; + readonly package: ToField; + readonly policy: ToField<"u8">; + readonly digest: ToField>; + + private constructor(typeArgs: [], fields: UpgradeTicketFields) { + this.$fullTypeName = composeSuiType(UpgradeTicket.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.cap = fields.cap; + this.package = fields.package; + this.policy = fields.policy; + this.digest = fields.digest; + } + + static reified(): UpgradeTicketReified { + return { + typeName: UpgradeTicket.$typeName, + fullTypeName: composeSuiType(UpgradeTicket.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: UpgradeTicket.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => UpgradeTicket.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => UpgradeTicket.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => UpgradeTicket.fromBcs(data), + bcs: UpgradeTicket.bcs, + fromJSONField: (field: any) => UpgradeTicket.fromJSONField(field), + fromJSON: (json: Record) => UpgradeTicket.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => UpgradeTicket.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => UpgradeTicket.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => UpgradeTicket.fetch(client, id), + new: (fields: UpgradeTicketFields) => { + return new UpgradeTicket([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return UpgradeTicket.reified(); + } + + static phantom(): PhantomReified> { + return phantom(UpgradeTicket.reified()); + } + static get p() { + return UpgradeTicket.phantom(); + } + + static get bcs() { + return bcs.struct("UpgradeTicket", { + cap: ID.bcs, + package: ID.bcs, + policy: bcs.u8(), + digest: bcs.vector(bcs.u8()), + }); + } + + static fromFields(fields: Record): UpgradeTicket { + return UpgradeTicket.reified().new({ + cap: decodeFromFields(ID.reified(), fields.cap), + package: decodeFromFields(ID.reified(), fields.package), + policy: decodeFromFields("u8", fields.policy), + digest: decodeFromFields(reified.vector("u8"), fields.digest), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): UpgradeTicket { + if (!isUpgradeTicket(item.type)) { + throw new Error("not a UpgradeTicket type"); + } + + return UpgradeTicket.reified().new({ + cap: decodeFromFieldsWithTypes(ID.reified(), item.fields.cap), + package: decodeFromFieldsWithTypes(ID.reified(), item.fields.package), + policy: decodeFromFieldsWithTypes("u8", item.fields.policy), + digest: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.digest), + }); + } + + static fromBcs(data: Uint8Array): UpgradeTicket { + return UpgradeTicket.fromFields(UpgradeTicket.bcs.parse(data)); + } + + toJSONField() { + return { + cap: this.cap, + package: this.package, + policy: this.policy, + digest: fieldToJSON>(`vector`, this.digest), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): UpgradeTicket { + return UpgradeTicket.reified().new({ + cap: decodeFromJSONField(ID.reified(), field.cap), + package: decodeFromJSONField(ID.reified(), field.package), + policy: decodeFromJSONField("u8", field.policy), + digest: decodeFromJSONField(reified.vector("u8"), field.digest), + }); + } + + static fromJSON(json: Record): UpgradeTicket { + if (json.$typeName !== UpgradeTicket.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return UpgradeTicket.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): UpgradeTicket { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isUpgradeTicket(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a UpgradeTicket object`); + } + return UpgradeTicket.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): UpgradeTicket { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isUpgradeTicket(data.bcs.type)) { + throw new Error(`object at is not a UpgradeTicket object`); + } + + return UpgradeTicket.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return UpgradeTicket.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching UpgradeTicket object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isUpgradeTicket(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a UpgradeTicket object`); + } + + return UpgradeTicket.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/sui/pay/functions.ts b/src/services/models/sui/sui/pay/functions.ts new file mode 100644 index 00000000..90bc5afb --- /dev/null +++ b/src/services/models/sui/sui/pay/functions.ts @@ -0,0 +1,105 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure, vector } from "../../_framework/util"; +import { Coin } from "../coin/structs"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface JoinArgs { + self: TransactionObjectInput; + coin: TransactionObjectInput; +} + +export function join(tx: Transaction, typeArg: string, args: JoinArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pay::join`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.coin)], + }); +} + +export interface SplitArgs { + coin: TransactionObjectInput; + splitAmount: bigint | TransactionArgument; +} + +export function split(tx: Transaction, typeArg: string, args: SplitArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pay::split`, + typeArguments: [typeArg], + arguments: [obj(tx, args.coin), pure(tx, args.splitAmount, `u64`)], + }); +} + +export interface DivideAndKeepArgs { + self: TransactionObjectInput; + n: bigint | TransactionArgument; +} + +export function divideAndKeep(tx: Transaction, typeArg: string, args: DivideAndKeepArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pay::divide_and_keep`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), pure(tx, args.n, `u64`)], + }); +} + +export interface JoinVecArgs { + self: TransactionObjectInput; + coins: Array | TransactionArgument; +} + +export function joinVec(tx: Transaction, typeArg: string, args: JoinVecArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pay::join_vec`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), vector(tx, `${Coin.$typeName}<${typeArg}>`, args.coins)], + }); +} + +export interface JoinVecAndTransferArgs { + coins: Array | TransactionArgument; + receiver: string | TransactionArgument; +} + +export function joinVecAndTransfer(tx: Transaction, typeArg: string, args: JoinVecAndTransferArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pay::join_vec_and_transfer`, + typeArguments: [typeArg], + arguments: [vector(tx, `${Coin.$typeName}<${typeArg}>`, args.coins), pure(tx, args.receiver, `address`)], + }); +} + +export function keep(tx: Transaction, typeArg: string, c: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pay::keep`, + typeArguments: [typeArg], + arguments: [obj(tx, c)], + }); +} + +export interface SplitAndTransferArgs { + c: TransactionObjectInput; + amount: bigint | TransactionArgument; + recipient: string | TransactionArgument; +} + +export function splitAndTransfer(tx: Transaction, typeArg: string, args: SplitAndTransferArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pay::split_and_transfer`, + typeArguments: [typeArg], + arguments: [obj(tx, args.c), pure(tx, args.amount, `u64`), pure(tx, args.recipient, `address`)], + }); +} + +export interface SplitVecArgs { + self: TransactionObjectInput; + splitAmounts: Array | TransactionArgument; +} + +export function splitVec(tx: Transaction, typeArg: string, args: SplitVecArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::pay::split_vec`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), pure(tx, args.splitAmounts, `vector`)], + }); +} diff --git a/src/services/models/sui/sui/poseidon/functions.ts b/src/services/models/sui/sui/poseidon/functions.ts new file mode 100644 index 00000000..591ce710 --- /dev/null +++ b/src/services/models/sui/sui/poseidon/functions.ts @@ -0,0 +1,21 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { pure } from "../../_framework/util"; +import { Transaction, TransactionArgument } from "@mysten/sui/transactions"; + +export function poseidonBn254(tx: Transaction, data: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::poseidon::poseidon_bn254`, + arguments: [pure(tx, data, `vector`)], + }); +} + +export function poseidonBn254Internal( + tx: Transaction, + data: Array | TransactionArgument> | TransactionArgument +) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::poseidon::poseidon_bn254_internal`, + arguments: [pure(tx, data, `vector>`)], + }); +} diff --git a/src/services/models/sui/sui/priority-queue/functions.ts b/src/services/models/sui/sui/priority-queue/functions.ts new file mode 100644 index 00000000..c91cd9fd --- /dev/null +++ b/src/services/models/sui/sui/priority-queue/functions.ts @@ -0,0 +1,100 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj, pure, vector } from "../../_framework/util"; +import { Entry } from "./structs"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface InsertArgs { + pq: TransactionObjectInput; + priority: bigint | TransactionArgument; + value: GenericArg; +} + +export function insert(tx: Transaction, typeArg: string, args: InsertArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::priority_queue::insert`, + typeArguments: [typeArg], + arguments: [obj(tx, args.pq), pure(tx, args.priority, `u64`), generic(tx, `${typeArg}`, args.value)], + }); +} + +export function new_(tx: Transaction, typeArg: string, entries: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::priority_queue::new`, + typeArguments: [typeArg], + arguments: [vector(tx, `${Entry.$typeName}<${typeArg}>`, entries)], + }); +} + +export interface CreateEntriesArgs { + p: Array | TransactionArgument; + v: Array | TransactionArgument; +} + +export function createEntries(tx: Transaction, typeArg: string, args: CreateEntriesArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::priority_queue::create_entries`, + typeArguments: [typeArg], + arguments: [pure(tx, args.p, `vector`), vector(tx, `${typeArg}`, args.v)], + }); +} + +export interface MaxHeapifyRecursiveArgs { + v: Array | TransactionArgument; + len: bigint | TransactionArgument; + i: bigint | TransactionArgument; +} + +export function maxHeapifyRecursive(tx: Transaction, typeArg: string, args: MaxHeapifyRecursiveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::priority_queue::max_heapify_recursive`, + typeArguments: [typeArg], + arguments: [ + vector(tx, `${Entry.$typeName}<${typeArg}>`, args.v), + pure(tx, args.len, `u64`), + pure(tx, args.i, `u64`), + ], + }); +} + +export interface NewEntryArgs { + priority: bigint | TransactionArgument; + value: GenericArg; +} + +export function newEntry(tx: Transaction, typeArg: string, args: NewEntryArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::priority_queue::new_entry`, + typeArguments: [typeArg], + arguments: [pure(tx, args.priority, `u64`), generic(tx, `${typeArg}`, args.value)], + }); +} + +export function popMax(tx: Transaction, typeArg: string, pq: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::priority_queue::pop_max`, + typeArguments: [typeArg], + arguments: [obj(tx, pq)], + }); +} + +export function priorities(tx: Transaction, typeArg: string, pq: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::priority_queue::priorities`, + typeArguments: [typeArg], + arguments: [obj(tx, pq)], + }); +} + +export interface RestoreHeapRecursiveArgs { + v: Array | TransactionArgument; + i: bigint | TransactionArgument; +} + +export function restoreHeapRecursive(tx: Transaction, typeArg: string, args: RestoreHeapRecursiveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::priority_queue::restore_heap_recursive`, + typeArguments: [typeArg], + arguments: [vector(tx, `${Entry.$typeName}<${typeArg}>`, args.v), pure(tx, args.i, `u64`)], + }); +} diff --git a/src/services/models/sui/sui/priority-queue/structs.ts b/src/services/models/sui/sui/priority-queue/structs.ts new file mode 100644 index 00000000..1cc8854e --- /dev/null +++ b/src/services/models/sui/sui/priority-queue/structs.ts @@ -0,0 +1,432 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeArgument, + ToTypeStr, + TypeArgument, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + fieldToJSON, + phantom, + toBcs, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { Vector } from "../../_framework/vector"; +import { PKG_V26 } from "../index"; +import { BcsType, bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Entry =============================== */ + +export function isEntry(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::priority_queue::Entry` + "<"); +} + +export interface EntryFields { + priority: ToField<"u64">; + value: ToField; +} + +export type EntryReified = Reified, EntryFields>; + +export class Entry implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::priority_queue::Entry`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [false] as const; + + readonly $typeName = Entry.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [ToTypeStr]; + readonly $isPhantom = Entry.$isPhantom; + + readonly priority: ToField<"u64">; + readonly value: ToField; + + private constructor(typeArgs: [ToTypeStr], fields: EntryFields) { + this.$fullTypeName = composeSuiType(Entry.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.priority = fields.priority; + this.value = fields.value; + } + + static reified>(T: T): EntryReified> { + return { + typeName: Entry.$typeName, + fullTypeName: composeSuiType(Entry.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [ToTypeStr>], + isPhantom: Entry.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => Entry.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Entry.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => Entry.fromBcs(T, data), + bcs: Entry.bcs(toBcs(T)), + fromJSONField: (field: any) => Entry.fromJSONField(T, field), + fromJSON: (json: Record) => Entry.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => Entry.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => Entry.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => Entry.fetch(client, T, id), + new: (fields: EntryFields>) => { + return new Entry([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Entry.reified; + } + + static phantom>(T: T): PhantomReified>>> { + return phantom(Entry.reified(T)); + } + static get p() { + return Entry.phantom; + } + + static get bcs() { + return >(T: T) => + bcs.struct(`Entry<${T.name}>`, { + priority: bcs.u64(), + value: T, + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): Entry> { + return Entry.reified(typeArg).new({ + priority: decodeFromFields("u64", fields.priority), + value: decodeFromFields(typeArg, fields.value), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): Entry> { + if (!isEntry(item.type)) { + throw new Error("not a Entry type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Entry.reified(typeArg).new({ + priority: decodeFromFieldsWithTypes("u64", item.fields.priority), + value: decodeFromFieldsWithTypes(typeArg, item.fields.value), + }); + } + + static fromBcs>(typeArg: T, data: Uint8Array): Entry> { + const typeArgs = [typeArg]; + + return Entry.fromFields(typeArg, Entry.bcs(toBcs(typeArgs[0])).parse(data)); + } + + toJSONField() { + return { + priority: this.priority.toString(), + value: fieldToJSON(this.$typeArgs[0], this.value), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>(typeArg: T, field: any): Entry> { + return Entry.reified(typeArg).new({ + priority: decodeFromJSONField("u64", field.priority), + value: decodeFromJSONField(typeArg, field.value), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): Entry> { + if (json.$typeName !== Entry.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Entry.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Entry.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): Entry> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isEntry(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Entry object`); + } + return Entry.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): Entry> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isEntry(data.bcs.type)) { + throw new Error(`object at is not a Entry object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Entry.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Entry.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Entry object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isEntry(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Entry object`); + } + + return Entry.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== PriorityQueue =============================== */ + +export function isPriorityQueue(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::priority_queue::PriorityQueue` + "<"); +} + +export interface PriorityQueueFields { + entries: ToField>>; +} + +export type PriorityQueueReified = Reified, PriorityQueueFields>; + +export class PriorityQueue implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::priority_queue::PriorityQueue`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [false] as const; + + readonly $typeName = PriorityQueue.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [ToTypeStr]; + readonly $isPhantom = PriorityQueue.$isPhantom; + + readonly entries: ToField>>; + + private constructor(typeArgs: [ToTypeStr], fields: PriorityQueueFields) { + this.$fullTypeName = composeSuiType(PriorityQueue.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.entries = fields.entries; + } + + static reified>(T: T): PriorityQueueReified> { + return { + typeName: PriorityQueue.$typeName, + fullTypeName: composeSuiType(PriorityQueue.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [ToTypeStr>], + isPhantom: PriorityQueue.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => PriorityQueue.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => PriorityQueue.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => PriorityQueue.fromBcs(T, data), + bcs: PriorityQueue.bcs(toBcs(T)), + fromJSONField: (field: any) => PriorityQueue.fromJSONField(T, field), + fromJSON: (json: Record) => PriorityQueue.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => PriorityQueue.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => PriorityQueue.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => PriorityQueue.fetch(client, T, id), + new: (fields: PriorityQueueFields>) => { + return new PriorityQueue([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return PriorityQueue.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(PriorityQueue.reified(T)); + } + static get p() { + return PriorityQueue.phantom; + } + + static get bcs() { + return >(T: T) => + bcs.struct(`PriorityQueue<${T.name}>`, { + entries: bcs.vector(Entry.bcs(T)), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): PriorityQueue> { + return PriorityQueue.reified(typeArg).new({ + entries: decodeFromFields(reified.vector(Entry.reified(typeArg)), fields.entries), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): PriorityQueue> { + if (!isPriorityQueue(item.type)) { + throw new Error("not a PriorityQueue type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return PriorityQueue.reified(typeArg).new({ + entries: decodeFromFieldsWithTypes(reified.vector(Entry.reified(typeArg)), item.fields.entries), + }); + } + + static fromBcs>(typeArg: T, data: Uint8Array): PriorityQueue> { + const typeArgs = [typeArg]; + + return PriorityQueue.fromFields(typeArg, PriorityQueue.bcs(toBcs(typeArgs[0])).parse(data)); + } + + toJSONField() { + return { + entries: fieldToJSON>>(`vector<${Entry.$typeName}<${this.$typeArgs[0]}>>`, this.entries), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>(typeArg: T, field: any): PriorityQueue> { + return PriorityQueue.reified(typeArg).new({ + entries: decodeFromJSONField(reified.vector(Entry.reified(typeArg)), field.entries), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): PriorityQueue> { + if (json.$typeName !== PriorityQueue.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(PriorityQueue.$typeName, extractType(typeArg)), json.$typeArgs, [ + typeArg, + ]); + + return PriorityQueue.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): PriorityQueue> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isPriorityQueue(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a PriorityQueue object`); + } + return PriorityQueue.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): PriorityQueue> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isPriorityQueue(data.bcs.type)) { + throw new Error(`object at is not a PriorityQueue object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return PriorityQueue.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return PriorityQueue.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching PriorityQueue object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isPriorityQueue(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a PriorityQueue object`); + } + + return PriorityQueue.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/sui/random/functions.ts b/src/services/models/sui/sui/random/functions.ts new file mode 100644 index 00000000..6203644c --- /dev/null +++ b/src/services/models/sui/sui/random/functions.ts @@ -0,0 +1,229 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, obj, pure, vector } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function create(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::create`, + arguments: [], + }); +} + +export function loadInner(tx: Transaction, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::load_inner`, + arguments: [obj(tx, self)], + }); +} + +export function loadInnerMut(tx: Transaction, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::load_inner_mut`, + arguments: [obj(tx, self)], + }); +} + +export function deriveNextBlock(tx: Transaction, g: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::derive_next_block`, + arguments: [obj(tx, g)], + }); +} + +export function fillBuffer(tx: Transaction, g: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::fill_buffer`, + arguments: [obj(tx, g)], + }); +} + +export function generateBool(tx: Transaction, g: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::generate_bool`, + arguments: [obj(tx, g)], + }); +} + +export interface GenerateBytesArgs { + g: TransactionObjectInput; + numOfBytes: number | TransactionArgument; +} + +export function generateBytes(tx: Transaction, args: GenerateBytesArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::generate_bytes`, + arguments: [obj(tx, args.g), pure(tx, args.numOfBytes, `u16`)], + }); +} + +export function generateU128(tx: Transaction, g: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::generate_u128`, + arguments: [obj(tx, g)], + }); +} + +export interface GenerateU128InRangeArgs { + g: TransactionObjectInput; + min: bigint | TransactionArgument; + max: bigint | TransactionArgument; +} + +export function generateU128InRange(tx: Transaction, args: GenerateU128InRangeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::generate_u128_in_range`, + arguments: [obj(tx, args.g), pure(tx, args.min, `u128`), pure(tx, args.max, `u128`)], + }); +} + +export function generateU16(tx: Transaction, g: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::generate_u16`, + arguments: [obj(tx, g)], + }); +} + +export interface GenerateU16InRangeArgs { + g: TransactionObjectInput; + min: number | TransactionArgument; + max: number | TransactionArgument; +} + +export function generateU16InRange(tx: Transaction, args: GenerateU16InRangeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::generate_u16_in_range`, + arguments: [obj(tx, args.g), pure(tx, args.min, `u16`), pure(tx, args.max, `u16`)], + }); +} + +export function generateU256(tx: Transaction, g: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::generate_u256`, + arguments: [obj(tx, g)], + }); +} + +export function generateU32(tx: Transaction, g: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::generate_u32`, + arguments: [obj(tx, g)], + }); +} + +export interface GenerateU32InRangeArgs { + g: TransactionObjectInput; + min: number | TransactionArgument; + max: number | TransactionArgument; +} + +export function generateU32InRange(tx: Transaction, args: GenerateU32InRangeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::generate_u32_in_range`, + arguments: [obj(tx, args.g), pure(tx, args.min, `u32`), pure(tx, args.max, `u32`)], + }); +} + +export function generateU64(tx: Transaction, g: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::generate_u64`, + arguments: [obj(tx, g)], + }); +} + +export interface GenerateU64InRangeArgs { + g: TransactionObjectInput; + min: bigint | TransactionArgument; + max: bigint | TransactionArgument; +} + +export function generateU64InRange(tx: Transaction, args: GenerateU64InRangeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::generate_u64_in_range`, + arguments: [obj(tx, args.g), pure(tx, args.min, `u64`), pure(tx, args.max, `u64`)], + }); +} + +export function generateU8(tx: Transaction, g: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::generate_u8`, + arguments: [obj(tx, g)], + }); +} + +export interface GenerateU8InRangeArgs { + g: TransactionObjectInput; + min: number | TransactionArgument; + max: number | TransactionArgument; +} + +export function generateU8InRange(tx: Transaction, args: GenerateU8InRangeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::generate_u8_in_range`, + arguments: [obj(tx, args.g), pure(tx, args.min, `u8`), pure(tx, args.max, `u8`)], + }); +} + +export function newGenerator(tx: Transaction, r: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::new_generator`, + arguments: [obj(tx, r)], + }); +} + +export interface ShuffleArgs { + g: TransactionObjectInput; + v: Array | TransactionArgument; +} + +export function shuffle(tx: Transaction, typeArg: string, args: ShuffleArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::shuffle`, + typeArguments: [typeArg], + arguments: [obj(tx, args.g), vector(tx, `${typeArg}`, args.v)], + }); +} + +export interface U128InRangeArgs { + g: TransactionObjectInput; + min: bigint | TransactionArgument; + max: bigint | TransactionArgument; + numOfBytes: number | TransactionArgument; +} + +export function u128InRange(tx: Transaction, args: U128InRangeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::u128_in_range`, + arguments: [ + obj(tx, args.g), + pure(tx, args.min, `u128`), + pure(tx, args.max, `u128`), + pure(tx, args.numOfBytes, `u8`), + ], + }); +} + +export interface U256FromBytesArgs { + g: TransactionObjectInput; + numOfBytes: number | TransactionArgument; +} + +export function u256FromBytes(tx: Transaction, args: U256FromBytesArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::u256_from_bytes`, + arguments: [obj(tx, args.g), pure(tx, args.numOfBytes, `u8`)], + }); +} + +export interface UpdateRandomnessStateArgs { + self: TransactionObjectInput; + newRound: bigint | TransactionArgument; + newBytes: Array | TransactionArgument; +} + +export function updateRandomnessState(tx: Transaction, args: UpdateRandomnessStateArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::random::update_randomness_state`, + arguments: [obj(tx, args.self), pure(tx, args.newRound, `u64`), pure(tx, args.newBytes, `vector`)], + }); +} diff --git a/src/services/models/sui/sui/random/structs.ts b/src/services/models/sui/sui/random/structs.ts new file mode 100644 index 00000000..d28a57e7 --- /dev/null +++ b/src/services/models/sui/sui/random/structs.ts @@ -0,0 +1,559 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { Vector } from "../../_framework/vector"; +import { PKG_V26 } from "../index"; +import { UID } from "../object/structs"; +import { Versioned } from "../versioned/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Random =============================== */ + +export function isRandom(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::random::Random`; +} + +export interface RandomFields { + id: ToField; + inner: ToField; +} + +export type RandomReified = Reified; + +export class Random implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::random::Random`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Random.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Random.$isPhantom; + + readonly id: ToField; + readonly inner: ToField; + + private constructor(typeArgs: [], fields: RandomFields) { + this.$fullTypeName = composeSuiType(Random.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.inner = fields.inner; + } + + static reified(): RandomReified { + return { + typeName: Random.$typeName, + fullTypeName: composeSuiType(Random.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Random.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Random.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Random.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Random.fromBcs(data), + bcs: Random.bcs, + fromJSONField: (field: any) => Random.fromJSONField(field), + fromJSON: (json: Record) => Random.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Random.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Random.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Random.fetch(client, id), + new: (fields: RandomFields) => { + return new Random([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Random.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Random.reified()); + } + static get p() { + return Random.phantom(); + } + + static get bcs() { + return bcs.struct("Random", { + id: UID.bcs, + inner: Versioned.bcs, + }); + } + + static fromFields(fields: Record): Random { + return Random.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + inner: decodeFromFields(Versioned.reified(), fields.inner), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Random { + if (!isRandom(item.type)) { + throw new Error("not a Random type"); + } + + return Random.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + inner: decodeFromFieldsWithTypes(Versioned.reified(), item.fields.inner), + }); + } + + static fromBcs(data: Uint8Array): Random { + return Random.fromFields(Random.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + inner: this.inner.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Random { + return Random.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + inner: decodeFromJSONField(Versioned.reified(), field.inner), + }); + } + + static fromJSON(json: Record): Random { + if (json.$typeName !== Random.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Random.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Random { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isRandom(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Random object`); + } + return Random.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Random { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isRandom(data.bcs.type)) { + throw new Error(`object at is not a Random object`); + } + + return Random.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Random.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Random object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isRandom(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Random object`); + } + + return Random.fromSuiObjectData(res.data); + } +} + +/* ============================== RandomGenerator =============================== */ + +export function isRandomGenerator(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::random::RandomGenerator`; +} + +export interface RandomGeneratorFields { + seed: ToField>; + counter: ToField<"u16">; + buffer: ToField>; +} + +export type RandomGeneratorReified = Reified; + +export class RandomGenerator implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::random::RandomGenerator`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = RandomGenerator.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = RandomGenerator.$isPhantom; + + readonly seed: ToField>; + readonly counter: ToField<"u16">; + readonly buffer: ToField>; + + private constructor(typeArgs: [], fields: RandomGeneratorFields) { + this.$fullTypeName = composeSuiType(RandomGenerator.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.seed = fields.seed; + this.counter = fields.counter; + this.buffer = fields.buffer; + } + + static reified(): RandomGeneratorReified { + return { + typeName: RandomGenerator.$typeName, + fullTypeName: composeSuiType(RandomGenerator.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: RandomGenerator.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => RandomGenerator.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => RandomGenerator.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => RandomGenerator.fromBcs(data), + bcs: RandomGenerator.bcs, + fromJSONField: (field: any) => RandomGenerator.fromJSONField(field), + fromJSON: (json: Record) => RandomGenerator.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => RandomGenerator.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => RandomGenerator.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => RandomGenerator.fetch(client, id), + new: (fields: RandomGeneratorFields) => { + return new RandomGenerator([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return RandomGenerator.reified(); + } + + static phantom(): PhantomReified> { + return phantom(RandomGenerator.reified()); + } + static get p() { + return RandomGenerator.phantom(); + } + + static get bcs() { + return bcs.struct("RandomGenerator", { + seed: bcs.vector(bcs.u8()), + counter: bcs.u16(), + buffer: bcs.vector(bcs.u8()), + }); + } + + static fromFields(fields: Record): RandomGenerator { + return RandomGenerator.reified().new({ + seed: decodeFromFields(reified.vector("u8"), fields.seed), + counter: decodeFromFields("u16", fields.counter), + buffer: decodeFromFields(reified.vector("u8"), fields.buffer), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): RandomGenerator { + if (!isRandomGenerator(item.type)) { + throw new Error("not a RandomGenerator type"); + } + + return RandomGenerator.reified().new({ + seed: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.seed), + counter: decodeFromFieldsWithTypes("u16", item.fields.counter), + buffer: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.buffer), + }); + } + + static fromBcs(data: Uint8Array): RandomGenerator { + return RandomGenerator.fromFields(RandomGenerator.bcs.parse(data)); + } + + toJSONField() { + return { + seed: fieldToJSON>(`vector`, this.seed), + counter: this.counter, + buffer: fieldToJSON>(`vector`, this.buffer), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): RandomGenerator { + return RandomGenerator.reified().new({ + seed: decodeFromJSONField(reified.vector("u8"), field.seed), + counter: decodeFromJSONField("u16", field.counter), + buffer: decodeFromJSONField(reified.vector("u8"), field.buffer), + }); + } + + static fromJSON(json: Record): RandomGenerator { + if (json.$typeName !== RandomGenerator.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return RandomGenerator.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): RandomGenerator { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isRandomGenerator(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a RandomGenerator object`); + } + return RandomGenerator.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): RandomGenerator { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isRandomGenerator(data.bcs.type)) { + throw new Error(`object at is not a RandomGenerator object`); + } + + return RandomGenerator.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return RandomGenerator.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching RandomGenerator object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isRandomGenerator(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a RandomGenerator object`); + } + + return RandomGenerator.fromSuiObjectData(res.data); + } +} + +/* ============================== RandomInner =============================== */ + +export function isRandomInner(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::random::RandomInner`; +} + +export interface RandomInnerFields { + version: ToField<"u64">; + epoch: ToField<"u64">; + randomnessRound: ToField<"u64">; + randomBytes: ToField>; +} + +export type RandomInnerReified = Reified; + +export class RandomInner implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::random::RandomInner`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = RandomInner.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = RandomInner.$isPhantom; + + readonly version: ToField<"u64">; + readonly epoch: ToField<"u64">; + readonly randomnessRound: ToField<"u64">; + readonly randomBytes: ToField>; + + private constructor(typeArgs: [], fields: RandomInnerFields) { + this.$fullTypeName = composeSuiType(RandomInner.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.version = fields.version; + this.epoch = fields.epoch; + this.randomnessRound = fields.randomnessRound; + this.randomBytes = fields.randomBytes; + } + + static reified(): RandomInnerReified { + return { + typeName: RandomInner.$typeName, + fullTypeName: composeSuiType(RandomInner.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: RandomInner.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => RandomInner.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => RandomInner.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => RandomInner.fromBcs(data), + bcs: RandomInner.bcs, + fromJSONField: (field: any) => RandomInner.fromJSONField(field), + fromJSON: (json: Record) => RandomInner.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => RandomInner.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => RandomInner.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => RandomInner.fetch(client, id), + new: (fields: RandomInnerFields) => { + return new RandomInner([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return RandomInner.reified(); + } + + static phantom(): PhantomReified> { + return phantom(RandomInner.reified()); + } + static get p() { + return RandomInner.phantom(); + } + + static get bcs() { + return bcs.struct("RandomInner", { + version: bcs.u64(), + epoch: bcs.u64(), + randomness_round: bcs.u64(), + random_bytes: bcs.vector(bcs.u8()), + }); + } + + static fromFields(fields: Record): RandomInner { + return RandomInner.reified().new({ + version: decodeFromFields("u64", fields.version), + epoch: decodeFromFields("u64", fields.epoch), + randomnessRound: decodeFromFields("u64", fields.randomness_round), + randomBytes: decodeFromFields(reified.vector("u8"), fields.random_bytes), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): RandomInner { + if (!isRandomInner(item.type)) { + throw new Error("not a RandomInner type"); + } + + return RandomInner.reified().new({ + version: decodeFromFieldsWithTypes("u64", item.fields.version), + epoch: decodeFromFieldsWithTypes("u64", item.fields.epoch), + randomnessRound: decodeFromFieldsWithTypes("u64", item.fields.randomness_round), + randomBytes: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.random_bytes), + }); + } + + static fromBcs(data: Uint8Array): RandomInner { + return RandomInner.fromFields(RandomInner.bcs.parse(data)); + } + + toJSONField() { + return { + version: this.version.toString(), + epoch: this.epoch.toString(), + randomnessRound: this.randomnessRound.toString(), + randomBytes: fieldToJSON>(`vector`, this.randomBytes), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): RandomInner { + return RandomInner.reified().new({ + version: decodeFromJSONField("u64", field.version), + epoch: decodeFromJSONField("u64", field.epoch), + randomnessRound: decodeFromJSONField("u64", field.randomnessRound), + randomBytes: decodeFromJSONField(reified.vector("u8"), field.randomBytes), + }); + } + + static fromJSON(json: Record): RandomInner { + if (json.$typeName !== RandomInner.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return RandomInner.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): RandomInner { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isRandomInner(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a RandomInner object`); + } + return RandomInner.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): RandomInner { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isRandomInner(data.bcs.type)) { + throw new Error(`object at is not a RandomInner object`); + } + + return RandomInner.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return RandomInner.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching RandomInner object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isRandomInner(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a RandomInner object`); + } + + return RandomInner.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/sui/sui/functions.ts b/src/services/models/sui/sui/sui/functions.ts new file mode 100644 index 00000000..a5337da6 --- /dev/null +++ b/src/services/models/sui/sui/sui/functions.ts @@ -0,0 +1,20 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function new_(tx: Transaction) { + return tx.moveCall({ target: `${PUBLISHED_AT}::sui::new`, arguments: [] }); +} + +export interface TransferArgs { + c: TransactionObjectInput; + recipient: string | TransactionArgument; +} + +export function transfer(tx: Transaction, args: TransferArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::sui::transfer`, + arguments: [obj(tx, args.c), pure(tx, args.recipient, `address`)], + }); +} diff --git a/src/services/models/sui/sui/sui/structs.ts b/src/services/models/sui/sui/sui/structs.ts new file mode 100644 index 00000000..5cad915a --- /dev/null +++ b/src/services/models/sui/sui/sui/structs.ts @@ -0,0 +1,180 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== SUI =============================== */ + +export function isSUI(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::sui::SUI`; +} + +export interface SUIFields { + dummyField: ToField<"bool">; +} + +export type SUIReified = Reified; + +export class SUI implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::sui::SUI`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = SUI.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = SUI.$isPhantom; + + readonly dummyField: ToField<"bool">; + + private constructor(typeArgs: [], fields: SUIFields) { + this.$fullTypeName = composeSuiType(SUI.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.dummyField = fields.dummyField; + } + + static reified(): SUIReified { + return { + typeName: SUI.$typeName, + fullTypeName: composeSuiType(SUI.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: SUI.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => SUI.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => SUI.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => SUI.fromBcs(data), + bcs: SUI.bcs, + fromJSONField: (field: any) => SUI.fromJSONField(field), + fromJSON: (json: Record) => SUI.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => SUI.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => SUI.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => SUI.fetch(client, id), + new: (fields: SUIFields) => { + return new SUI([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return SUI.reified(); + } + + static phantom(): PhantomReified> { + return phantom(SUI.reified()); + } + static get p() { + return SUI.phantom(); + } + + static get bcs() { + return bcs.struct("SUI", { + dummy_field: bcs.bool(), + }); + } + + static fromFields(fields: Record): SUI { + return SUI.reified().new({ + dummyField: decodeFromFields("bool", fields.dummy_field), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): SUI { + if (!isSUI(item.type)) { + throw new Error("not a SUI type"); + } + + return SUI.reified().new({ + dummyField: decodeFromFieldsWithTypes("bool", item.fields.dummy_field), + }); + } + + static fromBcs(data: Uint8Array): SUI { + return SUI.fromFields(SUI.bcs.parse(data)); + } + + toJSONField() { + return { + dummyField: this.dummyField, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): SUI { + return SUI.reified().new({ + dummyField: decodeFromJSONField("bool", field.dummyField), + }); + } + + static fromJSON(json: Record): SUI { + if (json.$typeName !== SUI.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return SUI.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): SUI { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isSUI(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a SUI object`); + } + return SUI.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): SUI { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isSUI(data.bcs.type)) { + throw new Error(`object at is not a SUI object`); + } + + return SUI.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return SUI.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching SUI object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isSUI(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a SUI object`); + } + + return SUI.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/sui/table-vec/functions.ts b/src/services/models/sui/sui/table-vec/functions.ts new file mode 100644 index 00000000..480054bd --- /dev/null +++ b/src/services/models/sui/sui/table-vec/functions.ts @@ -0,0 +1,126 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface BorrowArgs { + t: TransactionObjectInput; + i: bigint | TransactionArgument; +} + +export function borrow(tx: Transaction, typeArg: string, args: BorrowArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table_vec::borrow`, + typeArguments: [typeArg], + arguments: [obj(tx, args.t), pure(tx, args.i, `u64`)], + }); +} + +export interface BorrowMutArgs { + t: TransactionObjectInput; + i: bigint | TransactionArgument; +} + +export function borrowMut(tx: Transaction, typeArg: string, args: BorrowMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table_vec::borrow_mut`, + typeArguments: [typeArg], + arguments: [obj(tx, args.t), pure(tx, args.i, `u64`)], + }); +} + +export function destroyEmpty(tx: Transaction, typeArg: string, t: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table_vec::destroy_empty`, + typeArguments: [typeArg], + arguments: [obj(tx, t)], + }); +} + +export function empty(tx: Transaction, typeArg: string) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table_vec::empty`, + typeArguments: [typeArg], + arguments: [], + }); +} + +export function isEmpty(tx: Transaction, typeArg: string, t: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table_vec::is_empty`, + typeArguments: [typeArg], + arguments: [obj(tx, t)], + }); +} + +export function length(tx: Transaction, typeArg: string, t: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table_vec::length`, + typeArguments: [typeArg], + arguments: [obj(tx, t)], + }); +} + +export function popBack(tx: Transaction, typeArg: string, t: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table_vec::pop_back`, + typeArguments: [typeArg], + arguments: [obj(tx, t)], + }); +} + +export interface PushBackArgs { + t: TransactionObjectInput; + e: GenericArg; +} + +export function pushBack(tx: Transaction, typeArg: string, args: PushBackArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table_vec::push_back`, + typeArguments: [typeArg], + arguments: [obj(tx, args.t), generic(tx, `${typeArg}`, args.e)], + }); +} + +export function singleton(tx: Transaction, typeArg: string, e: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table_vec::singleton`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, e)], + }); +} + +export interface SwapArgs { + t: TransactionObjectInput; + i: bigint | TransactionArgument; + j: bigint | TransactionArgument; +} + +export function swap(tx: Transaction, typeArg: string, args: SwapArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table_vec::swap`, + typeArguments: [typeArg], + arguments: [obj(tx, args.t), pure(tx, args.i, `u64`), pure(tx, args.j, `u64`)], + }); +} + +export interface SwapRemoveArgs { + t: TransactionObjectInput; + i: bigint | TransactionArgument; +} + +export function swapRemove(tx: Transaction, typeArg: string, args: SwapRemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table_vec::swap_remove`, + typeArguments: [typeArg], + arguments: [obj(tx, args.t), pure(tx, args.i, `u64`)], + }); +} + +export function drop(tx: Transaction, typeArg: string, t: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table_vec::drop`, + typeArguments: [typeArg], + arguments: [obj(tx, t)], + }); +} diff --git a/src/services/models/sui/sui/table-vec/structs.ts b/src/services/models/sui/sui/table-vec/structs.ts new file mode 100644 index 00000000..bcef2635 --- /dev/null +++ b/src/services/models/sui/sui/table-vec/structs.ts @@ -0,0 +1,229 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { Table } from "../table/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== TableVec =============================== */ + +export function isTableVec(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::table_vec::TableVec` + "<"); +} + +export interface TableVecFields { + contents: ToField>; +} + +export type TableVecReified = Reified, TableVecFields>; + +export class TableVec implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::table_vec::TableVec`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = TableVec.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = TableVec.$isPhantom; + + readonly contents: ToField>; + + private constructor(typeArgs: [PhantomToTypeStr], fields: TableVecFields) { + this.$fullTypeName = composeSuiType(TableVec.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.contents = fields.contents; + } + + static reified>( + Element: Element + ): TableVecReified> { + return { + typeName: TableVec.$typeName, + fullTypeName: composeSuiType(TableVec.$typeName, ...[extractType(Element)]) as string, + typeArgs: [extractType(Element)] as [PhantomToTypeStr>], + isPhantom: TableVec.$isPhantom, + reifiedTypeArgs: [Element], + fromFields: (fields: Record) => TableVec.fromFields(Element, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => TableVec.fromFieldsWithTypes(Element, item), + fromBcs: (data: Uint8Array) => TableVec.fromBcs(Element, data), + bcs: TableVec.bcs, + fromJSONField: (field: any) => TableVec.fromJSONField(Element, field), + fromJSON: (json: Record) => TableVec.fromJSON(Element, json), + fromSuiParsedData: (content: SuiParsedData) => TableVec.fromSuiParsedData(Element, content), + fromSuiObjectData: (content: SuiObjectData) => TableVec.fromSuiObjectData(Element, content), + fetch: async (client: SuiClient, id: string) => TableVec.fetch(client, Element, id), + new: (fields: TableVecFields>) => { + return new TableVec([extractType(Element)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return TableVec.reified; + } + + static phantom>( + Element: Element + ): PhantomReified>>> { + return phantom(TableVec.reified(Element)); + } + static get p() { + return TableVec.phantom; + } + + static get bcs() { + return bcs.struct("TableVec", { + contents: Table.bcs, + }); + } + + static fromFields>( + typeArg: Element, + fields: Record + ): TableVec> { + return TableVec.reified(typeArg).new({ + contents: decodeFromFields(Table.reified(reified.phantom("u64"), typeArg), fields.contents), + }); + } + + static fromFieldsWithTypes>( + typeArg: Element, + item: FieldsWithTypes + ): TableVec> { + if (!isTableVec(item.type)) { + throw new Error("not a TableVec type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return TableVec.reified(typeArg).new({ + contents: decodeFromFieldsWithTypes(Table.reified(reified.phantom("u64"), typeArg), item.fields.contents), + }); + } + + static fromBcs>( + typeArg: Element, + data: Uint8Array + ): TableVec> { + return TableVec.fromFields(typeArg, TableVec.bcs.parse(data)); + } + + toJSONField() { + return { + contents: this.contents.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: Element, + field: any + ): TableVec> { + return TableVec.reified(typeArg).new({ + contents: decodeFromJSONField(Table.reified(reified.phantom("u64"), typeArg), field.contents), + }); + } + + static fromJSON>( + typeArg: Element, + json: Record + ): TableVec> { + if (json.$typeName !== TableVec.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(TableVec.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return TableVec.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: Element, + content: SuiParsedData + ): TableVec> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTableVec(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a TableVec object`); + } + return TableVec.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: Element, + data: SuiObjectData + ): TableVec> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTableVec(data.bcs.type)) { + throw new Error(`object at is not a TableVec object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return TableVec.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return TableVec.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: Element, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching TableVec object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTableVec(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a TableVec object`); + } + + return TableVec.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/sui/table/functions.ts b/src/services/models/sui/sui/table/functions.ts new file mode 100644 index 00000000..d425ac10 --- /dev/null +++ b/src/services/models/sui/sui/table/functions.ts @@ -0,0 +1,110 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj } from "../../_framework/util"; +import { Transaction, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface AddArgs { + table: TransactionObjectInput; + k: GenericArg; + v: GenericArg; +} + +export function add(tx: Transaction, typeArgs: [string, string], args: AddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table::add`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k), generic(tx, `${typeArgs[1]}`, args.v)], + }); +} + +export interface BorrowArgs { + table: TransactionObjectInput; + k: GenericArg; +} + +export function borrow(tx: Transaction, typeArgs: [string, string], args: BorrowArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table::borrow`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export interface BorrowMutArgs { + table: TransactionObjectInput; + k: GenericArg; +} + +export function borrowMut(tx: Transaction, typeArgs: [string, string], args: BorrowMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table::borrow_mut`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export interface ContainsArgs { + table: TransactionObjectInput; + k: GenericArg; +} + +export function contains(tx: Transaction, typeArgs: [string, string], args: ContainsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table::contains`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export function destroyEmpty(tx: Transaction, typeArgs: [string, string], table: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table::destroy_empty`, + typeArguments: typeArgs, + arguments: [obj(tx, table)], + }); +} + +export function isEmpty(tx: Transaction, typeArgs: [string, string], table: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table::is_empty`, + typeArguments: typeArgs, + arguments: [obj(tx, table)], + }); +} + +export function length(tx: Transaction, typeArgs: [string, string], table: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table::length`, + typeArguments: typeArgs, + arguments: [obj(tx, table)], + }); +} + +export interface RemoveArgs { + table: TransactionObjectInput; + k: GenericArg; +} + +export function remove(tx: Transaction, typeArgs: [string, string], args: RemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table::remove`, + typeArguments: typeArgs, + arguments: [obj(tx, args.table), generic(tx, `${typeArgs[0]}`, args.k)], + }); +} + +export function new_(tx: Transaction, typeArgs: [string, string]) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table::new`, + typeArguments: typeArgs, + arguments: [], + }); +} + +export function drop(tx: Transaction, typeArgs: [string, string], table: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::table::drop`, + typeArguments: typeArgs, + arguments: [obj(tx, table)], + }); +} diff --git a/src/services/models/sui/sui/table/structs.ts b/src/services/models/sui/sui/table/structs.ts new file mode 100644 index 00000000..f76f4135 --- /dev/null +++ b/src/services/models/sui/sui/table/structs.ts @@ -0,0 +1,248 @@ +// @ts-nocheck +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { UID } from "../object/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Table =============================== */ + +export function isTable(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::table::Table` + "<"); +} + +export interface TableFields { + id: ToField; + size: ToField<"u64">; +} + +export type TableReified = Reified< + Table, + TableFields +>; + +export class Table implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::table::Table`; + } + static readonly $numTypeParams = 2; + static readonly $isPhantom = [true, true] as const; + + readonly $typeName = Table.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr, PhantomToTypeStr]; + readonly $isPhantom = Table.$isPhantom; + + readonly id: ToField; + readonly size: ToField<"u64">; + + private constructor(typeArgs: [PhantomToTypeStr, PhantomToTypeStr], fields: TableFields) { + this.$fullTypeName = composeSuiType(Table.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.size = fields.size; + } + + static reified, V extends PhantomReified>( + K: K, + V: V + ): TableReified, ToPhantomTypeArgument> { + return { + typeName: Table.$typeName, + fullTypeName: composeSuiType(Table.$typeName, ...[extractType(K), extractType(V)]) as string, + typeArgs: [extractType(K), extractType(V)] as [ + PhantomToTypeStr>, + PhantomToTypeStr>, + ], + isPhantom: Table.$isPhantom, + reifiedTypeArgs: [K, V], + fromFields: (fields: Record) => Table.fromFields([K, V], fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Table.fromFieldsWithTypes([K, V], item), + fromBcs: (data: Uint8Array) => Table.fromBcs([K, V], data), + bcs: Table.bcs, + fromJSONField: (field: any) => Table.fromJSONField([K, V], field), + fromJSON: (json: Record) => Table.fromJSON([K, V], json), + fromSuiParsedData: (content: SuiParsedData) => Table.fromSuiParsedData([K, V], content), + fromSuiObjectData: (content: SuiObjectData) => Table.fromSuiObjectData([K, V], content), + fetch: async (client: SuiClient, id: string) => Table.fetch(client, [K, V], id), + new: (fields: TableFields, ToPhantomTypeArgument>) => { + return new Table([extractType(K), extractType(V)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Table.reified; + } + + static phantom, V extends PhantomReified>( + K: K, + V: V + ): PhantomReified, ToPhantomTypeArgument>>> { + return phantom(Table.reified(K, V)); + } + static get p() { + return Table.phantom; + } + + static get bcs() { + return bcs.struct("Table", { + id: UID.bcs, + size: bcs.u64(), + }); + } + + static fromFields, V extends PhantomReified>( + typeArgs: [K, V], + fields: Record + ): Table, ToPhantomTypeArgument> { + return Table.reified(typeArgs[0], typeArgs[1]).new({ + id: decodeFromFields(UID.reified(), fields.id), + size: decodeFromFields("u64", fields.size), + }); + } + + static fromFieldsWithTypes< + K extends PhantomReified, + V extends PhantomReified, + >(typeArgs: [K, V], item: FieldsWithTypes): Table, ToPhantomTypeArgument> { + if (!isTable(item.type)) { + throw new Error("not a Table type"); + } + assertFieldsWithTypesArgsMatch(item, typeArgs); + + return Table.reified(typeArgs[0], typeArgs[1]).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + size: decodeFromFieldsWithTypes("u64", item.fields.size), + }); + } + + static fromBcs, V extends PhantomReified>( + typeArgs: [K, V], + data: Uint8Array + ): Table, ToPhantomTypeArgument> { + return Table.fromFields(typeArgs, Table.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + size: this.size.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField, V extends PhantomReified>( + typeArgs: [K, V], + field: any + ): Table, ToPhantomTypeArgument> { + return Table.reified(typeArgs[0], typeArgs[1]).new({ + id: decodeFromJSONField(UID.reified(), field.id), + size: decodeFromJSONField("u64", field.size), + }); + } + + static fromJSON, V extends PhantomReified>( + typeArgs: [K, V], + json: Record + ): Table, ToPhantomTypeArgument> { + if (json.$typeName !== Table.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Table.$typeName, ...typeArgs.map(extractType)), json.$typeArgs, typeArgs); + + return Table.fromJSONField(typeArgs, json); + } + + static fromSuiParsedData< + K extends PhantomReified, + V extends PhantomReified, + >(typeArgs: [K, V], content: SuiParsedData): Table, ToPhantomTypeArgument> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTable(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Table object`); + } + return Table.fromFieldsWithTypes(typeArgs, content); + } + + static fromSuiObjectData< + K extends PhantomReified, + V extends PhantomReified, + >(typeArgs: [K, V], data: SuiObjectData): Table, ToPhantomTypeArgument> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTable(data.bcs.type)) { + throw new Error(`object at is not a Table object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 2) { + throw new Error(`type argument mismatch: expected 2 type arguments but got ${gotTypeArgs.length}`); + } + for (let i = 0; i < 2; i++) { + const gotTypeArg = compressSuiType(gotTypeArgs[i]); + const expectedTypeArg = compressSuiType(extractType(typeArgs[i])); + if (gotTypeArg !== expectedTypeArg) { + throw new Error( + `type argument mismatch at position ${i}: expected '${expectedTypeArg}' but got '${gotTypeArg}'` + ); + } + } + + return Table.fromBcs(typeArgs, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Table.fromSuiParsedData(typeArgs, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch, V extends PhantomReified>( + client: SuiClient, + typeArgs: [K, V], + id: string + ): Promise, ToPhantomTypeArgument>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Table object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTable(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Table object`); + } + + return Table.fromSuiObjectData(typeArgs, res.data); + } +} diff --git a/src/services/models/sui/sui/token/functions.ts b/src/services/models/sui/sui/token/functions.ts new file mode 100644 index 00000000..8b04dad9 --- /dev/null +++ b/src/services/models/sui/sui/token/functions.ts @@ -0,0 +1,496 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { Option } from "../../_dependencies/source/0x1/option/structs"; +import { String } from "../../_dependencies/source/0x1/string/structs"; +import { GenericArg, generic, obj, option, pure } from "../../_framework/util"; +import { Balance } from "../balance/structs"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function value(tx: Transaction, typeArg: string, t: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::value`, + typeArguments: [typeArg], + arguments: [obj(tx, t)], + }); +} + +export interface AllowArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; + action: string | TransactionArgument; +} + +export function allow(tx: Transaction, typeArg: string, args: AllowArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::allow`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.cap), pure(tx, args.action, `${String.$typeName}`)], + }); +} + +export function sender(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::sender`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function amount(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::amount`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function recipient(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::recipient`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export interface TransferArgs { + t: TransactionObjectInput; + recipient: string | TransactionArgument; +} + +export function transfer(tx: Transaction, typeArg: string, args: TransferArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::transfer`, + typeArguments: [typeArg], + arguments: [obj(tx, args.t), pure(tx, args.recipient, `address`)], + }); +} + +export function key(tx: Transaction, typeArg: string) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::key`, + typeArguments: [typeArg], + arguments: [], + }); +} + +export function destroyZero(tx: Transaction, typeArg: string, token: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::destroy_zero`, + typeArguments: [typeArg], + arguments: [obj(tx, token)], + }); +} + +export interface JoinArgs { + token: TransactionObjectInput; + another: TransactionObjectInput; +} + +export function join(tx: Transaction, typeArg: string, args: JoinArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::join`, + typeArguments: [typeArg], + arguments: [obj(tx, args.token), obj(tx, args.another)], + }); +} + +export interface SplitArgs { + token: TransactionObjectInput; + amount: bigint | TransactionArgument; +} + +export function split(tx: Transaction, typeArg: string, args: SplitArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::split`, + typeArguments: [typeArg], + arguments: [obj(tx, args.token), pure(tx, args.amount, `u64`)], + }); +} + +export function zero(tx: Transaction, typeArg: string) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::zero`, + typeArguments: [typeArg], + arguments: [], + }); +} + +export interface BurnArgs { + cap: TransactionObjectInput; + token: TransactionObjectInput; +} + +export function burn(tx: Transaction, typeArg: string, args: BurnArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::burn`, + typeArguments: [typeArg], + arguments: [obj(tx, args.cap), obj(tx, args.token)], + }); +} + +export interface MintArgs { + cap: TransactionObjectInput; + amount: bigint | TransactionArgument; +} + +export function mint(tx: Transaction, typeArg: string, args: MintArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::mint`, + typeArguments: [typeArg], + arguments: [obj(tx, args.cap), pure(tx, args.amount, `u64`)], + }); +} + +export interface ConfirmRequestArgs { + policy: TransactionObjectInput; + request: TransactionObjectInput; +} + +export function confirmRequest(tx: Transaction, typeArg: string, args: ConfirmRequestArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::confirm_request`, + typeArguments: [typeArg], + arguments: [obj(tx, args.policy), obj(tx, args.request)], + }); +} + +export interface NewRequestArgs { + name: string | TransactionArgument; + amount: bigint | TransactionArgument; + recipient: string | TransactionArgument | TransactionArgument | null; + spentBalance: TransactionObjectInput | TransactionArgument | null; +} + +export function newRequest(tx: Transaction, typeArg: string, args: NewRequestArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::new_request`, + typeArguments: [typeArg], + arguments: [ + pure(tx, args.name, `${String.$typeName}`), + pure(tx, args.amount, `u64`), + pure(tx, args.recipient, `${Option.$typeName}
`), + option(tx, `${Balance.$typeName}<${typeArg}>`, args.spentBalance), + ], + }); +} + +export interface RulesArgs { + self: TransactionObjectInput; + action: string | TransactionArgument; +} + +export function rules(tx: Transaction, typeArg: string, args: RulesArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::rules`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), pure(tx, args.action, `${String.$typeName}`)], + }); +} + +export function keep(tx: Transaction, typeArg: string, token: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::keep`, + typeArguments: [typeArg], + arguments: [obj(tx, token)], + }); +} + +export function action(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::action`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export interface AddApprovalArgs { + t: GenericArg; + request: TransactionObjectInput; +} + +export function addApproval(tx: Transaction, typeArgs: [string, string], args: AddApprovalArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::add_approval`, + typeArguments: typeArgs, + arguments: [generic(tx, `${typeArgs[1]}`, args.t), obj(tx, args.request)], + }); +} + +export interface AddRuleConfigArgs { + rule: GenericArg; + self: TransactionObjectInput; + cap: TransactionObjectInput; + config: GenericArg; +} + +export function addRuleConfig(tx: Transaction, typeArgs: [string, string, string], args: AddRuleConfigArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::add_rule_config`, + typeArguments: typeArgs, + arguments: [ + generic(tx, `${typeArgs[1]}`, args.rule), + obj(tx, args.self), + obj(tx, args.cap), + generic(tx, `${typeArgs[2]}`, args.config), + ], + }); +} + +export interface AddRuleForActionArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; + action: string | TransactionArgument; +} + +export function addRuleForAction(tx: Transaction, typeArgs: [string, string], args: AddRuleForActionArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::add_rule_for_action`, + typeArguments: typeArgs, + arguments: [obj(tx, args.self), obj(tx, args.cap), pure(tx, args.action, `${String.$typeName}`)], + }); +} + +export function approvals(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::approvals`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export interface ConfirmRequestMutArgs { + policy: TransactionObjectInput; + request: TransactionObjectInput; +} + +export function confirmRequestMut(tx: Transaction, typeArg: string, args: ConfirmRequestMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::confirm_request_mut`, + typeArguments: [typeArg], + arguments: [obj(tx, args.policy), obj(tx, args.request)], + }); +} + +export interface ConfirmWithPolicyCapArgs { + policyCap: TransactionObjectInput; + request: TransactionObjectInput; +} + +export function confirmWithPolicyCap(tx: Transaction, typeArg: string, args: ConfirmWithPolicyCapArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::confirm_with_policy_cap`, + typeArguments: [typeArg], + arguments: [obj(tx, args.policyCap), obj(tx, args.request)], + }); +} + +export interface ConfirmWithTreasuryCapArgs { + treasuryCap: TransactionObjectInput; + request: TransactionObjectInput; +} + +export function confirmWithTreasuryCap(tx: Transaction, typeArg: string, args: ConfirmWithTreasuryCapArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::confirm_with_treasury_cap`, + typeArguments: [typeArg], + arguments: [obj(tx, args.treasuryCap), obj(tx, args.request)], + }); +} + +export interface DisallowArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; + action: string | TransactionArgument; +} + +export function disallow(tx: Transaction, typeArg: string, args: DisallowArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::disallow`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.cap), pure(tx, args.action, `${String.$typeName}`)], + }); +} + +export interface FlushArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; +} + +export function flush(tx: Transaction, typeArg: string, args: FlushArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::flush`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.cap)], + }); +} + +export function fromCoin(tx: Transaction, typeArg: string, coin: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::from_coin`, + typeArguments: [typeArg], + arguments: [obj(tx, coin)], + }); +} + +export function fromCoinAction(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::from_coin_action`, + arguments: [], + }); +} + +export function hasRuleConfig(tx: Transaction, typeArgs: [string, string], self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::has_rule_config`, + typeArguments: typeArgs, + arguments: [obj(tx, self)], + }); +} + +export function hasRuleConfigWithType( + tx: Transaction, + typeArgs: [string, string, string], + self: TransactionObjectInput +) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::has_rule_config_with_type`, + typeArguments: typeArgs, + arguments: [obj(tx, self)], + }); +} + +export interface IsAllowedArgs { + self: TransactionObjectInput; + action: string | TransactionArgument; +} + +export function isAllowed(tx: Transaction, typeArg: string, args: IsAllowedArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::is_allowed`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), pure(tx, args.action, `${String.$typeName}`)], + }); +} + +export function newPolicy(tx: Transaction, typeArg: string, treasuryCap: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::new_policy`, + typeArguments: [typeArg], + arguments: [obj(tx, treasuryCap)], + }); +} + +export function spentBalance(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::spent_balance`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export interface RemoveRuleConfigArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; +} + +export function removeRuleConfig(tx: Transaction, typeArgs: [string, string, string], args: RemoveRuleConfigArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::remove_rule_config`, + typeArguments: typeArgs, + arguments: [obj(tx, args.self), obj(tx, args.cap)], + }); +} + +export interface RemoveRuleForActionArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; + action: string | TransactionArgument; +} + +export function removeRuleForAction(tx: Transaction, typeArgs: [string, string], args: RemoveRuleForActionArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::remove_rule_for_action`, + typeArguments: typeArgs, + arguments: [obj(tx, args.self), obj(tx, args.cap), pure(tx, args.action, `${String.$typeName}`)], + }); +} + +export interface RuleConfigArgs { + rule: GenericArg; + self: TransactionObjectInput; +} + +export function ruleConfig(tx: Transaction, typeArgs: [string, string, string], args: RuleConfigArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::rule_config`, + typeArguments: typeArgs, + arguments: [generic(tx, `${typeArgs[1]}`, args.rule), obj(tx, args.self)], + }); +} + +export interface RuleConfigMutArgs { + rule: GenericArg; + self: TransactionObjectInput; + cap: TransactionObjectInput; +} + +export function ruleConfigMut(tx: Transaction, typeArgs: [string, string, string], args: RuleConfigMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::rule_config_mut`, + typeArguments: typeArgs, + arguments: [generic(tx, `${typeArgs[1]}`, args.rule), obj(tx, args.self), obj(tx, args.cap)], + }); +} + +export function sharePolicy(tx: Transaction, typeArg: string, policy: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::share_policy`, + typeArguments: [typeArg], + arguments: [obj(tx, policy)], + }); +} + +export function spend(tx: Transaction, typeArg: string, t: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::spend`, + typeArguments: [typeArg], + arguments: [obj(tx, t)], + }); +} + +export function spendAction(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::spend_action`, + arguments: [], + }); +} + +export function spent(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::spent`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function toCoin(tx: Transaction, typeArg: string, t: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::to_coin`, + typeArguments: [typeArg], + arguments: [obj(tx, t)], + }); +} + +export function toCoinAction(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::to_coin_action`, + arguments: [], + }); +} + +export function transferAction(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::token::transfer_action`, + arguments: [], + }); +} diff --git a/src/services/models/sui/sui/token/structs.ts b/src/services/models/sui/sui/token/structs.ts new file mode 100644 index 00000000..1ff019f2 --- /dev/null +++ b/src/services/models/sui/sui/token/structs.ts @@ -0,0 +1,1348 @@ +// @ts-nocheck +import { Option } from "../../_dependencies/source/0x1/option/structs"; +import { String } from "../../_dependencies/source/0x1/string/structs"; +import { TypeName } from "../../_dependencies/source/0x1/type-name/structs"; +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + fieldToJSON, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { Balance } from "../balance/structs"; +import { PKG_V26 } from "../index"; +import { ID, UID } from "../object/structs"; +import { VecMap } from "../vec-map/structs"; +import { VecSet } from "../vec-set/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64, fromHEX, toHEX } from "@mysten/sui/utils"; + +/* ============================== RuleKey =============================== */ + +export function isRuleKey(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::token::RuleKey` + "<"); +} + +export interface RuleKeyFields { + isProtected: ToField<"bool">; +} + +export type RuleKeyReified = Reified, RuleKeyFields>; + +export class RuleKey implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::token::RuleKey`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = RuleKey.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = RuleKey.$isPhantom; + + readonly isProtected: ToField<"bool">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: RuleKeyFields) { + this.$fullTypeName = composeSuiType(RuleKey.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.isProtected = fields.isProtected; + } + + static reified>(T: T): RuleKeyReified> { + return { + typeName: RuleKey.$typeName, + fullTypeName: composeSuiType(RuleKey.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: RuleKey.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => RuleKey.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => RuleKey.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => RuleKey.fromBcs(T, data), + bcs: RuleKey.bcs, + fromJSONField: (field: any) => RuleKey.fromJSONField(T, field), + fromJSON: (json: Record) => RuleKey.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => RuleKey.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => RuleKey.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => RuleKey.fetch(client, T, id), + new: (fields: RuleKeyFields>) => { + return new RuleKey([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return RuleKey.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(RuleKey.reified(T)); + } + static get p() { + return RuleKey.phantom; + } + + static get bcs() { + return bcs.struct("RuleKey", { + is_protected: bcs.bool(), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): RuleKey> { + return RuleKey.reified(typeArg).new({ + isProtected: decodeFromFields("bool", fields.is_protected), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): RuleKey> { + if (!isRuleKey(item.type)) { + throw new Error("not a RuleKey type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return RuleKey.reified(typeArg).new({ + isProtected: decodeFromFieldsWithTypes("bool", item.fields.is_protected), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): RuleKey> { + return RuleKey.fromFields(typeArg, RuleKey.bcs.parse(data)); + } + + toJSONField() { + return { + isProtected: this.isProtected, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): RuleKey> { + return RuleKey.reified(typeArg).new({ + isProtected: decodeFromJSONField("bool", field.isProtected), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): RuleKey> { + if (json.$typeName !== RuleKey.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(RuleKey.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return RuleKey.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): RuleKey> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isRuleKey(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a RuleKey object`); + } + return RuleKey.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): RuleKey> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isRuleKey(data.bcs.type)) { + throw new Error(`object at is not a RuleKey object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return RuleKey.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return RuleKey.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching RuleKey object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isRuleKey(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a RuleKey object`); + } + + return RuleKey.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== ActionRequest =============================== */ + +export function isActionRequest(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::token::ActionRequest` + "<"); +} + +export interface ActionRequestFields { + name: ToField; + amount: ToField<"u64">; + sender: ToField<"address">; + recipient: ToField>; + spentBalance: ToField>>; + approvals: ToField>; +} + +export type ActionRequestReified = Reified, ActionRequestFields>; + +export class ActionRequest implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::token::ActionRequest`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = ActionRequest.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = ActionRequest.$isPhantom; + + readonly name: ToField; + readonly amount: ToField<"u64">; + readonly sender: ToField<"address">; + readonly recipient: ToField>; + readonly spentBalance: ToField>>; + readonly approvals: ToField>; + + private constructor(typeArgs: [PhantomToTypeStr], fields: ActionRequestFields) { + this.$fullTypeName = composeSuiType(ActionRequest.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.name = fields.name; + this.amount = fields.amount; + this.sender = fields.sender; + this.recipient = fields.recipient; + this.spentBalance = fields.spentBalance; + this.approvals = fields.approvals; + } + + static reified>(T: T): ActionRequestReified> { + return { + typeName: ActionRequest.$typeName, + fullTypeName: composeSuiType(ActionRequest.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: ActionRequest.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => ActionRequest.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => ActionRequest.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => ActionRequest.fromBcs(T, data), + bcs: ActionRequest.bcs, + fromJSONField: (field: any) => ActionRequest.fromJSONField(T, field), + fromJSON: (json: Record) => ActionRequest.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => ActionRequest.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => ActionRequest.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => ActionRequest.fetch(client, T, id), + new: (fields: ActionRequestFields>) => { + return new ActionRequest([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return ActionRequest.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(ActionRequest.reified(T)); + } + static get p() { + return ActionRequest.phantom; + } + + static get bcs() { + return bcs.struct("ActionRequest", { + name: String.bcs, + amount: bcs.u64(), + sender: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + recipient: Option.bcs( + bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }) + ), + spent_balance: Option.bcs(Balance.bcs), + approvals: VecSet.bcs(TypeName.bcs), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): ActionRequest> { + return ActionRequest.reified(typeArg).new({ + name: decodeFromFields(String.reified(), fields.name), + amount: decodeFromFields("u64", fields.amount), + sender: decodeFromFields("address", fields.sender), + recipient: decodeFromFields(Option.reified("address"), fields.recipient), + spentBalance: decodeFromFields(Option.reified(Balance.reified(typeArg)), fields.spent_balance), + approvals: decodeFromFields(VecSet.reified(TypeName.reified()), fields.approvals), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): ActionRequest> { + if (!isActionRequest(item.type)) { + throw new Error("not a ActionRequest type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return ActionRequest.reified(typeArg).new({ + name: decodeFromFieldsWithTypes(String.reified(), item.fields.name), + amount: decodeFromFieldsWithTypes("u64", item.fields.amount), + sender: decodeFromFieldsWithTypes("address", item.fields.sender), + recipient: decodeFromFieldsWithTypes(Option.reified("address"), item.fields.recipient), + spentBalance: decodeFromFieldsWithTypes(Option.reified(Balance.reified(typeArg)), item.fields.spent_balance), + approvals: decodeFromFieldsWithTypes(VecSet.reified(TypeName.reified()), item.fields.approvals), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): ActionRequest> { + return ActionRequest.fromFields(typeArg, ActionRequest.bcs.parse(data)); + } + + toJSONField() { + return { + name: this.name, + amount: this.amount.toString(), + sender: this.sender, + recipient: fieldToJSON>(`${Option.$typeName}
`, this.recipient), + spentBalance: fieldToJSON>>( + `${Option.$typeName}<${Balance.$typeName}<${this.$typeArgs[0]}>>`, + this.spentBalance + ), + approvals: this.approvals.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): ActionRequest> { + return ActionRequest.reified(typeArg).new({ + name: decodeFromJSONField(String.reified(), field.name), + amount: decodeFromJSONField("u64", field.amount), + sender: decodeFromJSONField("address", field.sender), + recipient: decodeFromJSONField(Option.reified("address"), field.recipient), + spentBalance: decodeFromJSONField(Option.reified(Balance.reified(typeArg)), field.spentBalance), + approvals: decodeFromJSONField(VecSet.reified(TypeName.reified()), field.approvals), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): ActionRequest> { + if (json.$typeName !== ActionRequest.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(ActionRequest.$typeName, extractType(typeArg)), json.$typeArgs, [ + typeArg, + ]); + + return ActionRequest.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): ActionRequest> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isActionRequest(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a ActionRequest object`); + } + return ActionRequest.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): ActionRequest> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isActionRequest(data.bcs.type)) { + throw new Error(`object at is not a ActionRequest object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return ActionRequest.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return ActionRequest.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching ActionRequest object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isActionRequest(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a ActionRequest object`); + } + + return ActionRequest.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== Token =============================== */ + +export function isToken(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::token::Token` + "<"); +} + +export interface TokenFields { + id: ToField; + balance: ToField>; +} + +export type TokenReified = Reified, TokenFields>; + +export class Token implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::token::Token`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = Token.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = Token.$isPhantom; + + readonly id: ToField; + readonly balance: ToField>; + + private constructor(typeArgs: [PhantomToTypeStr], fields: TokenFields) { + this.$fullTypeName = composeSuiType(Token.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.balance = fields.balance; + } + + static reified>(T: T): TokenReified> { + return { + typeName: Token.$typeName, + fullTypeName: composeSuiType(Token.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: Token.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => Token.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Token.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => Token.fromBcs(T, data), + bcs: Token.bcs, + fromJSONField: (field: any) => Token.fromJSONField(T, field), + fromJSON: (json: Record) => Token.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => Token.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => Token.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => Token.fetch(client, T, id), + new: (fields: TokenFields>) => { + return new Token([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Token.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(Token.reified(T)); + } + static get p() { + return Token.phantom; + } + + static get bcs() { + return bcs.struct("Token", { + id: UID.bcs, + balance: Balance.bcs, + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): Token> { + return Token.reified(typeArg).new({ + id: decodeFromFields(UID.reified(), fields.id), + balance: decodeFromFields(Balance.reified(typeArg), fields.balance), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): Token> { + if (!isToken(item.type)) { + throw new Error("not a Token type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Token.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + balance: decodeFromFieldsWithTypes(Balance.reified(typeArg), item.fields.balance), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): Token> { + return Token.fromFields(typeArg, Token.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + balance: this.balance.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): Token> { + return Token.reified(typeArg).new({ + id: decodeFromJSONField(UID.reified(), field.id), + balance: decodeFromJSONField(Balance.reified(typeArg), field.balance), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): Token> { + if (json.$typeName !== Token.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Token.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Token.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): Token> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isToken(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Token object`); + } + return Token.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): Token> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isToken(data.bcs.type)) { + throw new Error(`object at is not a Token object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Token.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Token.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Token object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isToken(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Token object`); + } + + return Token.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== TokenPolicy =============================== */ + +export function isTokenPolicy(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::token::TokenPolicy` + "<"); +} + +export interface TokenPolicyFields { + id: ToField; + spentBalance: ToField>; + rules: ToField>>; +} + +export type TokenPolicyReified = Reified, TokenPolicyFields>; + +export class TokenPolicy implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::token::TokenPolicy`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = TokenPolicy.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = TokenPolicy.$isPhantom; + + readonly id: ToField; + readonly spentBalance: ToField>; + readonly rules: ToField>>; + + private constructor(typeArgs: [PhantomToTypeStr], fields: TokenPolicyFields) { + this.$fullTypeName = composeSuiType(TokenPolicy.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.spentBalance = fields.spentBalance; + this.rules = fields.rules; + } + + static reified>(T: T): TokenPolicyReified> { + return { + typeName: TokenPolicy.$typeName, + fullTypeName: composeSuiType(TokenPolicy.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: TokenPolicy.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => TokenPolicy.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => TokenPolicy.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => TokenPolicy.fromBcs(T, data), + bcs: TokenPolicy.bcs, + fromJSONField: (field: any) => TokenPolicy.fromJSONField(T, field), + fromJSON: (json: Record) => TokenPolicy.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => TokenPolicy.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => TokenPolicy.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => TokenPolicy.fetch(client, T, id), + new: (fields: TokenPolicyFields>) => { + return new TokenPolicy([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return TokenPolicy.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(TokenPolicy.reified(T)); + } + static get p() { + return TokenPolicy.phantom; + } + + static get bcs() { + return bcs.struct("TokenPolicy", { + id: UID.bcs, + spent_balance: Balance.bcs, + rules: VecMap.bcs(String.bcs, VecSet.bcs(TypeName.bcs)), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): TokenPolicy> { + return TokenPolicy.reified(typeArg).new({ + id: decodeFromFields(UID.reified(), fields.id), + spentBalance: decodeFromFields(Balance.reified(typeArg), fields.spent_balance), + rules: decodeFromFields(VecMap.reified(String.reified(), VecSet.reified(TypeName.reified())), fields.rules), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): TokenPolicy> { + if (!isTokenPolicy(item.type)) { + throw new Error("not a TokenPolicy type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return TokenPolicy.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + spentBalance: decodeFromFieldsWithTypes(Balance.reified(typeArg), item.fields.spent_balance), + rules: decodeFromFieldsWithTypes( + VecMap.reified(String.reified(), VecSet.reified(TypeName.reified())), + item.fields.rules + ), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): TokenPolicy> { + return TokenPolicy.fromFields(typeArg, TokenPolicy.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + spentBalance: this.spentBalance.toJSONField(), + rules: this.rules.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): TokenPolicy> { + return TokenPolicy.reified(typeArg).new({ + id: decodeFromJSONField(UID.reified(), field.id), + spentBalance: decodeFromJSONField(Balance.reified(typeArg), field.spentBalance), + rules: decodeFromJSONField(VecMap.reified(String.reified(), VecSet.reified(TypeName.reified())), field.rules), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): TokenPolicy> { + if (json.$typeName !== TokenPolicy.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(TokenPolicy.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return TokenPolicy.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): TokenPolicy> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTokenPolicy(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a TokenPolicy object`); + } + return TokenPolicy.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): TokenPolicy> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTokenPolicy(data.bcs.type)) { + throw new Error(`object at is not a TokenPolicy object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return TokenPolicy.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return TokenPolicy.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching TokenPolicy object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTokenPolicy(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a TokenPolicy object`); + } + + return TokenPolicy.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== TokenPolicyCap =============================== */ + +export function isTokenPolicyCap(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::token::TokenPolicyCap` + "<"); +} + +export interface TokenPolicyCapFields { + id: ToField; + for: ToField; +} + +export type TokenPolicyCapReified = Reified, TokenPolicyCapFields>; + +export class TokenPolicyCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::token::TokenPolicyCap`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = TokenPolicyCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = TokenPolicyCap.$isPhantom; + + readonly id: ToField; + readonly for: ToField; + + private constructor(typeArgs: [PhantomToTypeStr], fields: TokenPolicyCapFields) { + this.$fullTypeName = composeSuiType(TokenPolicyCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.for = fields.for; + } + + static reified>(T: T): TokenPolicyCapReified> { + return { + typeName: TokenPolicyCap.$typeName, + fullTypeName: composeSuiType(TokenPolicyCap.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: TokenPolicyCap.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => TokenPolicyCap.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => TokenPolicyCap.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => TokenPolicyCap.fromBcs(T, data), + bcs: TokenPolicyCap.bcs, + fromJSONField: (field: any) => TokenPolicyCap.fromJSONField(T, field), + fromJSON: (json: Record) => TokenPolicyCap.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => TokenPolicyCap.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => TokenPolicyCap.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => TokenPolicyCap.fetch(client, T, id), + new: (fields: TokenPolicyCapFields>) => { + return new TokenPolicyCap([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return TokenPolicyCap.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(TokenPolicyCap.reified(T)); + } + static get p() { + return TokenPolicyCap.phantom; + } + + static get bcs() { + return bcs.struct("TokenPolicyCap", { + id: UID.bcs, + for: ID.bcs, + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): TokenPolicyCap> { + return TokenPolicyCap.reified(typeArg).new({ + id: decodeFromFields(UID.reified(), fields.id), + for: decodeFromFields(ID.reified(), fields.for), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): TokenPolicyCap> { + if (!isTokenPolicyCap(item.type)) { + throw new Error("not a TokenPolicyCap type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return TokenPolicyCap.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + for: decodeFromFieldsWithTypes(ID.reified(), item.fields.for), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): TokenPolicyCap> { + return TokenPolicyCap.fromFields(typeArg, TokenPolicyCap.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + for: this.for, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): TokenPolicyCap> { + return TokenPolicyCap.reified(typeArg).new({ + id: decodeFromJSONField(UID.reified(), field.id), + for: decodeFromJSONField(ID.reified(), field.for), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): TokenPolicyCap> { + if (json.$typeName !== TokenPolicyCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(TokenPolicyCap.$typeName, extractType(typeArg)), json.$typeArgs, [ + typeArg, + ]); + + return TokenPolicyCap.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): TokenPolicyCap> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTokenPolicyCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a TokenPolicyCap object`); + } + return TokenPolicyCap.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): TokenPolicyCap> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTokenPolicyCap(data.bcs.type)) { + throw new Error(`object at is not a TokenPolicyCap object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return TokenPolicyCap.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return TokenPolicyCap.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching TokenPolicyCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTokenPolicyCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a TokenPolicyCap object`); + } + + return TokenPolicyCap.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== TokenPolicyCreated =============================== */ + +export function isTokenPolicyCreated(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::token::TokenPolicyCreated` + "<"); +} + +export interface TokenPolicyCreatedFields { + id: ToField; + isMutable: ToField<"bool">; +} + +export type TokenPolicyCreatedReified = Reified< + TokenPolicyCreated, + TokenPolicyCreatedFields +>; + +export class TokenPolicyCreated implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::token::TokenPolicyCreated`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = TokenPolicyCreated.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = TokenPolicyCreated.$isPhantom; + + readonly id: ToField; + readonly isMutable: ToField<"bool">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: TokenPolicyCreatedFields) { + this.$fullTypeName = composeSuiType(TokenPolicyCreated.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.isMutable = fields.isMutable; + } + + static reified>( + T: T + ): TokenPolicyCreatedReified> { + return { + typeName: TokenPolicyCreated.$typeName, + fullTypeName: composeSuiType(TokenPolicyCreated.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: TokenPolicyCreated.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => TokenPolicyCreated.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => TokenPolicyCreated.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => TokenPolicyCreated.fromBcs(T, data), + bcs: TokenPolicyCreated.bcs, + fromJSONField: (field: any) => TokenPolicyCreated.fromJSONField(T, field), + fromJSON: (json: Record) => TokenPolicyCreated.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => TokenPolicyCreated.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => TokenPolicyCreated.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => TokenPolicyCreated.fetch(client, T, id), + new: (fields: TokenPolicyCreatedFields>) => { + return new TokenPolicyCreated([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return TokenPolicyCreated.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(TokenPolicyCreated.reified(T)); + } + static get p() { + return TokenPolicyCreated.phantom; + } + + static get bcs() { + return bcs.struct("TokenPolicyCreated", { + id: ID.bcs, + is_mutable: bcs.bool(), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): TokenPolicyCreated> { + return TokenPolicyCreated.reified(typeArg).new({ + id: decodeFromFields(ID.reified(), fields.id), + isMutable: decodeFromFields("bool", fields.is_mutable), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): TokenPolicyCreated> { + if (!isTokenPolicyCreated(item.type)) { + throw new Error("not a TokenPolicyCreated type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return TokenPolicyCreated.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(ID.reified(), item.fields.id), + isMutable: decodeFromFieldsWithTypes("bool", item.fields.is_mutable), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): TokenPolicyCreated> { + return TokenPolicyCreated.fromFields(typeArg, TokenPolicyCreated.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + isMutable: this.isMutable, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): TokenPolicyCreated> { + return TokenPolicyCreated.reified(typeArg).new({ + id: decodeFromJSONField(ID.reified(), field.id), + isMutable: decodeFromJSONField("bool", field.isMutable), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): TokenPolicyCreated> { + if (json.$typeName !== TokenPolicyCreated.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(TokenPolicyCreated.$typeName, extractType(typeArg)), json.$typeArgs, [ + typeArg, + ]); + + return TokenPolicyCreated.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): TokenPolicyCreated> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTokenPolicyCreated(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a TokenPolicyCreated object`); + } + return TokenPolicyCreated.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): TokenPolicyCreated> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTokenPolicyCreated(data.bcs.type)) { + throw new Error(`object at is not a TokenPolicyCreated object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return TokenPolicyCreated.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return TokenPolicyCreated.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching TokenPolicyCreated object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTokenPolicyCreated(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a TokenPolicyCreated object`); + } + + return TokenPolicyCreated.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/sui/transfer-policy/functions.ts b/src/services/models/sui/sui/transfer-policy/functions.ts new file mode 100644 index 00000000..9240ddbd --- /dev/null +++ b/src/services/models/sui/sui/transfer-policy/functions.ts @@ -0,0 +1,214 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { Option } from "../../_dependencies/source/0x1/option/structs"; +import { GenericArg, generic, obj, pure } from "../../_framework/util"; +import { ID } from "../object/structs"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function default_(tx: Transaction, typeArg: string, pub: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer_policy::default`, + typeArguments: [typeArg], + arguments: [obj(tx, pub)], + }); +} + +export function new_(tx: Transaction, typeArg: string, pub: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer_policy::new`, + typeArguments: [typeArg], + arguments: [obj(tx, pub)], + }); +} + +export function uid(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer_policy::uid`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export interface WithdrawArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; + amount: bigint | TransactionArgument | TransactionArgument | null; +} + +export function withdraw(tx: Transaction, typeArg: string, args: WithdrawArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer_policy::withdraw`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.cap), pure(tx, args.amount, `${Option.$typeName}`)], + }); +} + +export interface AddReceiptArgs { + rule: GenericArg; + request: TransactionObjectInput; +} + +export function addReceipt(tx: Transaction, typeArgs: [string, string], args: AddReceiptArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer_policy::add_receipt`, + typeArguments: typeArgs, + arguments: [generic(tx, `${typeArgs[1]}`, args.rule), obj(tx, args.request)], + }); +} + +export interface AddRuleArgs { + rule: GenericArg; + policy: TransactionObjectInput; + cap: TransactionObjectInput; + cfg: GenericArg; +} + +export function addRule(tx: Transaction, typeArgs: [string, string, string], args: AddRuleArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer_policy::add_rule`, + typeArguments: typeArgs, + arguments: [ + generic(tx, `${typeArgs[1]}`, args.rule), + obj(tx, args.policy), + obj(tx, args.cap), + generic(tx, `${typeArgs[2]}`, args.cfg), + ], + }); +} + +export interface AddToBalanceArgs { + rule: GenericArg; + policy: TransactionObjectInput; + coin: TransactionObjectInput; +} + +export function addToBalance(tx: Transaction, typeArgs: [string, string], args: AddToBalanceArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer_policy::add_to_balance`, + typeArguments: typeArgs, + arguments: [generic(tx, `${typeArgs[1]}`, args.rule), obj(tx, args.policy), obj(tx, args.coin)], + }); +} + +export interface ConfirmRequestArgs { + self: TransactionObjectInput; + request: TransactionObjectInput; +} + +export function confirmRequest(tx: Transaction, typeArg: string, args: ConfirmRequestArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer_policy::confirm_request`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.request)], + }); +} + +export interface DestroyAndWithdrawArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; +} + +export function destroyAndWithdraw(tx: Transaction, typeArg: string, args: DestroyAndWithdrawArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer_policy::destroy_and_withdraw`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.cap)], + }); +} + +export function from(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer_policy::from`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export interface GetRuleArgs { + rule: GenericArg; + policy: TransactionObjectInput; +} + +export function getRule(tx: Transaction, typeArgs: [string, string, string], args: GetRuleArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer_policy::get_rule`, + typeArguments: typeArgs, + arguments: [generic(tx, `${typeArgs[1]}`, args.rule), obj(tx, args.policy)], + }); +} + +export function hasRule(tx: Transaction, typeArgs: [string, string], policy: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer_policy::has_rule`, + typeArguments: typeArgs, + arguments: [obj(tx, policy)], + }); +} + +export function item(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer_policy::item`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export interface NewRequestArgs { + item: string | TransactionArgument; + paid: bigint | TransactionArgument; + from: string | TransactionArgument; +} + +export function newRequest(tx: Transaction, typeArg: string, args: NewRequestArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer_policy::new_request`, + typeArguments: [typeArg], + arguments: [ + pure(tx, args.item, `${ID.$typeName}`), + pure(tx, args.paid, `u64`), + pure(tx, args.from, `${ID.$typeName}`), + ], + }); +} + +export function paid(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer_policy::paid`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export interface RemoveRuleArgs { + policy: TransactionObjectInput; + cap: TransactionObjectInput; +} + +export function removeRule(tx: Transaction, typeArgs: [string, string, string], args: RemoveRuleArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer_policy::remove_rule`, + typeArguments: typeArgs, + arguments: [obj(tx, args.policy), obj(tx, args.cap)], + }); +} + +export function rules(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer_policy::rules`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export interface UidMutAsOwnerArgs { + self: TransactionObjectInput; + cap: TransactionObjectInput; +} + +export function uidMutAsOwner(tx: Transaction, typeArg: string, args: UidMutAsOwnerArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer_policy::uid_mut_as_owner`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), obj(tx, args.cap)], + }); +} diff --git a/src/services/models/sui/sui/transfer-policy/structs.ts b/src/services/models/sui/sui/transfer-policy/structs.ts new file mode 100644 index 00000000..40235709 --- /dev/null +++ b/src/services/models/sui/sui/transfer-policy/structs.ts @@ -0,0 +1,1322 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { TypeName } from "../../_dependencies/source/0x1/type-name/structs"; +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, + ToTypeStr as ToPhantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { Balance } from "../balance/structs"; +import { PKG_V26 } from "../index"; +import { ID, UID } from "../object/structs"; +import { SUI } from "../sui/structs"; +import { VecSet } from "../vec-set/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== RuleKey =============================== */ + +export function isRuleKey(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::transfer_policy::RuleKey` + "<"); +} + +export interface RuleKeyFields { + dummyField: ToField<"bool">; +} + +export type RuleKeyReified = Reified, RuleKeyFields>; + +export class RuleKey implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::transfer_policy::RuleKey`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = RuleKey.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = RuleKey.$isPhantom; + + readonly dummyField: ToField<"bool">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: RuleKeyFields) { + this.$fullTypeName = composeSuiType(RuleKey.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.dummyField = fields.dummyField; + } + + static reified>(T: T): RuleKeyReified> { + return { + typeName: RuleKey.$typeName, + fullTypeName: composeSuiType(RuleKey.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: RuleKey.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => RuleKey.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => RuleKey.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => RuleKey.fromBcs(T, data), + bcs: RuleKey.bcs, + fromJSONField: (field: any) => RuleKey.fromJSONField(T, field), + fromJSON: (json: Record) => RuleKey.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => RuleKey.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => RuleKey.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => RuleKey.fetch(client, T, id), + new: (fields: RuleKeyFields>) => { + return new RuleKey([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return RuleKey.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(RuleKey.reified(T)); + } + static get p() { + return RuleKey.phantom; + } + + static get bcs() { + return bcs.struct("RuleKey", { + dummy_field: bcs.bool(), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): RuleKey> { + return RuleKey.reified(typeArg).new({ + dummyField: decodeFromFields("bool", fields.dummy_field), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): RuleKey> { + if (!isRuleKey(item.type)) { + throw new Error("not a RuleKey type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return RuleKey.reified(typeArg).new({ + dummyField: decodeFromFieldsWithTypes("bool", item.fields.dummy_field), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): RuleKey> { + return RuleKey.fromFields(typeArg, RuleKey.bcs.parse(data)); + } + + toJSONField() { + return { + dummyField: this.dummyField, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): RuleKey> { + return RuleKey.reified(typeArg).new({ + dummyField: decodeFromJSONField("bool", field.dummyField), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): RuleKey> { + if (json.$typeName !== RuleKey.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(RuleKey.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return RuleKey.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): RuleKey> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isRuleKey(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a RuleKey object`); + } + return RuleKey.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): RuleKey> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isRuleKey(data.bcs.type)) { + throw new Error(`object at is not a RuleKey object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return RuleKey.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return RuleKey.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching RuleKey object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isRuleKey(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a RuleKey object`); + } + + return RuleKey.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== TransferPolicy =============================== */ + +export function isTransferPolicy(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::transfer_policy::TransferPolicy` + "<"); +} + +export interface TransferPolicyFields { + id: ToField; + balance: ToField>>; + rules: ToField>; +} + +export type TransferPolicyReified = Reified, TransferPolicyFields>; + +export class TransferPolicy implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::transfer_policy::TransferPolicy`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = TransferPolicy.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = TransferPolicy.$isPhantom; + + readonly id: ToField; + readonly balance: ToField>>; + readonly rules: ToField>; + + private constructor(typeArgs: [PhantomToTypeStr], fields: TransferPolicyFields) { + this.$fullTypeName = composeSuiType(TransferPolicy.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.balance = fields.balance; + this.rules = fields.rules; + } + + static reified>(T: T): TransferPolicyReified> { + return { + typeName: TransferPolicy.$typeName, + fullTypeName: composeSuiType(TransferPolicy.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: TransferPolicy.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => TransferPolicy.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => TransferPolicy.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => TransferPolicy.fromBcs(T, data), + bcs: TransferPolicy.bcs, + fromJSONField: (field: any) => TransferPolicy.fromJSONField(T, field), + fromJSON: (json: Record) => TransferPolicy.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => TransferPolicy.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => TransferPolicy.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => TransferPolicy.fetch(client, T, id), + new: (fields: TransferPolicyFields>) => { + return new TransferPolicy([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return TransferPolicy.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(TransferPolicy.reified(T)); + } + static get p() { + return TransferPolicy.phantom; + } + + static get bcs() { + return bcs.struct("TransferPolicy", { + id: UID.bcs, + balance: Balance.bcs, + rules: VecSet.bcs(TypeName.bcs), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): TransferPolicy> { + return TransferPolicy.reified(typeArg).new({ + id: decodeFromFields(UID.reified(), fields.id), + balance: decodeFromFields(Balance.reified(reified.phantom(SUI.reified())), fields.balance), + rules: decodeFromFields(VecSet.reified(TypeName.reified()), fields.rules), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): TransferPolicy> { + if (!isTransferPolicy(item.type)) { + throw new Error("not a TransferPolicy type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return TransferPolicy.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + balance: decodeFromFieldsWithTypes(Balance.reified(reified.phantom(SUI.reified())), item.fields.balance), + rules: decodeFromFieldsWithTypes(VecSet.reified(TypeName.reified()), item.fields.rules), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): TransferPolicy> { + return TransferPolicy.fromFields(typeArg, TransferPolicy.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + balance: this.balance.toJSONField(), + rules: this.rules.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): TransferPolicy> { + return TransferPolicy.reified(typeArg).new({ + id: decodeFromJSONField(UID.reified(), field.id), + balance: decodeFromJSONField(Balance.reified(reified.phantom(SUI.reified())), field.balance), + rules: decodeFromJSONField(VecSet.reified(TypeName.reified()), field.rules), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): TransferPolicy> { + if (json.$typeName !== TransferPolicy.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(TransferPolicy.$typeName, extractType(typeArg)), json.$typeArgs, [ + typeArg, + ]); + + return TransferPolicy.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): TransferPolicy> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTransferPolicy(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a TransferPolicy object`); + } + return TransferPolicy.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): TransferPolicy> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTransferPolicy(data.bcs.type)) { + throw new Error(`object at is not a TransferPolicy object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return TransferPolicy.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return TransferPolicy.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching TransferPolicy object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTransferPolicy(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a TransferPolicy object`); + } + + return TransferPolicy.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== TransferPolicyCap =============================== */ + +export function isTransferPolicyCap(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::transfer_policy::TransferPolicyCap` + "<"); +} + +export interface TransferPolicyCapFields { + id: ToField; + policyId: ToField; +} + +export type TransferPolicyCapReified = Reified< + TransferPolicyCap, + TransferPolicyCapFields +>; + +export class TransferPolicyCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::transfer_policy::TransferPolicyCap`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = TransferPolicyCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = TransferPolicyCap.$isPhantom; + + readonly id: ToField; + readonly policyId: ToField; + + private constructor(typeArgs: [PhantomToTypeStr], fields: TransferPolicyCapFields) { + this.$fullTypeName = composeSuiType(TransferPolicyCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.policyId = fields.policyId; + } + + static reified>( + T: T + ): TransferPolicyCapReified> { + return { + typeName: TransferPolicyCap.$typeName, + fullTypeName: composeSuiType(TransferPolicyCap.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: TransferPolicyCap.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => TransferPolicyCap.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => TransferPolicyCap.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => TransferPolicyCap.fromBcs(T, data), + bcs: TransferPolicyCap.bcs, + fromJSONField: (field: any) => TransferPolicyCap.fromJSONField(T, field), + fromJSON: (json: Record) => TransferPolicyCap.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => TransferPolicyCap.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => TransferPolicyCap.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => TransferPolicyCap.fetch(client, T, id), + new: (fields: TransferPolicyCapFields>) => { + return new TransferPolicyCap([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return TransferPolicyCap.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(TransferPolicyCap.reified(T)); + } + static get p() { + return TransferPolicyCap.phantom; + } + + static get bcs() { + return bcs.struct("TransferPolicyCap", { + id: UID.bcs, + policy_id: ID.bcs, + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): TransferPolicyCap> { + return TransferPolicyCap.reified(typeArg).new({ + id: decodeFromFields(UID.reified(), fields.id), + policyId: decodeFromFields(ID.reified(), fields.policy_id), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): TransferPolicyCap> { + if (!isTransferPolicyCap(item.type)) { + throw new Error("not a TransferPolicyCap type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return TransferPolicyCap.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + policyId: decodeFromFieldsWithTypes(ID.reified(), item.fields.policy_id), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): TransferPolicyCap> { + return TransferPolicyCap.fromFields(typeArg, TransferPolicyCap.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + policyId: this.policyId, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): TransferPolicyCap> { + return TransferPolicyCap.reified(typeArg).new({ + id: decodeFromJSONField(UID.reified(), field.id), + policyId: decodeFromJSONField(ID.reified(), field.policyId), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): TransferPolicyCap> { + if (json.$typeName !== TransferPolicyCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(TransferPolicyCap.$typeName, extractType(typeArg)), json.$typeArgs, [ + typeArg, + ]); + + return TransferPolicyCap.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): TransferPolicyCap> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTransferPolicyCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a TransferPolicyCap object`); + } + return TransferPolicyCap.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): TransferPolicyCap> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTransferPolicyCap(data.bcs.type)) { + throw new Error(`object at is not a TransferPolicyCap object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return TransferPolicyCap.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return TransferPolicyCap.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching TransferPolicyCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTransferPolicyCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a TransferPolicyCap object`); + } + + return TransferPolicyCap.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== TransferPolicyCreated =============================== */ + +export function isTransferPolicyCreated(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::transfer_policy::TransferPolicyCreated` + "<"); +} + +export interface TransferPolicyCreatedFields { + id: ToField; +} + +export type TransferPolicyCreatedReified = Reified< + TransferPolicyCreated, + TransferPolicyCreatedFields +>; + +export class TransferPolicyCreated implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::transfer_policy::TransferPolicyCreated`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = TransferPolicyCreated.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = TransferPolicyCreated.$isPhantom; + + readonly id: ToField; + + private constructor(typeArgs: [PhantomToTypeStr], fields: TransferPolicyCreatedFields) { + this.$fullTypeName = composeSuiType(TransferPolicyCreated.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified>( + T: T + ): TransferPolicyCreatedReified> { + return { + typeName: TransferPolicyCreated.$typeName, + fullTypeName: composeSuiType(TransferPolicyCreated.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: TransferPolicyCreated.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => TransferPolicyCreated.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => TransferPolicyCreated.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => TransferPolicyCreated.fromBcs(T, data), + bcs: TransferPolicyCreated.bcs, + fromJSONField: (field: any) => TransferPolicyCreated.fromJSONField(T, field), + fromJSON: (json: Record) => TransferPolicyCreated.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => TransferPolicyCreated.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => TransferPolicyCreated.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => TransferPolicyCreated.fetch(client, T, id), + new: (fields: TransferPolicyCreatedFields>) => { + return new TransferPolicyCreated([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return TransferPolicyCreated.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(TransferPolicyCreated.reified(T)); + } + static get p() { + return TransferPolicyCreated.phantom; + } + + static get bcs() { + return bcs.struct("TransferPolicyCreated", { + id: ID.bcs, + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): TransferPolicyCreated> { + return TransferPolicyCreated.reified(typeArg).new({ + id: decodeFromFields(ID.reified(), fields.id), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): TransferPolicyCreated> { + if (!isTransferPolicyCreated(item.type)) { + throw new Error("not a TransferPolicyCreated type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return TransferPolicyCreated.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(ID.reified(), item.fields.id), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): TransferPolicyCreated> { + return TransferPolicyCreated.fromFields(typeArg, TransferPolicyCreated.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): TransferPolicyCreated> { + return TransferPolicyCreated.reified(typeArg).new({ + id: decodeFromJSONField(ID.reified(), field.id), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): TransferPolicyCreated> { + if (json.$typeName !== TransferPolicyCreated.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(TransferPolicyCreated.$typeName, extractType(typeArg)), json.$typeArgs, [ + typeArg, + ]); + + return TransferPolicyCreated.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): TransferPolicyCreated> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTransferPolicyCreated(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a TransferPolicyCreated object`); + } + return TransferPolicyCreated.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): TransferPolicyCreated> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTransferPolicyCreated(data.bcs.type)) { + throw new Error(`object at is not a TransferPolicyCreated object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return TransferPolicyCreated.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return TransferPolicyCreated.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching TransferPolicyCreated object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTransferPolicyCreated(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a TransferPolicyCreated object`); + } + + return TransferPolicyCreated.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== TransferPolicyDestroyed =============================== */ + +export function isTransferPolicyDestroyed(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::transfer_policy::TransferPolicyDestroyed` + "<"); +} + +export interface TransferPolicyDestroyedFields { + id: ToField; +} + +export type TransferPolicyDestroyedReified = Reified< + TransferPolicyDestroyed, + TransferPolicyDestroyedFields +>; + +export class TransferPolicyDestroyed implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::transfer_policy::TransferPolicyDestroyed`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = TransferPolicyDestroyed.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = TransferPolicyDestroyed.$isPhantom; + + readonly id: ToField; + + private constructor(typeArgs: [PhantomToTypeStr], fields: TransferPolicyDestroyedFields) { + this.$fullTypeName = composeSuiType(TransferPolicyDestroyed.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified>( + T: T + ): TransferPolicyDestroyedReified> { + return { + typeName: TransferPolicyDestroyed.$typeName, + fullTypeName: composeSuiType(TransferPolicyDestroyed.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: TransferPolicyDestroyed.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => TransferPolicyDestroyed.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => TransferPolicyDestroyed.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => TransferPolicyDestroyed.fromBcs(T, data), + bcs: TransferPolicyDestroyed.bcs, + fromJSONField: (field: any) => TransferPolicyDestroyed.fromJSONField(T, field), + fromJSON: (json: Record) => TransferPolicyDestroyed.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => TransferPolicyDestroyed.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => TransferPolicyDestroyed.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => TransferPolicyDestroyed.fetch(client, T, id), + new: (fields: TransferPolicyDestroyedFields>) => { + return new TransferPolicyDestroyed([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return TransferPolicyDestroyed.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(TransferPolicyDestroyed.reified(T)); + } + static get p() { + return TransferPolicyDestroyed.phantom; + } + + static get bcs() { + return bcs.struct("TransferPolicyDestroyed", { + id: ID.bcs, + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): TransferPolicyDestroyed> { + return TransferPolicyDestroyed.reified(typeArg).new({ + id: decodeFromFields(ID.reified(), fields.id), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): TransferPolicyDestroyed> { + if (!isTransferPolicyDestroyed(item.type)) { + throw new Error("not a TransferPolicyDestroyed type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return TransferPolicyDestroyed.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(ID.reified(), item.fields.id), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): TransferPolicyDestroyed> { + return TransferPolicyDestroyed.fromFields(typeArg, TransferPolicyDestroyed.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): TransferPolicyDestroyed> { + return TransferPolicyDestroyed.reified(typeArg).new({ + id: decodeFromJSONField(ID.reified(), field.id), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): TransferPolicyDestroyed> { + if (json.$typeName !== TransferPolicyDestroyed.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch( + composeSuiType(TransferPolicyDestroyed.$typeName, extractType(typeArg)), + json.$typeArgs, + [typeArg] + ); + + return TransferPolicyDestroyed.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): TransferPolicyDestroyed> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTransferPolicyDestroyed(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a TransferPolicyDestroyed object`); + } + return TransferPolicyDestroyed.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): TransferPolicyDestroyed> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTransferPolicyDestroyed(data.bcs.type)) { + throw new Error(`object at is not a TransferPolicyDestroyed object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return TransferPolicyDestroyed.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return TransferPolicyDestroyed.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching TransferPolicyDestroyed object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTransferPolicyDestroyed(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a TransferPolicyDestroyed object`); + } + + return TransferPolicyDestroyed.fromSuiObjectData(typeArg, res.data); + } +} + +/* ============================== TransferRequest =============================== */ + +export function isTransferRequest(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::transfer_policy::TransferRequest` + "<"); +} + +export interface TransferRequestFields { + item: ToField; + paid: ToField<"u64">; + from: ToField; + receipts: ToField>; +} + +export type TransferRequestReified = Reified< + TransferRequest, + TransferRequestFields +>; + +export class TransferRequest implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::transfer_policy::TransferRequest`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = TransferRequest.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = TransferRequest.$isPhantom; + + readonly item: ToField; + readonly paid: ToField<"u64">; + readonly from: ToField; + readonly receipts: ToField>; + + private constructor(typeArgs: [PhantomToTypeStr], fields: TransferRequestFields) { + this.$fullTypeName = composeSuiType(TransferRequest.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.item = fields.item; + this.paid = fields.paid; + this.from = fields.from; + this.receipts = fields.receipts; + } + + static reified>( + T: T + ): TransferRequestReified> { + return { + typeName: TransferRequest.$typeName, + fullTypeName: composeSuiType(TransferRequest.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: TransferRequest.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => TransferRequest.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => TransferRequest.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => TransferRequest.fromBcs(T, data), + bcs: TransferRequest.bcs, + fromJSONField: (field: any) => TransferRequest.fromJSONField(T, field), + fromJSON: (json: Record) => TransferRequest.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => TransferRequest.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => TransferRequest.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => TransferRequest.fetch(client, T, id), + new: (fields: TransferRequestFields>) => { + return new TransferRequest([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return TransferRequest.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(TransferRequest.reified(T)); + } + static get p() { + return TransferRequest.phantom; + } + + static get bcs() { + return bcs.struct("TransferRequest", { + item: ID.bcs, + paid: bcs.u64(), + from: ID.bcs, + receipts: VecSet.bcs(TypeName.bcs), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): TransferRequest> { + return TransferRequest.reified(typeArg).new({ + item: decodeFromFields(ID.reified(), fields.item), + paid: decodeFromFields("u64", fields.paid), + from: decodeFromFields(ID.reified(), fields.from), + receipts: decodeFromFields(VecSet.reified(TypeName.reified()), fields.receipts), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): TransferRequest> { + if (!isTransferRequest(item.type)) { + throw new Error("not a TransferRequest type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return TransferRequest.reified(typeArg).new({ + item: decodeFromFieldsWithTypes(ID.reified(), item.fields.item), + paid: decodeFromFieldsWithTypes("u64", item.fields.paid), + from: decodeFromFieldsWithTypes(ID.reified(), item.fields.from), + receipts: decodeFromFieldsWithTypes(VecSet.reified(TypeName.reified()), item.fields.receipts), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): TransferRequest> { + return TransferRequest.fromFields(typeArg, TransferRequest.bcs.parse(data)); + } + + toJSONField() { + return { + item: this.item, + paid: this.paid.toString(), + from: this.from, + receipts: this.receipts.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): TransferRequest> { + return TransferRequest.reified(typeArg).new({ + item: decodeFromJSONField(ID.reified(), field.item), + paid: decodeFromJSONField("u64", field.paid), + from: decodeFromJSONField(ID.reified(), field.from), + receipts: decodeFromJSONField(VecSet.reified(TypeName.reified()), field.receipts), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): TransferRequest> { + if (json.$typeName !== TransferRequest.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(TransferRequest.$typeName, extractType(typeArg)), json.$typeArgs, [ + typeArg, + ]); + + return TransferRequest.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): TransferRequest> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTransferRequest(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a TransferRequest object`); + } + return TransferRequest.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): TransferRequest> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTransferRequest(data.bcs.type)) { + throw new Error(`object at is not a TransferRequest object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return TransferRequest.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return TransferRequest.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching TransferRequest object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTransferRequest(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a TransferRequest object`); + } + + return TransferRequest.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/sui/transfer/functions.ts b/src/services/models/sui/sui/transfer/functions.ts new file mode 100644 index 00000000..7f0eec9e --- /dev/null +++ b/src/services/models/sui/sui/transfer/functions.ts @@ -0,0 +1,144 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj, pure } from "../../_framework/util"; +import { ID } from "../object/structs"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface TransferArgs { + obj: GenericArg; + recipient: string | TransactionArgument; +} + +export function transfer(tx: Transaction, typeArg: string, args: TransferArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer::transfer`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, args.obj), pure(tx, args.recipient, `address`)], + }); +} + +export function freezeObject(tx: Transaction, typeArg: string, obj: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer::freeze_object`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, obj)], + }); +} + +export function freezeObjectImpl(tx: Transaction, typeArg: string, obj: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer::freeze_object_impl`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, obj)], + }); +} + +export function publicFreezeObject(tx: Transaction, typeArg: string, obj: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer::public_freeze_object`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, obj)], + }); +} + +export interface PublicReceiveArgs { + parent: TransactionObjectInput; + toReceive: TransactionObjectInput; +} + +export function publicReceive(tx: Transaction, typeArg: string, args: PublicReceiveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer::public_receive`, + typeArguments: [typeArg], + arguments: [obj(tx, args.parent), obj(tx, args.toReceive)], + }); +} + +export function publicShareObject(tx: Transaction, typeArg: string, obj: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer::public_share_object`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, obj)], + }); +} + +export interface PublicTransferArgs { + obj: GenericArg; + recipient: string | TransactionArgument; +} + +export function publicTransfer(tx: Transaction, typeArg: string, args: PublicTransferArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer::public_transfer`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, args.obj), pure(tx, args.recipient, `address`)], + }); +} + +export interface ReceiveArgs { + parent: TransactionObjectInput; + toReceive: TransactionObjectInput; +} + +export function receive(tx: Transaction, typeArg: string, args: ReceiveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer::receive`, + typeArguments: [typeArg], + arguments: [obj(tx, args.parent), obj(tx, args.toReceive)], + }); +} + +export interface ReceiveImplArgs { + parent: string | TransactionArgument; + toReceive: string | TransactionArgument; + version: bigint | TransactionArgument; +} + +export function receiveImpl(tx: Transaction, typeArg: string, args: ReceiveImplArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer::receive_impl`, + typeArguments: [typeArg], + arguments: [ + pure(tx, args.parent, `address`), + pure(tx, args.toReceive, `${ID.$typeName}`), + pure(tx, args.version, `u64`), + ], + }); +} + +export function receivingObjectId(tx: Transaction, typeArg: string, receiving: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer::receiving_object_id`, + typeArguments: [typeArg], + arguments: [obj(tx, receiving)], + }); +} + +export function shareObject(tx: Transaction, typeArg: string, obj: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer::share_object`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, obj)], + }); +} + +export function shareObjectImpl(tx: Transaction, typeArg: string, obj: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer::share_object_impl`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, obj)], + }); +} + +export interface TransferImplArgs { + obj: GenericArg; + recipient: string | TransactionArgument; +} + +export function transferImpl(tx: Transaction, typeArg: string, args: TransferImplArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::transfer::transfer_impl`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, args.obj), pure(tx, args.recipient, `address`)], + }); +} diff --git a/src/services/models/sui/sui/transfer/structs.ts b/src/services/models/sui/sui/transfer/structs.ts new file mode 100644 index 00000000..3313fc50 --- /dev/null +++ b/src/services/models/sui/sui/transfer/structs.ts @@ -0,0 +1,234 @@ +// @ts-nocheck +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { ID } from "../object/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Receiving =============================== */ + +export function isReceiving(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::transfer::Receiving` + "<"); +} + +export interface ReceivingFields { + id: ToField; + version: ToField<"u64">; +} + +export type ReceivingReified = Reified, ReceivingFields>; + +export class Receiving implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::transfer::Receiving`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = Receiving.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = Receiving.$isPhantom; + + readonly id: ToField; + readonly version: ToField<"u64">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: ReceivingFields) { + this.$fullTypeName = composeSuiType(Receiving.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.version = fields.version; + } + + static reified>(T: T): ReceivingReified> { + return { + typeName: Receiving.$typeName, + fullTypeName: composeSuiType(Receiving.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: Receiving.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => Receiving.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Receiving.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => Receiving.fromBcs(T, data), + bcs: Receiving.bcs, + fromJSONField: (field: any) => Receiving.fromJSONField(T, field), + fromJSON: (json: Record) => Receiving.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => Receiving.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => Receiving.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => Receiving.fetch(client, T, id), + new: (fields: ReceivingFields>) => { + return new Receiving([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Receiving.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(Receiving.reified(T)); + } + static get p() { + return Receiving.phantom; + } + + static get bcs() { + return bcs.struct("Receiving", { + id: ID.bcs, + version: bcs.u64(), + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): Receiving> { + return Receiving.reified(typeArg).new({ + id: decodeFromFields(ID.reified(), fields.id), + version: decodeFromFields("u64", fields.version), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): Receiving> { + if (!isReceiving(item.type)) { + throw new Error("not a Receiving type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Receiving.reified(typeArg).new({ + id: decodeFromFieldsWithTypes(ID.reified(), item.fields.id), + version: decodeFromFieldsWithTypes("u64", item.fields.version), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): Receiving> { + return Receiving.fromFields(typeArg, Receiving.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + version: this.version.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): Receiving> { + return Receiving.reified(typeArg).new({ + id: decodeFromJSONField(ID.reified(), field.id), + version: decodeFromJSONField("u64", field.version), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): Receiving> { + if (json.$typeName !== Receiving.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Receiving.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Receiving.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): Receiving> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isReceiving(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Receiving object`); + } + return Receiving.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): Receiving> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isReceiving(data.bcs.type)) { + throw new Error(`object at is not a Receiving object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Receiving.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Receiving.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Receiving object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isReceiving(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Receiving object`); + } + + return Receiving.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/sui/tx-context/functions.ts b/src/services/models/sui/sui/tx-context/functions.ts new file mode 100644 index 00000000..e0800c04 --- /dev/null +++ b/src/services/models/sui/sui/tx-context/functions.ts @@ -0,0 +1,58 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { pure } from "../../_framework/util"; +import { Transaction, TransactionArgument } from "@mysten/sui/transactions"; + +export interface DeriveIdArgs { + txHash: Array | TransactionArgument; + idsCreated: bigint | TransactionArgument; +} + +export function deriveId(tx: Transaction, args: DeriveIdArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::tx_context::derive_id`, + arguments: [pure(tx, args.txHash, `vector`), pure(tx, args.idsCreated, `u64`)], + }); +} + +export function idsCreated(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::tx_context::ids_created`, + arguments: [], + }); +} + +export function digest(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::tx_context::digest`, + arguments: [], + }); +} + +export function epoch(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::tx_context::epoch`, + arguments: [], + }); +} + +export function epochTimestampMs(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::tx_context::epoch_timestamp_ms`, + arguments: [], + }); +} + +export function freshObjectAddress(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::tx_context::fresh_object_address`, + arguments: [], + }); +} + +export function sender(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::tx_context::sender`, + arguments: [], + }); +} diff --git a/src/services/models/sui/sui/tx-context/structs.ts b/src/services/models/sui/sui/tx-context/structs.ts new file mode 100644 index 00000000..b99e0c4d --- /dev/null +++ b/src/services/models/sui/sui/tx-context/structs.ts @@ -0,0 +1,218 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { Vector } from "../../_framework/vector"; +import { PKG_V26 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64, fromHEX, toHEX } from "@mysten/sui/utils"; + +/* ============================== TxContext =============================== */ + +export function isTxContext(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::tx_context::TxContext`; +} + +export interface TxContextFields { + sender: ToField<"address">; + txHash: ToField>; + epoch: ToField<"u64">; + epochTimestampMs: ToField<"u64">; + idsCreated: ToField<"u64">; +} + +export type TxContextReified = Reified; + +export class TxContext implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::tx_context::TxContext`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = TxContext.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = TxContext.$isPhantom; + + readonly sender: ToField<"address">; + readonly txHash: ToField>; + readonly epoch: ToField<"u64">; + readonly epochTimestampMs: ToField<"u64">; + readonly idsCreated: ToField<"u64">; + + private constructor(typeArgs: [], fields: TxContextFields) { + this.$fullTypeName = composeSuiType(TxContext.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.sender = fields.sender; + this.txHash = fields.txHash; + this.epoch = fields.epoch; + this.epochTimestampMs = fields.epochTimestampMs; + this.idsCreated = fields.idsCreated; + } + + static reified(): TxContextReified { + return { + typeName: TxContext.$typeName, + fullTypeName: composeSuiType(TxContext.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: TxContext.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => TxContext.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => TxContext.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => TxContext.fromBcs(data), + bcs: TxContext.bcs, + fromJSONField: (field: any) => TxContext.fromJSONField(field), + fromJSON: (json: Record) => TxContext.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => TxContext.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => TxContext.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => TxContext.fetch(client, id), + new: (fields: TxContextFields) => { + return new TxContext([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return TxContext.reified(); + } + + static phantom(): PhantomReified> { + return phantom(TxContext.reified()); + } + static get p() { + return TxContext.phantom(); + } + + static get bcs() { + return bcs.struct("TxContext", { + sender: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + tx_hash: bcs.vector(bcs.u8()), + epoch: bcs.u64(), + epoch_timestamp_ms: bcs.u64(), + ids_created: bcs.u64(), + }); + } + + static fromFields(fields: Record): TxContext { + return TxContext.reified().new({ + sender: decodeFromFields("address", fields.sender), + txHash: decodeFromFields(reified.vector("u8"), fields.tx_hash), + epoch: decodeFromFields("u64", fields.epoch), + epochTimestampMs: decodeFromFields("u64", fields.epoch_timestamp_ms), + idsCreated: decodeFromFields("u64", fields.ids_created), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): TxContext { + if (!isTxContext(item.type)) { + throw new Error("not a TxContext type"); + } + + return TxContext.reified().new({ + sender: decodeFromFieldsWithTypes("address", item.fields.sender), + txHash: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.tx_hash), + epoch: decodeFromFieldsWithTypes("u64", item.fields.epoch), + epochTimestampMs: decodeFromFieldsWithTypes("u64", item.fields.epoch_timestamp_ms), + idsCreated: decodeFromFieldsWithTypes("u64", item.fields.ids_created), + }); + } + + static fromBcs(data: Uint8Array): TxContext { + return TxContext.fromFields(TxContext.bcs.parse(data)); + } + + toJSONField() { + return { + sender: this.sender, + txHash: fieldToJSON>(`vector`, this.txHash), + epoch: this.epoch.toString(), + epochTimestampMs: this.epochTimestampMs.toString(), + idsCreated: this.idsCreated.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): TxContext { + return TxContext.reified().new({ + sender: decodeFromJSONField("address", field.sender), + txHash: decodeFromJSONField(reified.vector("u8"), field.txHash), + epoch: decodeFromJSONField("u64", field.epoch), + epochTimestampMs: decodeFromJSONField("u64", field.epochTimestampMs), + idsCreated: decodeFromJSONField("u64", field.idsCreated), + }); + } + + static fromJSON(json: Record): TxContext { + if (json.$typeName !== TxContext.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return TxContext.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): TxContext { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isTxContext(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a TxContext object`); + } + return TxContext.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): TxContext { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isTxContext(data.bcs.type)) { + throw new Error(`object at is not a TxContext object`); + } + + return TxContext.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return TxContext.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching TxContext object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isTxContext(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a TxContext object`); + } + + return TxContext.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/sui/types/functions.ts b/src/services/models/sui/sui/types/functions.ts new file mode 100644 index 00000000..16bad66f --- /dev/null +++ b/src/services/models/sui/sui/types/functions.ts @@ -0,0 +1,12 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic } from "../../_framework/util"; +import { Transaction } from "@mysten/sui/transactions"; + +export function isOneTimeWitness(tx: Transaction, typeArg: string, t: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::types::is_one_time_witness`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, t)], + }); +} diff --git a/src/services/models/sui/sui/url/functions.ts b/src/services/models/sui/sui/url/functions.ts new file mode 100644 index 00000000..47118979 --- /dev/null +++ b/src/services/models/sui/sui/url/functions.ts @@ -0,0 +1,38 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { String } from "../../_dependencies/source/0x1/ascii/structs"; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function innerUrl(tx: Transaction, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::url::inner_url`, + arguments: [obj(tx, self)], + }); +} + +export function newUnsafe(tx: Transaction, url: string | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::url::new_unsafe`, + arguments: [pure(tx, url, `${String.$typeName}`)], + }); +} + +export function newUnsafeFromBytes(tx: Transaction, bytes: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::url::new_unsafe_from_bytes`, + arguments: [pure(tx, bytes, `vector`)], + }); +} + +export interface UpdateArgs { + self: TransactionObjectInput; + url: string | TransactionArgument; +} + +export function update(tx: Transaction, args: UpdateArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::url::update`, + arguments: [obj(tx, args.self), pure(tx, args.url, `${String.$typeName}`)], + }); +} diff --git a/src/services/models/sui/sui/url/structs.ts b/src/services/models/sui/sui/url/structs.ts new file mode 100644 index 00000000..1d9d2453 --- /dev/null +++ b/src/services/models/sui/sui/url/structs.ts @@ -0,0 +1,181 @@ +// @ts-nocheck +import { String } from "../../_dependencies/source/0x1/ascii/structs"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Url =============================== */ + +export function isUrl(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::url::Url`; +} + +export interface UrlFields { + url: ToField; +} + +export type UrlReified = Reified; + +export class Url implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::url::Url`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Url.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Url.$isPhantom; + + readonly url: ToField; + + private constructor(typeArgs: [], fields: UrlFields) { + this.$fullTypeName = composeSuiType(Url.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.url = fields.url; + } + + static reified(): UrlReified { + return { + typeName: Url.$typeName, + fullTypeName: composeSuiType(Url.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Url.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Url.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Url.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Url.fromBcs(data), + bcs: Url.bcs, + fromJSONField: (field: any) => Url.fromJSONField(field), + fromJSON: (json: Record) => Url.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Url.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Url.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Url.fetch(client, id), + new: (fields: UrlFields) => { + return new Url([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Url.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Url.reified()); + } + static get p() { + return Url.phantom(); + } + + static get bcs() { + return bcs.struct("Url", { + url: String.bcs, + }); + } + + static fromFields(fields: Record): Url { + return Url.reified().new({ + url: decodeFromFields(String.reified(), fields.url), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Url { + if (!isUrl(item.type)) { + throw new Error("not a Url type"); + } + + return Url.reified().new({ + url: decodeFromFieldsWithTypes(String.reified(), item.fields.url), + }); + } + + static fromBcs(data: Uint8Array): Url { + return Url.fromFields(Url.bcs.parse(data)); + } + + toJSONField() { + return { + url: this.url, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Url { + return Url.reified().new({ + url: decodeFromJSONField(String.reified(), field.url), + }); + } + + static fromJSON(json: Record): Url { + if (json.$typeName !== Url.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Url.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Url { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isUrl(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Url object`); + } + return Url.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Url { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isUrl(data.bcs.type)) { + throw new Error(`object at is not a Url object`); + } + + return Url.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Url.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Url object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isUrl(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Url object`); + } + + return Url.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/sui/vdf/functions.ts b/src/services/models/sui/sui/vdf/functions.ts new file mode 100644 index 00000000..fba8367d --- /dev/null +++ b/src/services/models/sui/sui/vdf/functions.ts @@ -0,0 +1,59 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { pure } from "../../_framework/util"; +import { Transaction, TransactionArgument } from "@mysten/sui/transactions"; + +export function hashToInput(tx: Transaction, message: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vdf::hash_to_input`, + arguments: [pure(tx, message, `vector`)], + }); +} + +export function hashToInputInternal( + tx: Transaction, + message: Array | TransactionArgument +) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vdf::hash_to_input_internal`, + arguments: [pure(tx, message, `vector`)], + }); +} + +export interface VdfVerifyArgs { + input: Array | TransactionArgument; + output: Array | TransactionArgument; + proof: Array | TransactionArgument; + iterations: bigint | TransactionArgument; +} + +export function vdfVerify(tx: Transaction, args: VdfVerifyArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vdf::vdf_verify`, + arguments: [ + pure(tx, args.input, `vector`), + pure(tx, args.output, `vector`), + pure(tx, args.proof, `vector`), + pure(tx, args.iterations, `u64`), + ], + }); +} + +export interface VdfVerifyInternalArgs { + input: Array | TransactionArgument; + output: Array | TransactionArgument; + proof: Array | TransactionArgument; + iterations: bigint | TransactionArgument; +} + +export function vdfVerifyInternal(tx: Transaction, args: VdfVerifyInternalArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vdf::vdf_verify_internal`, + arguments: [ + pure(tx, args.input, `vector`), + pure(tx, args.output, `vector`), + pure(tx, args.proof, `vector`), + pure(tx, args.iterations, `u64`), + ], + }); +} diff --git a/src/services/models/sui/sui/vec-map/functions.ts b/src/services/models/sui/sui/vec-map/functions.ts new file mode 100644 index 00000000..46266b00 --- /dev/null +++ b/src/services/models/sui/sui/vec-map/functions.ts @@ -0,0 +1,217 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj, pure, vector } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface ContainsArgs { + self: TransactionObjectInput; + key: GenericArg; +} + +export function contains(tx: Transaction, typeArgs: [string, string], args: ContainsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::contains`, + typeArguments: typeArgs, + arguments: [obj(tx, args.self), generic(tx, `${typeArgs[0]}`, args.key)], + }); +} + +export function destroyEmpty(tx: Transaction, typeArgs: [string, string], self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::destroy_empty`, + typeArguments: typeArgs, + arguments: [obj(tx, self)], + }); +} + +export function empty(tx: Transaction, typeArgs: [string, string]) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::empty`, + typeArguments: typeArgs, + arguments: [], + }); +} + +export interface InsertArgs { + self: TransactionObjectInput; + key: GenericArg; + value: GenericArg; +} + +export function insert(tx: Transaction, typeArgs: [string, string], args: InsertArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::insert`, + typeArguments: typeArgs, + arguments: [obj(tx, args.self), generic(tx, `${typeArgs[0]}`, args.key), generic(tx, `${typeArgs[1]}`, args.value)], + }); +} + +export function isEmpty(tx: Transaction, typeArgs: [string, string], self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::is_empty`, + typeArguments: typeArgs, + arguments: [obj(tx, self)], + }); +} + +export interface RemoveArgs { + self: TransactionObjectInput; + key: GenericArg; +} + +export function remove(tx: Transaction, typeArgs: [string, string], args: RemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::remove`, + typeArguments: typeArgs, + arguments: [obj(tx, args.self), generic(tx, `${typeArgs[0]}`, args.key)], + }); +} + +export function keys(tx: Transaction, typeArgs: [string, string], self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::keys`, + typeArguments: typeArgs, + arguments: [obj(tx, self)], + }); +} + +export interface GetIdxArgs { + self: TransactionObjectInput; + key: GenericArg; +} + +export function getIdx(tx: Transaction, typeArgs: [string, string], args: GetIdxArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::get_idx`, + typeArguments: typeArgs, + arguments: [obj(tx, args.self), generic(tx, `${typeArgs[0]}`, args.key)], + }); +} + +export interface GetIdxOptArgs { + self: TransactionObjectInput; + key: GenericArg; +} + +export function getIdxOpt(tx: Transaction, typeArgs: [string, string], args: GetIdxOptArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::get_idx_opt`, + typeArguments: typeArgs, + arguments: [obj(tx, args.self), generic(tx, `${typeArgs[0]}`, args.key)], + }); +} + +export function size(tx: Transaction, typeArgs: [string, string], self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::size`, + typeArguments: typeArgs, + arguments: [obj(tx, self)], + }); +} + +export interface GetArgs { + self: TransactionObjectInput; + key: GenericArg; +} + +export function get(tx: Transaction, typeArgs: [string, string], args: GetArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::get`, + typeArguments: typeArgs, + arguments: [obj(tx, args.self), generic(tx, `${typeArgs[0]}`, args.key)], + }); +} + +export interface FromKeysValuesArgs { + keys: Array | TransactionArgument; + values: Array | TransactionArgument; +} + +export function fromKeysValues(tx: Transaction, typeArgs: [string, string], args: FromKeysValuesArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::from_keys_values`, + typeArguments: typeArgs, + arguments: [vector(tx, `${typeArgs[0]}`, args.keys), vector(tx, `${typeArgs[1]}`, args.values)], + }); +} + +export interface GetEntryByIdxArgs { + self: TransactionObjectInput; + idx: bigint | TransactionArgument; +} + +export function getEntryByIdx(tx: Transaction, typeArgs: [string, string], args: GetEntryByIdxArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::get_entry_by_idx`, + typeArguments: typeArgs, + arguments: [obj(tx, args.self), pure(tx, args.idx, `u64`)], + }); +} + +export interface GetEntryByIdxMutArgs { + self: TransactionObjectInput; + idx: bigint | TransactionArgument; +} + +export function getEntryByIdxMut(tx: Transaction, typeArgs: [string, string], args: GetEntryByIdxMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::get_entry_by_idx_mut`, + typeArguments: typeArgs, + arguments: [obj(tx, args.self), pure(tx, args.idx, `u64`)], + }); +} + +export interface GetMutArgs { + self: TransactionObjectInput; + key: GenericArg; +} + +export function getMut(tx: Transaction, typeArgs: [string, string], args: GetMutArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::get_mut`, + typeArguments: typeArgs, + arguments: [obj(tx, args.self), generic(tx, `${typeArgs[0]}`, args.key)], + }); +} + +export function intoKeysValues(tx: Transaction, typeArgs: [string, string], self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::into_keys_values`, + typeArguments: typeArgs, + arguments: [obj(tx, self)], + }); +} + +export function pop(tx: Transaction, typeArgs: [string, string], self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::pop`, + typeArguments: typeArgs, + arguments: [obj(tx, self)], + }); +} + +export interface RemoveEntryByIdxArgs { + self: TransactionObjectInput; + idx: bigint | TransactionArgument; +} + +export function removeEntryByIdx(tx: Transaction, typeArgs: [string, string], args: RemoveEntryByIdxArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::remove_entry_by_idx`, + typeArguments: typeArgs, + arguments: [obj(tx, args.self), pure(tx, args.idx, `u64`)], + }); +} + +export interface TryGetArgs { + self: TransactionObjectInput; + key: GenericArg; +} + +export function tryGet(tx: Transaction, typeArgs: [string, string], args: TryGetArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_map::try_get`, + typeArguments: typeArgs, + arguments: [obj(tx, args.self), generic(tx, `${typeArgs[0]}`, args.key)], + }); +} diff --git a/src/services/models/sui/sui/vec-map/structs.ts b/src/services/models/sui/sui/vec-map/structs.ts new file mode 100644 index 00000000..14991ef5 --- /dev/null +++ b/src/services/models/sui/sui/vec-map/structs.ts @@ -0,0 +1,466 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeArgument, + ToTypeStr, + TypeArgument, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + fieldToJSON, + phantom, + toBcs, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { Vector } from "../../_framework/vector"; +import { PKG_V26 } from "../index"; +import { BcsType, bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Entry =============================== */ + +export function isEntry(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::vec_map::Entry` + "<"); +} + +export interface EntryFields { + key: ToField; + value: ToField; +} + +export type EntryReified = Reified, EntryFields>; + +export class Entry implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::vec_map::Entry`; + } + static readonly $numTypeParams = 2; + static readonly $isPhantom = [false, false] as const; + + readonly $typeName = Entry.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [ToTypeStr, ToTypeStr]; + readonly $isPhantom = Entry.$isPhantom; + + readonly key: ToField; + readonly value: ToField; + + private constructor(typeArgs: [ToTypeStr, ToTypeStr], fields: EntryFields) { + this.$fullTypeName = composeSuiType(Entry.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.key = fields.key; + this.value = fields.value; + } + + static reified, V extends Reified>( + K: K, + V: V + ): EntryReified, ToTypeArgument> { + return { + typeName: Entry.$typeName, + fullTypeName: composeSuiType(Entry.$typeName, ...[extractType(K), extractType(V)]) as string, + typeArgs: [extractType(K), extractType(V)] as [ToTypeStr>, ToTypeStr>], + isPhantom: Entry.$isPhantom, + reifiedTypeArgs: [K, V], + fromFields: (fields: Record) => Entry.fromFields([K, V], fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Entry.fromFieldsWithTypes([K, V], item), + fromBcs: (data: Uint8Array) => Entry.fromBcs([K, V], data), + bcs: Entry.bcs(toBcs(K), toBcs(V)), + fromJSONField: (field: any) => Entry.fromJSONField([K, V], field), + fromJSON: (json: Record) => Entry.fromJSON([K, V], json), + fromSuiParsedData: (content: SuiParsedData) => Entry.fromSuiParsedData([K, V], content), + fromSuiObjectData: (content: SuiObjectData) => Entry.fromSuiObjectData([K, V], content), + fetch: async (client: SuiClient, id: string) => Entry.fetch(client, [K, V], id), + new: (fields: EntryFields, ToTypeArgument>) => { + return new Entry([extractType(K), extractType(V)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Entry.reified; + } + + static phantom, V extends Reified>( + K: K, + V: V + ): PhantomReified, ToTypeArgument>>> { + return phantom(Entry.reified(K, V)); + } + static get p() { + return Entry.phantom; + } + + static get bcs() { + return , V extends BcsType>(K: K, V: V) => + bcs.struct(`Entry<${K.name}, ${V.name}>`, { + key: K, + value: V, + }); + } + + static fromFields, V extends Reified>( + typeArgs: [K, V], + fields: Record + ): Entry, ToTypeArgument> { + return Entry.reified(typeArgs[0], typeArgs[1]).new({ + key: decodeFromFields(typeArgs[0], fields.key), + value: decodeFromFields(typeArgs[1], fields.value), + }); + } + + static fromFieldsWithTypes, V extends Reified>( + typeArgs: [K, V], + item: FieldsWithTypes + ): Entry, ToTypeArgument> { + if (!isEntry(item.type)) { + throw new Error("not a Entry type"); + } + assertFieldsWithTypesArgsMatch(item, typeArgs); + + return Entry.reified(typeArgs[0], typeArgs[1]).new({ + key: decodeFromFieldsWithTypes(typeArgs[0], item.fields.key), + value: decodeFromFieldsWithTypes(typeArgs[1], item.fields.value), + }); + } + + static fromBcs, V extends Reified>( + typeArgs: [K, V], + data: Uint8Array + ): Entry, ToTypeArgument> { + return Entry.fromFields(typeArgs, Entry.bcs(toBcs(typeArgs[0]), toBcs(typeArgs[1])).parse(data)); + } + + toJSONField() { + return { + key: fieldToJSON(this.$typeArgs[0], this.key), + value: fieldToJSON(this.$typeArgs[1], this.value), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField, V extends Reified>( + typeArgs: [K, V], + field: any + ): Entry, ToTypeArgument> { + return Entry.reified(typeArgs[0], typeArgs[1]).new({ + key: decodeFromJSONField(typeArgs[0], field.key), + value: decodeFromJSONField(typeArgs[1], field.value), + }); + } + + static fromJSON, V extends Reified>( + typeArgs: [K, V], + json: Record + ): Entry, ToTypeArgument> { + if (json.$typeName !== Entry.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Entry.$typeName, ...typeArgs.map(extractType)), json.$typeArgs, typeArgs); + + return Entry.fromJSONField(typeArgs, json); + } + + static fromSuiParsedData, V extends Reified>( + typeArgs: [K, V], + content: SuiParsedData + ): Entry, ToTypeArgument> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isEntry(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Entry object`); + } + return Entry.fromFieldsWithTypes(typeArgs, content); + } + + static fromSuiObjectData, V extends Reified>( + typeArgs: [K, V], + data: SuiObjectData + ): Entry, ToTypeArgument> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isEntry(data.bcs.type)) { + throw new Error(`object at is not a Entry object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 2) { + throw new Error(`type argument mismatch: expected 2 type arguments but got ${gotTypeArgs.length}`); + } + for (let i = 0; i < 2; i++) { + const gotTypeArg = compressSuiType(gotTypeArgs[i]); + const expectedTypeArg = compressSuiType(extractType(typeArgs[i])); + if (gotTypeArg !== expectedTypeArg) { + throw new Error( + `type argument mismatch at position ${i}: expected '${expectedTypeArg}' but got '${gotTypeArg}'` + ); + } + } + + return Entry.fromBcs(typeArgs, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Entry.fromSuiParsedData(typeArgs, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch, V extends Reified>( + client: SuiClient, + typeArgs: [K, V], + id: string + ): Promise, ToTypeArgument>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Entry object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isEntry(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Entry object`); + } + + return Entry.fromSuiObjectData(typeArgs, res.data); + } +} + +/* ============================== VecMap =============================== */ + +export function isVecMap(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::vec_map::VecMap` + "<"); +} + +export interface VecMapFields { + contents: ToField>>; +} + +export type VecMapReified = Reified, VecMapFields>; + +export class VecMap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::vec_map::VecMap`; + } + static readonly $numTypeParams = 2; + static readonly $isPhantom = [false, false] as const; + + readonly $typeName = VecMap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [ToTypeStr, ToTypeStr]; + readonly $isPhantom = VecMap.$isPhantom; + + readonly contents: ToField>>; + + private constructor(typeArgs: [ToTypeStr, ToTypeStr], fields: VecMapFields) { + this.$fullTypeName = composeSuiType(VecMap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.contents = fields.contents; + } + + static reified, V extends Reified>( + K: K, + V: V + ): VecMapReified, ToTypeArgument> { + return { + typeName: VecMap.$typeName, + fullTypeName: composeSuiType(VecMap.$typeName, ...[extractType(K), extractType(V)]) as string, + typeArgs: [extractType(K), extractType(V)] as [ToTypeStr>, ToTypeStr>], + isPhantom: VecMap.$isPhantom, + reifiedTypeArgs: [K, V], + fromFields: (fields: Record) => VecMap.fromFields([K, V], fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => VecMap.fromFieldsWithTypes([K, V], item), + fromBcs: (data: Uint8Array) => VecMap.fromBcs([K, V], data), + bcs: VecMap.bcs(toBcs(K), toBcs(V)), + fromJSONField: (field: any) => VecMap.fromJSONField([K, V], field), + fromJSON: (json: Record) => VecMap.fromJSON([K, V], json), + fromSuiParsedData: (content: SuiParsedData) => VecMap.fromSuiParsedData([K, V], content), + fromSuiObjectData: (content: SuiObjectData) => VecMap.fromSuiObjectData([K, V], content), + fetch: async (client: SuiClient, id: string) => VecMap.fetch(client, [K, V], id), + new: (fields: VecMapFields, ToTypeArgument>) => { + return new VecMap([extractType(K), extractType(V)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return VecMap.reified; + } + + static phantom, V extends Reified>( + K: K, + V: V + ): PhantomReified, ToTypeArgument>>> { + return phantom(VecMap.reified(K, V)); + } + static get p() { + return VecMap.phantom; + } + + static get bcs() { + return , V extends BcsType>(K: K, V: V) => + bcs.struct(`VecMap<${K.name}, ${V.name}>`, { + contents: bcs.vector(Entry.bcs(K, V)), + }); + } + + static fromFields, V extends Reified>( + typeArgs: [K, V], + fields: Record + ): VecMap, ToTypeArgument> { + return VecMap.reified(typeArgs[0], typeArgs[1]).new({ + contents: decodeFromFields(reified.vector(Entry.reified(typeArgs[0], typeArgs[1])), fields.contents), + }); + } + + static fromFieldsWithTypes, V extends Reified>( + typeArgs: [K, V], + item: FieldsWithTypes + ): VecMap, ToTypeArgument> { + if (!isVecMap(item.type)) { + throw new Error("not a VecMap type"); + } + assertFieldsWithTypesArgsMatch(item, typeArgs); + + return VecMap.reified(typeArgs[0], typeArgs[1]).new({ + contents: decodeFromFieldsWithTypes( + reified.vector(Entry.reified(typeArgs[0], typeArgs[1])), + item.fields.contents + ), + }); + } + + static fromBcs, V extends Reified>( + typeArgs: [K, V], + data: Uint8Array + ): VecMap, ToTypeArgument> { + return VecMap.fromFields(typeArgs, VecMap.bcs(toBcs(typeArgs[0]), toBcs(typeArgs[1])).parse(data)); + } + + toJSONField() { + return { + contents: fieldToJSON>>( + `vector<${Entry.$typeName}<${this.$typeArgs[0]}, ${this.$typeArgs[1]}>>`, + this.contents + ), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField, V extends Reified>( + typeArgs: [K, V], + field: any + ): VecMap, ToTypeArgument> { + return VecMap.reified(typeArgs[0], typeArgs[1]).new({ + contents: decodeFromJSONField(reified.vector(Entry.reified(typeArgs[0], typeArgs[1])), field.contents), + }); + } + + static fromJSON, V extends Reified>( + typeArgs: [K, V], + json: Record + ): VecMap, ToTypeArgument> { + if (json.$typeName !== VecMap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch( + composeSuiType(VecMap.$typeName, ...typeArgs.map(extractType)), + json.$typeArgs, + typeArgs + ); + + return VecMap.fromJSONField(typeArgs, json); + } + + static fromSuiParsedData, V extends Reified>( + typeArgs: [K, V], + content: SuiParsedData + ): VecMap, ToTypeArgument> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isVecMap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a VecMap object`); + } + return VecMap.fromFieldsWithTypes(typeArgs, content); + } + + static fromSuiObjectData, V extends Reified>( + typeArgs: [K, V], + data: SuiObjectData + ): VecMap, ToTypeArgument> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isVecMap(data.bcs.type)) { + throw new Error(`object at is not a VecMap object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 2) { + throw new Error(`type argument mismatch: expected 2 type arguments but got ${gotTypeArgs.length}`); + } + for (let i = 0; i < 2; i++) { + const gotTypeArg = compressSuiType(gotTypeArgs[i]); + const expectedTypeArg = compressSuiType(extractType(typeArgs[i])); + if (gotTypeArg !== expectedTypeArg) { + throw new Error( + `type argument mismatch at position ${i}: expected '${expectedTypeArg}' but got '${gotTypeArg}'` + ); + } + } + + return VecMap.fromBcs(typeArgs, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return VecMap.fromSuiParsedData(typeArgs, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch, V extends Reified>( + client: SuiClient, + typeArgs: [K, V], + id: string + ): Promise, ToTypeArgument>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching VecMap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isVecMap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a VecMap object`); + } + + return VecMap.fromSuiObjectData(typeArgs, res.data); + } +} diff --git a/src/services/models/sui/sui/vec-set/functions.ts b/src/services/models/sui/sui/vec-set/functions.ts new file mode 100644 index 00000000..9213a5cb --- /dev/null +++ b/src/services/models/sui/sui/vec-set/functions.ts @@ -0,0 +1,125 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj, vector } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface ContainsArgs { + self: TransactionObjectInput; + key: GenericArg; +} + +export function contains(tx: Transaction, typeArg: string, args: ContainsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_set::contains`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), generic(tx, `${typeArg}`, args.key)], + }); +} + +export function empty(tx: Transaction, typeArg: string) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_set::empty`, + typeArguments: [typeArg], + arguments: [], + }); +} + +export interface InsertArgs { + self: TransactionObjectInput; + key: GenericArg; +} + +export function insert(tx: Transaction, typeArg: string, args: InsertArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_set::insert`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), generic(tx, `${typeArg}`, args.key)], + }); +} + +export function isEmpty(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_set::is_empty`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export interface RemoveArgs { + self: TransactionObjectInput; + key: GenericArg; +} + +export function remove(tx: Transaction, typeArg: string, args: RemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_set::remove`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), generic(tx, `${typeArg}`, args.key)], + }); +} + +export function singleton(tx: Transaction, typeArg: string, key: GenericArg) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_set::singleton`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, key)], + }); +} + +export function fromKeys(tx: Transaction, typeArg: string, keys: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_set::from_keys`, + typeArguments: [typeArg], + arguments: [vector(tx, `${typeArg}`, keys)], + }); +} + +export function keys(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_set::keys`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export interface GetIdxArgs { + self: TransactionObjectInput; + key: GenericArg; +} + +export function getIdx(tx: Transaction, typeArg: string, args: GetIdxArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_set::get_idx`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), generic(tx, `${typeArg}`, args.key)], + }); +} + +export interface GetIdxOptArgs { + self: TransactionObjectInput; + key: GenericArg; +} + +export function getIdxOpt(tx: Transaction, typeArg: string, args: GetIdxOptArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_set::get_idx_opt`, + typeArguments: [typeArg], + arguments: [obj(tx, args.self), generic(tx, `${typeArg}`, args.key)], + }); +} + +export function intoKeys(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_set::into_keys`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function size(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::vec_set::size`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} diff --git a/src/services/models/sui/sui/vec-set/structs.ts b/src/services/models/sui/sui/vec-set/structs.ts new file mode 100644 index 00000000..15071fd8 --- /dev/null +++ b/src/services/models/sui/sui/vec-set/structs.ts @@ -0,0 +1,223 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeArgument, + ToTypeStr, + TypeArgument, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + fieldToJSON, + phantom, + toBcs, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { Vector } from "../../_framework/vector"; +import { PKG_V26 } from "../index"; +import { BcsType, bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== VecSet =============================== */ + +export function isVecSet(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V26}::vec_set::VecSet` + "<"); +} + +export interface VecSetFields { + contents: ToField>; +} + +export type VecSetReified = Reified, VecSetFields>; + +export class VecSet implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::vec_set::VecSet`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [false] as const; + + readonly $typeName = VecSet.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [ToTypeStr]; + readonly $isPhantom = VecSet.$isPhantom; + + readonly contents: ToField>; + + private constructor(typeArgs: [ToTypeStr], fields: VecSetFields) { + this.$fullTypeName = composeSuiType(VecSet.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.contents = fields.contents; + } + + static reified>(K: K): VecSetReified> { + return { + typeName: VecSet.$typeName, + fullTypeName: composeSuiType(VecSet.$typeName, ...[extractType(K)]) as string, + typeArgs: [extractType(K)] as [ToTypeStr>], + isPhantom: VecSet.$isPhantom, + reifiedTypeArgs: [K], + fromFields: (fields: Record) => VecSet.fromFields(K, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => VecSet.fromFieldsWithTypes(K, item), + fromBcs: (data: Uint8Array) => VecSet.fromBcs(K, data), + bcs: VecSet.bcs(toBcs(K)), + fromJSONField: (field: any) => VecSet.fromJSONField(K, field), + fromJSON: (json: Record) => VecSet.fromJSON(K, json), + fromSuiParsedData: (content: SuiParsedData) => VecSet.fromSuiParsedData(K, content), + fromSuiObjectData: (content: SuiObjectData) => VecSet.fromSuiObjectData(K, content), + fetch: async (client: SuiClient, id: string) => VecSet.fetch(client, K, id), + new: (fields: VecSetFields>) => { + return new VecSet([extractType(K)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return VecSet.reified; + } + + static phantom>(K: K): PhantomReified>>> { + return phantom(VecSet.reified(K)); + } + static get p() { + return VecSet.phantom; + } + + static get bcs() { + return >(K: K) => + bcs.struct(`VecSet<${K.name}>`, { + contents: bcs.vector(K), + }); + } + + static fromFields>( + typeArg: K, + fields: Record + ): VecSet> { + return VecSet.reified(typeArg).new({ + contents: decodeFromFields(reified.vector(typeArg), fields.contents), + }); + } + + static fromFieldsWithTypes>( + typeArg: K, + item: FieldsWithTypes + ): VecSet> { + if (!isVecSet(item.type)) { + throw new Error("not a VecSet type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return VecSet.reified(typeArg).new({ + contents: decodeFromFieldsWithTypes(reified.vector(typeArg), item.fields.contents), + }); + } + + static fromBcs>(typeArg: K, data: Uint8Array): VecSet> { + const typeArgs = [typeArg]; + + return VecSet.fromFields(typeArg, VecSet.bcs(toBcs(typeArgs[0])).parse(data)); + } + + toJSONField() { + return { + contents: fieldToJSON>(`vector<${this.$typeArgs[0]}>`, this.contents), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>(typeArg: K, field: any): VecSet> { + return VecSet.reified(typeArg).new({ + contents: decodeFromJSONField(reified.vector(typeArg), field.contents), + }); + } + + static fromJSON>( + typeArg: K, + json: Record + ): VecSet> { + if (json.$typeName !== VecSet.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(VecSet.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return VecSet.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: K, + content: SuiParsedData + ): VecSet> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isVecSet(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a VecSet object`); + } + return VecSet.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: K, + data: SuiObjectData + ): VecSet> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isVecSet(data.bcs.type)) { + throw new Error(`object at is not a VecSet object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return VecSet.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return VecSet.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: K, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching VecSet object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isVecSet(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a VecSet object`); + } + + return VecSet.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/sui/versioned/functions.ts b/src/services/models/sui/sui/versioned/functions.ts new file mode 100644 index 00000000..8324758f --- /dev/null +++ b/src/services/models/sui/sui/versioned/functions.ts @@ -0,0 +1,76 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function version(tx: Transaction, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::versioned::version`, + arguments: [obj(tx, self)], + }); +} + +export interface CreateArgs { + initVersion: bigint | TransactionArgument; + initValue: GenericArg; +} + +export function create(tx: Transaction, typeArg: string, args: CreateArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::versioned::create`, + typeArguments: [typeArg], + arguments: [pure(tx, args.initVersion, `u64`), generic(tx, `${typeArg}`, args.initValue)], + }); +} + +export function destroy(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::versioned::destroy`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function loadValue(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::versioned::load_value`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function loadValueMut(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::versioned::load_value_mut`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export function removeValueForUpgrade(tx: Transaction, typeArg: string, self: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::versioned::remove_value_for_upgrade`, + typeArguments: [typeArg], + arguments: [obj(tx, self)], + }); +} + +export interface UpgradeArgs { + self: TransactionObjectInput; + newVersion: bigint | TransactionArgument; + newValue: GenericArg; + cap: TransactionObjectInput; +} + +export function upgrade(tx: Transaction, typeArg: string, args: UpgradeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::versioned::upgrade`, + typeArguments: [typeArg], + arguments: [ + obj(tx, args.self), + pure(tx, args.newVersion, `u64`), + generic(tx, `${typeArg}`, args.newValue), + obj(tx, args.cap), + ], + }); +} diff --git a/src/services/models/sui/sui/versioned/structs.ts b/src/services/models/sui/sui/versioned/structs.ts new file mode 100644 index 00000000..0b18ce79 --- /dev/null +++ b/src/services/models/sui/sui/versioned/structs.ts @@ -0,0 +1,360 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { ID, UID } from "../object/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== VersionChangeCap =============================== */ + +export function isVersionChangeCap(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::versioned::VersionChangeCap`; +} + +export interface VersionChangeCapFields { + versionedId: ToField; + oldVersion: ToField<"u64">; +} + +export type VersionChangeCapReified = Reified; + +export class VersionChangeCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::versioned::VersionChangeCap`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = VersionChangeCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = VersionChangeCap.$isPhantom; + + readonly versionedId: ToField; + readonly oldVersion: ToField<"u64">; + + private constructor(typeArgs: [], fields: VersionChangeCapFields) { + this.$fullTypeName = composeSuiType(VersionChangeCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.versionedId = fields.versionedId; + this.oldVersion = fields.oldVersion; + } + + static reified(): VersionChangeCapReified { + return { + typeName: VersionChangeCap.$typeName, + fullTypeName: composeSuiType(VersionChangeCap.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: VersionChangeCap.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => VersionChangeCap.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => VersionChangeCap.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => VersionChangeCap.fromBcs(data), + bcs: VersionChangeCap.bcs, + fromJSONField: (field: any) => VersionChangeCap.fromJSONField(field), + fromJSON: (json: Record) => VersionChangeCap.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => VersionChangeCap.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => VersionChangeCap.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => VersionChangeCap.fetch(client, id), + new: (fields: VersionChangeCapFields) => { + return new VersionChangeCap([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return VersionChangeCap.reified(); + } + + static phantom(): PhantomReified> { + return phantom(VersionChangeCap.reified()); + } + static get p() { + return VersionChangeCap.phantom(); + } + + static get bcs() { + return bcs.struct("VersionChangeCap", { + versioned_id: ID.bcs, + old_version: bcs.u64(), + }); + } + + static fromFields(fields: Record): VersionChangeCap { + return VersionChangeCap.reified().new({ + versionedId: decodeFromFields(ID.reified(), fields.versioned_id), + oldVersion: decodeFromFields("u64", fields.old_version), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): VersionChangeCap { + if (!isVersionChangeCap(item.type)) { + throw new Error("not a VersionChangeCap type"); + } + + return VersionChangeCap.reified().new({ + versionedId: decodeFromFieldsWithTypes(ID.reified(), item.fields.versioned_id), + oldVersion: decodeFromFieldsWithTypes("u64", item.fields.old_version), + }); + } + + static fromBcs(data: Uint8Array): VersionChangeCap { + return VersionChangeCap.fromFields(VersionChangeCap.bcs.parse(data)); + } + + toJSONField() { + return { + versionedId: this.versionedId, + oldVersion: this.oldVersion.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): VersionChangeCap { + return VersionChangeCap.reified().new({ + versionedId: decodeFromJSONField(ID.reified(), field.versionedId), + oldVersion: decodeFromJSONField("u64", field.oldVersion), + }); + } + + static fromJSON(json: Record): VersionChangeCap { + if (json.$typeName !== VersionChangeCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return VersionChangeCap.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): VersionChangeCap { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isVersionChangeCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a VersionChangeCap object`); + } + return VersionChangeCap.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): VersionChangeCap { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isVersionChangeCap(data.bcs.type)) { + throw new Error(`object at is not a VersionChangeCap object`); + } + + return VersionChangeCap.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return VersionChangeCap.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching VersionChangeCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isVersionChangeCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a VersionChangeCap object`); + } + + return VersionChangeCap.fromSuiObjectData(res.data); + } +} + +/* ============================== Versioned =============================== */ + +export function isVersioned(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::versioned::Versioned`; +} + +export interface VersionedFields { + id: ToField; + version: ToField<"u64">; +} + +export type VersionedReified = Reified; + +export class Versioned implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::versioned::Versioned`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Versioned.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Versioned.$isPhantom; + + readonly id: ToField; + readonly version: ToField<"u64">; + + private constructor(typeArgs: [], fields: VersionedFields) { + this.$fullTypeName = composeSuiType(Versioned.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.version = fields.version; + } + + static reified(): VersionedReified { + return { + typeName: Versioned.$typeName, + fullTypeName: composeSuiType(Versioned.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Versioned.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Versioned.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Versioned.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Versioned.fromBcs(data), + bcs: Versioned.bcs, + fromJSONField: (field: any) => Versioned.fromJSONField(field), + fromJSON: (json: Record) => Versioned.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Versioned.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Versioned.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Versioned.fetch(client, id), + new: (fields: VersionedFields) => { + return new Versioned([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Versioned.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Versioned.reified()); + } + static get p() { + return Versioned.phantom(); + } + + static get bcs() { + return bcs.struct("Versioned", { + id: UID.bcs, + version: bcs.u64(), + }); + } + + static fromFields(fields: Record): Versioned { + return Versioned.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + version: decodeFromFields("u64", fields.version), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Versioned { + if (!isVersioned(item.type)) { + throw new Error("not a Versioned type"); + } + + return Versioned.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + version: decodeFromFieldsWithTypes("u64", item.fields.version), + }); + } + + static fromBcs(data: Uint8Array): Versioned { + return Versioned.fromFields(Versioned.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + version: this.version.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Versioned { + return Versioned.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + version: decodeFromJSONField("u64", field.version), + }); + } + + static fromJSON(json: Record): Versioned { + if (json.$typeName !== Versioned.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Versioned.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Versioned { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isVersioned(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Versioned object`); + } + return Versioned.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Versioned { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isVersioned(data.bcs.type)) { + throw new Error(`object at is not a Versioned object`); + } + + return Versioned.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Versioned.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Versioned object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isVersioned(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Versioned object`); + } + + return Versioned.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/sui/zklogin-verified-id/functions.ts b/src/services/models/sui/sui/zklogin-verified-id/functions.ts new file mode 100644 index 00000000..b07245b0 --- /dev/null +++ b/src/services/models/sui/sui/zklogin-verified-id/functions.ts @@ -0,0 +1,114 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { String } from "../../_dependencies/source/0x1/string/structs"; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function delete_(tx: Transaction, verifiedId: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::zklogin_verified_id::delete`, + arguments: [obj(tx, verifiedId)], + }); +} + +export function owner(tx: Transaction, verifiedId: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::zklogin_verified_id::owner`, + arguments: [obj(tx, verifiedId)], + }); +} + +export function audience(tx: Transaction, verifiedId: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::zklogin_verified_id::audience`, + arguments: [obj(tx, verifiedId)], + }); +} + +export interface CheckZkloginIdArgs { + address: string | TransactionArgument; + keyClaimName: string | TransactionArgument; + keyClaimValue: string | TransactionArgument; + issuer: string | TransactionArgument; + audience: string | TransactionArgument; + pinHash: bigint | TransactionArgument; +} + +export function checkZkloginId(tx: Transaction, args: CheckZkloginIdArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::zklogin_verified_id::check_zklogin_id`, + arguments: [ + pure(tx, args.address, `address`), + pure(tx, args.keyClaimName, `${String.$typeName}`), + pure(tx, args.keyClaimValue, `${String.$typeName}`), + pure(tx, args.issuer, `${String.$typeName}`), + pure(tx, args.audience, `${String.$typeName}`), + pure(tx, args.pinHash, `u256`), + ], + }); +} + +export interface CheckZkloginIdInternalArgs { + address: string | TransactionArgument; + keyClaimName: Array | TransactionArgument; + keyClaimValue: Array | TransactionArgument; + issuer: Array | TransactionArgument; + audience: Array | TransactionArgument; + pinHash: bigint | TransactionArgument; +} + +export function checkZkloginIdInternal(tx: Transaction, args: CheckZkloginIdInternalArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::zklogin_verified_id::check_zklogin_id_internal`, + arguments: [ + pure(tx, args.address, `address`), + pure(tx, args.keyClaimName, `vector`), + pure(tx, args.keyClaimValue, `vector`), + pure(tx, args.issuer, `vector`), + pure(tx, args.audience, `vector`), + pure(tx, args.pinHash, `u256`), + ], + }); +} + +export function keyClaimName(tx: Transaction, verifiedId: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::zklogin_verified_id::key_claim_name`, + arguments: [obj(tx, verifiedId)], + }); +} + +export function keyClaimValue(tx: Transaction, verifiedId: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::zklogin_verified_id::key_claim_value`, + arguments: [obj(tx, verifiedId)], + }); +} + +export function issuer(tx: Transaction, verifiedId: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::zklogin_verified_id::issuer`, + arguments: [obj(tx, verifiedId)], + }); +} + +export interface VerifyZkloginIdArgs { + keyClaimName: string | TransactionArgument; + keyClaimValue: string | TransactionArgument; + issuer: string | TransactionArgument; + audience: string | TransactionArgument; + pinHash: bigint | TransactionArgument; +} + +export function verifyZkloginId(tx: Transaction, args: VerifyZkloginIdArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::zklogin_verified_id::verify_zklogin_id`, + arguments: [ + pure(tx, args.keyClaimName, `${String.$typeName}`), + pure(tx, args.keyClaimValue, `${String.$typeName}`), + pure(tx, args.issuer, `${String.$typeName}`), + pure(tx, args.audience, `${String.$typeName}`), + pure(tx, args.pinHash, `u256`), + ], + }); +} diff --git a/src/services/models/sui/sui/zklogin-verified-id/structs.ts b/src/services/models/sui/sui/zklogin-verified-id/structs.ts new file mode 100644 index 00000000..a975acce --- /dev/null +++ b/src/services/models/sui/sui/zklogin-verified-id/structs.ts @@ -0,0 +1,225 @@ +// @ts-nocheck +import { String } from "../../_dependencies/source/0x1/string/structs"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { UID } from "../object/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64, fromHEX, toHEX } from "@mysten/sui/utils"; + +/* ============================== VerifiedID =============================== */ + +export function isVerifiedID(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::zklogin_verified_id::VerifiedID`; +} + +export interface VerifiedIDFields { + id: ToField; + owner: ToField<"address">; + keyClaimName: ToField; + keyClaimValue: ToField; + issuer: ToField; + audience: ToField; +} + +export type VerifiedIDReified = Reified; + +export class VerifiedID implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::zklogin_verified_id::VerifiedID`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = VerifiedID.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = VerifiedID.$isPhantom; + + readonly id: ToField; + readonly owner: ToField<"address">; + readonly keyClaimName: ToField; + readonly keyClaimValue: ToField; + readonly issuer: ToField; + readonly audience: ToField; + + private constructor(typeArgs: [], fields: VerifiedIDFields) { + this.$fullTypeName = composeSuiType(VerifiedID.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.owner = fields.owner; + this.keyClaimName = fields.keyClaimName; + this.keyClaimValue = fields.keyClaimValue; + this.issuer = fields.issuer; + this.audience = fields.audience; + } + + static reified(): VerifiedIDReified { + return { + typeName: VerifiedID.$typeName, + fullTypeName: composeSuiType(VerifiedID.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: VerifiedID.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => VerifiedID.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => VerifiedID.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => VerifiedID.fromBcs(data), + bcs: VerifiedID.bcs, + fromJSONField: (field: any) => VerifiedID.fromJSONField(field), + fromJSON: (json: Record) => VerifiedID.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => VerifiedID.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => VerifiedID.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => VerifiedID.fetch(client, id), + new: (fields: VerifiedIDFields) => { + return new VerifiedID([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return VerifiedID.reified(); + } + + static phantom(): PhantomReified> { + return phantom(VerifiedID.reified()); + } + static get p() { + return VerifiedID.phantom(); + } + + static get bcs() { + return bcs.struct("VerifiedID", { + id: UID.bcs, + owner: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + key_claim_name: String.bcs, + key_claim_value: String.bcs, + issuer: String.bcs, + audience: String.bcs, + }); + } + + static fromFields(fields: Record): VerifiedID { + return VerifiedID.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + owner: decodeFromFields("address", fields.owner), + keyClaimName: decodeFromFields(String.reified(), fields.key_claim_name), + keyClaimValue: decodeFromFields(String.reified(), fields.key_claim_value), + issuer: decodeFromFields(String.reified(), fields.issuer), + audience: decodeFromFields(String.reified(), fields.audience), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): VerifiedID { + if (!isVerifiedID(item.type)) { + throw new Error("not a VerifiedID type"); + } + + return VerifiedID.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + owner: decodeFromFieldsWithTypes("address", item.fields.owner), + keyClaimName: decodeFromFieldsWithTypes(String.reified(), item.fields.key_claim_name), + keyClaimValue: decodeFromFieldsWithTypes(String.reified(), item.fields.key_claim_value), + issuer: decodeFromFieldsWithTypes(String.reified(), item.fields.issuer), + audience: decodeFromFieldsWithTypes(String.reified(), item.fields.audience), + }); + } + + static fromBcs(data: Uint8Array): VerifiedID { + return VerifiedID.fromFields(VerifiedID.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + owner: this.owner, + keyClaimName: this.keyClaimName, + keyClaimValue: this.keyClaimValue, + issuer: this.issuer, + audience: this.audience, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): VerifiedID { + return VerifiedID.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + owner: decodeFromJSONField("address", field.owner), + keyClaimName: decodeFromJSONField(String.reified(), field.keyClaimName), + keyClaimValue: decodeFromJSONField(String.reified(), field.keyClaimValue), + issuer: decodeFromJSONField(String.reified(), field.issuer), + audience: decodeFromJSONField(String.reified(), field.audience), + }); + } + + static fromJSON(json: Record): VerifiedID { + if (json.$typeName !== VerifiedID.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return VerifiedID.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): VerifiedID { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isVerifiedID(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a VerifiedID object`); + } + return VerifiedID.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): VerifiedID { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isVerifiedID(data.bcs.type)) { + throw new Error(`object at is not a VerifiedID object`); + } + + return VerifiedID.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return VerifiedID.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching VerifiedID object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isVerifiedID(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a VerifiedID object`); + } + + return VerifiedID.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/sui/zklogin-verified-issuer/functions.ts b/src/services/models/sui/sui/zklogin-verified-issuer/functions.ts new file mode 100644 index 00000000..09a0ba4a --- /dev/null +++ b/src/services/models/sui/sui/zklogin-verified-issuer/functions.ts @@ -0,0 +1,72 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { String } from "../../_dependencies/source/0x1/string/structs"; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function delete_(tx: Transaction, verifiedIssuer: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::zklogin_verified_issuer::delete`, + arguments: [obj(tx, verifiedIssuer)], + }); +} + +export function owner(tx: Transaction, verifiedIssuer: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::zklogin_verified_issuer::owner`, + arguments: [obj(tx, verifiedIssuer)], + }); +} + +export function issuer(tx: Transaction, verifiedIssuer: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::zklogin_verified_issuer::issuer`, + arguments: [obj(tx, verifiedIssuer)], + }); +} + +export interface CheckZkloginIssuerArgs { + address: string | TransactionArgument; + addressSeed: bigint | TransactionArgument; + issuer: string | TransactionArgument; +} + +export function checkZkloginIssuer(tx: Transaction, args: CheckZkloginIssuerArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::zklogin_verified_issuer::check_zklogin_issuer`, + arguments: [ + pure(tx, args.address, `address`), + pure(tx, args.addressSeed, `u256`), + pure(tx, args.issuer, `${String.$typeName}`), + ], + }); +} + +export interface CheckZkloginIssuerInternalArgs { + address: string | TransactionArgument; + addressSeed: bigint | TransactionArgument; + issuer: Array | TransactionArgument; +} + +export function checkZkloginIssuerInternal(tx: Transaction, args: CheckZkloginIssuerInternalArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::zklogin_verified_issuer::check_zklogin_issuer_internal`, + arguments: [ + pure(tx, args.address, `address`), + pure(tx, args.addressSeed, `u256`), + pure(tx, args.issuer, `vector`), + ], + }); +} + +export interface VerifyZkloginIssuerArgs { + addressSeed: bigint | TransactionArgument; + issuer: string | TransactionArgument; +} + +export function verifyZkloginIssuer(tx: Transaction, args: VerifyZkloginIssuerArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::zklogin_verified_issuer::verify_zklogin_issuer`, + arguments: [pure(tx, args.addressSeed, `u256`), pure(tx, args.issuer, `${String.$typeName}`)], + }); +} diff --git a/src/services/models/sui/sui/zklogin-verified-issuer/structs.ts b/src/services/models/sui/sui/zklogin-verified-issuer/structs.ts new file mode 100644 index 00000000..87556984 --- /dev/null +++ b/src/services/models/sui/sui/zklogin-verified-issuer/structs.ts @@ -0,0 +1,201 @@ +// @ts-nocheck +import { String } from "../../_dependencies/source/0x1/string/structs"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { PKG_V26 } from "../index"; +import { UID } from "../object/structs"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64, fromHEX, toHEX } from "@mysten/sui/utils"; + +/* ============================== VerifiedIssuer =============================== */ + +export function isVerifiedIssuer(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V26}::zklogin_verified_issuer::VerifiedIssuer`; +} + +export interface VerifiedIssuerFields { + id: ToField; + owner: ToField<"address">; + issuer: ToField; +} + +export type VerifiedIssuerReified = Reified; + +export class VerifiedIssuer implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V26}::zklogin_verified_issuer::VerifiedIssuer`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = VerifiedIssuer.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = VerifiedIssuer.$isPhantom; + + readonly id: ToField; + readonly owner: ToField<"address">; + readonly issuer: ToField; + + private constructor(typeArgs: [], fields: VerifiedIssuerFields) { + this.$fullTypeName = composeSuiType(VerifiedIssuer.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.owner = fields.owner; + this.issuer = fields.issuer; + } + + static reified(): VerifiedIssuerReified { + return { + typeName: VerifiedIssuer.$typeName, + fullTypeName: composeSuiType(VerifiedIssuer.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: VerifiedIssuer.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => VerifiedIssuer.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => VerifiedIssuer.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => VerifiedIssuer.fromBcs(data), + bcs: VerifiedIssuer.bcs, + fromJSONField: (field: any) => VerifiedIssuer.fromJSONField(field), + fromJSON: (json: Record) => VerifiedIssuer.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => VerifiedIssuer.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => VerifiedIssuer.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => VerifiedIssuer.fetch(client, id), + new: (fields: VerifiedIssuerFields) => { + return new VerifiedIssuer([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return VerifiedIssuer.reified(); + } + + static phantom(): PhantomReified> { + return phantom(VerifiedIssuer.reified()); + } + static get p() { + return VerifiedIssuer.phantom(); + } + + static get bcs() { + return bcs.struct("VerifiedIssuer", { + id: UID.bcs, + owner: bcs.bytes(32).transform({ + input: (val: string) => fromHEX(val), + output: (val: Uint8Array) => toHEX(val), + }), + issuer: String.bcs, + }); + } + + static fromFields(fields: Record): VerifiedIssuer { + return VerifiedIssuer.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + owner: decodeFromFields("address", fields.owner), + issuer: decodeFromFields(String.reified(), fields.issuer), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): VerifiedIssuer { + if (!isVerifiedIssuer(item.type)) { + throw new Error("not a VerifiedIssuer type"); + } + + return VerifiedIssuer.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + owner: decodeFromFieldsWithTypes("address", item.fields.owner), + issuer: decodeFromFieldsWithTypes(String.reified(), item.fields.issuer), + }); + } + + static fromBcs(data: Uint8Array): VerifiedIssuer { + return VerifiedIssuer.fromFields(VerifiedIssuer.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + owner: this.owner, + issuer: this.issuer, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): VerifiedIssuer { + return VerifiedIssuer.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + owner: decodeFromJSONField("address", field.owner), + issuer: decodeFromJSONField(String.reified(), field.issuer), + }); + } + + static fromJSON(json: Record): VerifiedIssuer { + if (json.$typeName !== VerifiedIssuer.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return VerifiedIssuer.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): VerifiedIssuer { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isVerifiedIssuer(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a VerifiedIssuer object`); + } + return VerifiedIssuer.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): VerifiedIssuer { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isVerifiedIssuer(data.bcs.type)) { + throw new Error(`object at is not a VerifiedIssuer object`); + } + + return VerifiedIssuer.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return VerifiedIssuer.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching VerifiedIssuer object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isVerifiedIssuer(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a VerifiedIssuer object`); + } + + return VerifiedIssuer.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/utils/bytes32/functions.ts b/src/services/models/sui/utils/bytes32/functions.ts new file mode 100644 index 00000000..42e4bf55 --- /dev/null +++ b/src/services/models/sui/utils/bytes32/functions.ts @@ -0,0 +1,108 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { String } from "../../_dependencies/source/0x1/ascii/structs"; +import { String as String1 } from "../../_dependencies/source/0x1/string/structs"; +import { obj, pure } from "../../_framework/util"; +import { ID } from "../../sui/object/structs"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function isZero(tx: Transaction, bytes: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bytes32::is_zero`, + arguments: [obj(tx, bytes)], + }); +} + +export function data(tx: Transaction, bytes: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bytes32::data`, + arguments: [obj(tx, bytes)], + }); +} + +export function empty(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bytes32::empty`, + arguments: [], + }); +} + +export function new_(tx: Transaction, data: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bytes32::new`, + arguments: [pure(tx, data, `vector`)], + }); +} + +export function fromAddress(tx: Transaction, a: string | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bytes32::from_address`, + arguments: [pure(tx, a, `address`)], + }); +} + +export function fromAsciiHex(tx: Transaction, value: string | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bytes32::from_ascii_hex`, + arguments: [pure(tx, value, `${String.$typeName}`)], + }); +} + +export function fromHex(tx: Transaction, value: string | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bytes32::from_hex`, + arguments: [pure(tx, value, `${String1.$typeName}`)], + }); +} + +export function fromId(tx: Transaction, id: string | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bytes32::from_id`, + arguments: [pure(tx, id, `${ID.$typeName}`)], + }); +} + +export function fromUid(tx: Transaction, id: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bytes32::from_uid`, + arguments: [obj(tx, id)], + }); +} + +export function newFromPartial( + tx: Transaction, + partialData: Array | TransactionArgument +) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bytes32::new_from_partial`, + arguments: [pure(tx, partialData, `vector`)], + }); +} + +export function toAddress(tx: Transaction, bytes: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bytes32::to_address`, + arguments: [obj(tx, bytes)], + }); +} + +export function toAsciiHex(tx: Transaction, bytes: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bytes32::to_ascii_hex`, + arguments: [obj(tx, bytes)], + }); +} + +export function toHex(tx: Transaction, bytes: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bytes32::to_hex`, + arguments: [obj(tx, bytes)], + }); +} + +export function toId(tx: Transaction, bytes: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::bytes32::to_id`, + arguments: [obj(tx, bytes)], + }); +} diff --git a/src/services/models/sui/utils/bytes32/structs.ts b/src/services/models/sui/utils/bytes32/structs.ts new file mode 100644 index 00000000..d5cc81bb --- /dev/null +++ b/src/services/models/sui/utils/bytes32/structs.ts @@ -0,0 +1,183 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { Vector } from "../../_framework/vector"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Bytes32 =============================== */ + +export function isBytes32(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::bytes32::Bytes32`; +} + +export interface Bytes32Fields { + data: ToField>; +} + +export type Bytes32Reified = Reified; + +export class Bytes32 implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::bytes32::Bytes32`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Bytes32.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Bytes32.$isPhantom; + + readonly data: ToField>; + + private constructor(typeArgs: [], fields: Bytes32Fields) { + this.$fullTypeName = composeSuiType(Bytes32.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.data = fields.data; + } + + static reified(): Bytes32Reified { + return { + typeName: Bytes32.$typeName, + fullTypeName: composeSuiType(Bytes32.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Bytes32.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Bytes32.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Bytes32.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Bytes32.fromBcs(data), + bcs: Bytes32.bcs, + fromJSONField: (field: any) => Bytes32.fromJSONField(field), + fromJSON: (json: Record) => Bytes32.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Bytes32.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Bytes32.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Bytes32.fetch(client, id), + new: (fields: Bytes32Fields) => { + return new Bytes32([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Bytes32.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Bytes32.reified()); + } + static get p() { + return Bytes32.phantom(); + } + + static get bcs() { + return bcs.struct("Bytes32", { + data: bcs.vector(bcs.u8()), + }); + } + + static fromFields(fields: Record): Bytes32 { + return Bytes32.reified().new({ + data: decodeFromFields(reified.vector("u8"), fields.data), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Bytes32 { + if (!isBytes32(item.type)) { + throw new Error("not a Bytes32 type"); + } + + return Bytes32.reified().new({ + data: decodeFromFieldsWithTypes(reified.vector("u8"), item.fields.data), + }); + } + + static fromBcs(data: Uint8Array): Bytes32 { + return Bytes32.fromFields(Bytes32.bcs.parse(data)); + } + + toJSONField() { + return { + data: fieldToJSON>(`vector`, this.data), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Bytes32 { + return Bytes32.reified().new({ + data: decodeFromJSONField(reified.vector("u8"), field.data), + }); + } + + static fromJSON(json: Record): Bytes32 { + if (json.$typeName !== Bytes32.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Bytes32.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Bytes32 { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isBytes32(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Bytes32 object`); + } + return Bytes32.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Bytes32 { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isBytes32(data.bcs.type)) { + throw new Error(`object at is not a Bytes32 object`); + } + + return Bytes32.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Bytes32.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Bytes32 object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isBytes32(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Bytes32 object`); + } + + return Bytes32.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/utils/fee-collector/functions.ts b/src/services/models/sui/utils/fee-collector/functions.ts new file mode 100644 index 00000000..f589f1fb --- /dev/null +++ b/src/services/models/sui/utils/fee-collector/functions.ts @@ -0,0 +1,55 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function new_(tx: Transaction, typeArg: string) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::fee_collector::new`, + typeArguments: [typeArg], + arguments: [], + }); +} + +export function key(tx: Transaction, typeArg: string) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::fee_collector::key`, + typeArguments: [typeArg], + arguments: [], + }); +} + +export function balance(tx: Transaction, typeArgs: [string, string], feeCollector: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::fee_collector::balance`, + typeArguments: typeArgs, + arguments: [obj(tx, feeCollector)], + }); +} + +export interface WithdrawArgs { + cap: GenericArg; + feeCollector: TransactionObjectInput; + amount: bigint | TransactionArgument; +} + +export function withdraw(tx: Transaction, typeArgs: [string, string], args: WithdrawArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::fee_collector::withdraw`, + typeArguments: typeArgs, + arguments: [generic(tx, `${typeArgs[1]}`, args.cap), obj(tx, args.feeCollector), pure(tx, args.amount, `u64`)], + }); +} + +export interface AddFeeArgs { + feeCollector: TransactionObjectInput; + coin: TransactionObjectInput; +} + +export function addFee(tx: Transaction, typeArgs: [string, string], args: AddFeeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::fee_collector::add_fee`, + typeArguments: typeArgs, + arguments: [obj(tx, args.feeCollector), obj(tx, args.coin)], + }); +} diff --git a/src/services/models/sui/utils/fee-collector/structs.ts b/src/services/models/sui/utils/fee-collector/structs.ts new file mode 100644 index 00000000..be05d1e2 --- /dev/null +++ b/src/services/models/sui/utils/fee-collector/structs.ts @@ -0,0 +1,228 @@ +// @ts-nocheck +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { Bag } from "../../sui/bag/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== FeeCollector =============================== */ + +export function isFeeCollector(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V1}::fee_collector::FeeCollector` + "<"); +} + +export interface FeeCollectorFields { + balances: ToField; +} + +export type FeeCollectorReified = Reified, FeeCollectorFields>; + +export class FeeCollector implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::fee_collector::FeeCollector`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = FeeCollector.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = FeeCollector.$isPhantom; + + readonly balances: ToField; + + private constructor(typeArgs: [PhantomToTypeStr], fields: FeeCollectorFields) { + this.$fullTypeName = composeSuiType(FeeCollector.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.balances = fields.balances; + } + + static reified>( + Cap: Cap + ): FeeCollectorReified> { + return { + typeName: FeeCollector.$typeName, + fullTypeName: composeSuiType(FeeCollector.$typeName, ...[extractType(Cap)]) as string, + typeArgs: [extractType(Cap)] as [PhantomToTypeStr>], + isPhantom: FeeCollector.$isPhantom, + reifiedTypeArgs: [Cap], + fromFields: (fields: Record) => FeeCollector.fromFields(Cap, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => FeeCollector.fromFieldsWithTypes(Cap, item), + fromBcs: (data: Uint8Array) => FeeCollector.fromBcs(Cap, data), + bcs: FeeCollector.bcs, + fromJSONField: (field: any) => FeeCollector.fromJSONField(Cap, field), + fromJSON: (json: Record) => FeeCollector.fromJSON(Cap, json), + fromSuiParsedData: (content: SuiParsedData) => FeeCollector.fromSuiParsedData(Cap, content), + fromSuiObjectData: (content: SuiObjectData) => FeeCollector.fromSuiObjectData(Cap, content), + fetch: async (client: SuiClient, id: string) => FeeCollector.fetch(client, Cap, id), + new: (fields: FeeCollectorFields>) => { + return new FeeCollector([extractType(Cap)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return FeeCollector.reified; + } + + static phantom>( + Cap: Cap + ): PhantomReified>>> { + return phantom(FeeCollector.reified(Cap)); + } + static get p() { + return FeeCollector.phantom; + } + + static get bcs() { + return bcs.struct("FeeCollector", { + balances: Bag.bcs, + }); + } + + static fromFields>( + typeArg: Cap, + fields: Record + ): FeeCollector> { + return FeeCollector.reified(typeArg).new({ + balances: decodeFromFields(Bag.reified(), fields.balances), + }); + } + + static fromFieldsWithTypes>( + typeArg: Cap, + item: FieldsWithTypes + ): FeeCollector> { + if (!isFeeCollector(item.type)) { + throw new Error("not a FeeCollector type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return FeeCollector.reified(typeArg).new({ + balances: decodeFromFieldsWithTypes(Bag.reified(), item.fields.balances), + }); + } + + static fromBcs>( + typeArg: Cap, + data: Uint8Array + ): FeeCollector> { + return FeeCollector.fromFields(typeArg, FeeCollector.bcs.parse(data)); + } + + toJSONField() { + return { + balances: this.balances.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: Cap, + field: any + ): FeeCollector> { + return FeeCollector.reified(typeArg).new({ + balances: decodeFromJSONField(Bag.reified(), field.balances), + }); + } + + static fromJSON>( + typeArg: Cap, + json: Record + ): FeeCollector> { + if (json.$typeName !== FeeCollector.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(FeeCollector.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return FeeCollector.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: Cap, + content: SuiParsedData + ): FeeCollector> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isFeeCollector(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a FeeCollector object`); + } + return FeeCollector.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: Cap, + data: SuiObjectData + ): FeeCollector> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isFeeCollector(data.bcs.type)) { + throw new Error(`object at is not a FeeCollector object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return FeeCollector.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return FeeCollector.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: Cap, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching FeeCollector object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isFeeCollector(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a FeeCollector object`); + } + + return FeeCollector.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/utils/index.ts b/src/services/models/sui/utils/index.ts new file mode 100644 index 00000000..12959240 --- /dev/null +++ b/src/services/models/sui/utils/index.ts @@ -0,0 +1,33 @@ +// @ts-nocheck +import { compressSuiType } from "../_framework/util"; + +class PackageAddress { + private static $PACKAGE_ID = ""; + private static $PUBLISHED_AT = ""; + private static $PKG_V = []; + get PACKAGE_ID() { + return compressSuiType(PackageAddress.$PACKAGE_ID); + } + get PUBLISHED_AT() { + return compressSuiType(PackageAddress.$PUBLISHED_AT); + } + get PKG_V1() { + return compressSuiType(PackageAddress.$PKG_V[1]); + } + setPackageId(address: string): void { + PackageAddress.$PACKAGE_ID = address; + } + setPublishedAt(address: string): void { + PackageAddress.$PUBLISHED_AT = address; + } + setPkgV(v: number, address: string): void { + PackageAddress.$PKG_V[v] = address; + } + setAddress(address: string, pkgV1?: string) { + PackageAddress.$PACKAGE_ID = address; + PackageAddress.$PUBLISHED_AT = address; + PackageAddress.$PKG_V[1] = pkgV1 || address; + } +} +const packageAddress = new PackageAddress(); +export = packageAddress; diff --git a/src/services/models/sui/utils/init.ts b/src/services/models/sui/utils/init.ts new file mode 100644 index 00000000..41401683 --- /dev/null +++ b/src/services/models/sui/utils/init.ts @@ -0,0 +1,18 @@ +// @ts-nocheck +import * as bytes32 from "./bytes32/structs"; +import * as feeCollector from "./fee-collector/structs"; +import * as message from "./message/structs"; +import * as messengerProtocol from "./messenger-protocol/structs"; +import * as set from "./set/structs"; +import * as version from "./version/structs"; +import { StructClassLoader } from "../_framework/loader"; + +export function registerClasses(loader: StructClassLoader) { + loader.register(messengerProtocol.MessengerProtocol); + loader.register(bytes32.Bytes32); + loader.register(message.Message); + loader.register(version.CurrentVersion); + loader.register(set.Empty); + loader.register(set.Set); + loader.register(feeCollector.FeeCollector); +} diff --git a/src/services/models/sui/utils/message/functions.ts b/src/services/models/sui/utils/message/functions.ts new file mode 100644 index 00000000..46110285 --- /dev/null +++ b/src/services/models/sui/utils/message/functions.ts @@ -0,0 +1,111 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { ID } from "../../sui/object/structs"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function data(tx: Transaction, message: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::message::data`, + arguments: [obj(tx, message)], + }); +} + +export function fromBytes(tx: Transaction, message: Array | TransactionArgument) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::message::from_bytes`, + arguments: [pure(tx, message, `vector`)], + }); +} + +export function new_(tx: Transaction, message: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::message::new`, + arguments: [obj(tx, message)], + }); +} + +export function toHex(tx: Transaction, message: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::message::to_hex`, + arguments: [obj(tx, message)], + }); +} + +export interface AddSenderArgs { + message: TransactionObjectInput; + sender: string | TransactionArgument; +} + +export function addSender(tx: Transaction, args: AddSenderArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::message::add_sender`, + arguments: [obj(tx, args.message), pure(tx, args.sender, `${ID.$typeName}`)], + }); +} + +export function chainFrom(tx: Transaction, message: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::message::chain_from`, + arguments: [obj(tx, message)], + }); +} + +export function chainTo(tx: Transaction, message: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::message::chain_to`, + arguments: [obj(tx, message)], + }); +} + +export interface FromArgsArgs { + amount: bigint | TransactionArgument; + recipient: TransactionObjectInput; + sourceChainId: number | TransactionArgument; + destinationChainId: number | TransactionArgument; + receiveToken: TransactionObjectInput; + nonce: bigint | TransactionArgument; + messenger: TransactionObjectInput; +} + +export function fromArgs(tx: Transaction, args: FromArgsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::message::from_args`, + arguments: [ + pure(tx, args.amount, `u64`), + obj(tx, args.recipient), + pure(tx, args.sourceChainId, `u8`), + pure(tx, args.destinationChainId, `u8`), + obj(tx, args.receiveToken), + pure(tx, args.nonce, `u256`), + obj(tx, args.messenger), + ], + }); +} + +export interface FromArgsWithSenderArgs { + amount: bigint | TransactionArgument; + recipient: TransactionObjectInput; + sourceChainId: number | TransactionArgument; + destinationChainId: number | TransactionArgument; + receiveToken: TransactionObjectInput; + nonce: bigint | TransactionArgument; + messenger: TransactionObjectInput; + sender: string | TransactionArgument; +} + +export function fromArgsWithSender(tx: Transaction, args: FromArgsWithSenderArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::message::from_args_with_sender`, + arguments: [ + pure(tx, args.amount, `u64`), + obj(tx, args.recipient), + pure(tx, args.sourceChainId, `u8`), + pure(tx, args.destinationChainId, `u8`), + obj(tx, args.receiveToken), + pure(tx, args.nonce, `u256`), + obj(tx, args.messenger), + pure(tx, args.sender, `${ID.$typeName}`), + ], + }); +} diff --git a/src/services/models/sui/utils/message/structs.ts b/src/services/models/sui/utils/message/structs.ts new file mode 100644 index 00000000..a0cae6ba --- /dev/null +++ b/src/services/models/sui/utils/message/structs.ts @@ -0,0 +1,181 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { Bytes32 } from "../bytes32/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Message =============================== */ + +export function isMessage(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::message::Message`; +} + +export interface MessageFields { + message: ToField; +} + +export type MessageReified = Reified; + +export class Message implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::message::Message`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Message.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Message.$isPhantom; + + readonly message: ToField; + + private constructor(typeArgs: [], fields: MessageFields) { + this.$fullTypeName = composeSuiType(Message.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.message = fields.message; + } + + static reified(): MessageReified { + return { + typeName: Message.$typeName, + fullTypeName: composeSuiType(Message.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Message.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Message.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Message.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Message.fromBcs(data), + bcs: Message.bcs, + fromJSONField: (field: any) => Message.fromJSONField(field), + fromJSON: (json: Record) => Message.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Message.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Message.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Message.fetch(client, id), + new: (fields: MessageFields) => { + return new Message([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Message.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Message.reified()); + } + static get p() { + return Message.phantom(); + } + + static get bcs() { + return bcs.struct("Message", { + message: Bytes32.bcs, + }); + } + + static fromFields(fields: Record): Message { + return Message.reified().new({ + message: decodeFromFields(Bytes32.reified(), fields.message), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Message { + if (!isMessage(item.type)) { + throw new Error("not a Message type"); + } + + return Message.reified().new({ + message: decodeFromFieldsWithTypes(Bytes32.reified(), item.fields.message), + }); + } + + static fromBcs(data: Uint8Array): Message { + return Message.fromFields(Message.bcs.parse(data)); + } + + toJSONField() { + return { + message: this.message.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Message { + return Message.reified().new({ + message: decodeFromJSONField(Bytes32.reified(), field.message), + }); + } + + static fromJSON(json: Record): Message { + if (json.$typeName !== Message.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Message.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Message { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isMessage(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Message object`); + } + return Message.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Message { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isMessage(data.bcs.type)) { + throw new Error(`object at is not a Message object`); + } + + return Message.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Message.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Message object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isMessage(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Message object`); + } + + return Message.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/utils/messenger-protocol/functions.ts b/src/services/models/sui/utils/messenger-protocol/functions.ts new file mode 100644 index 00000000..97ea1f15 --- /dev/null +++ b/src/services/models/sui/utils/messenger-protocol/functions.ts @@ -0,0 +1,25 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj } from "../../_framework/util"; +import { Transaction, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function wormhole(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger_protocol::wormhole`, + arguments: [], + }); +} + +export function allbridge(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger_protocol::allbridge`, + arguments: [], + }); +} + +export function id(tx: Transaction, messengerProtocol: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::messenger_protocol::id`, + arguments: [obj(tx, messengerProtocol)], + }); +} diff --git a/src/services/models/sui/utils/messenger-protocol/structs.ts b/src/services/models/sui/utils/messenger-protocol/structs.ts new file mode 100644 index 00000000..1902ed3e --- /dev/null +++ b/src/services/models/sui/utils/messenger-protocol/structs.ts @@ -0,0 +1,180 @@ +// @ts-nocheck +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== MessengerProtocol =============================== */ + +export function isMessengerProtocol(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::messenger_protocol::MessengerProtocol`; +} + +export interface MessengerProtocolFields { + id: ToField<"u8">; +} + +export type MessengerProtocolReified = Reified; + +export class MessengerProtocol implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::messenger_protocol::MessengerProtocol`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = MessengerProtocol.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = MessengerProtocol.$isPhantom; + + readonly id: ToField<"u8">; + + private constructor(typeArgs: [], fields: MessengerProtocolFields) { + this.$fullTypeName = composeSuiType(MessengerProtocol.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified(): MessengerProtocolReified { + return { + typeName: MessengerProtocol.$typeName, + fullTypeName: composeSuiType(MessengerProtocol.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: MessengerProtocol.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => MessengerProtocol.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => MessengerProtocol.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => MessengerProtocol.fromBcs(data), + bcs: MessengerProtocol.bcs, + fromJSONField: (field: any) => MessengerProtocol.fromJSONField(field), + fromJSON: (json: Record) => MessengerProtocol.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => MessengerProtocol.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => MessengerProtocol.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => MessengerProtocol.fetch(client, id), + new: (fields: MessengerProtocolFields) => { + return new MessengerProtocol([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return MessengerProtocol.reified(); + } + + static phantom(): PhantomReified> { + return phantom(MessengerProtocol.reified()); + } + static get p() { + return MessengerProtocol.phantom(); + } + + static get bcs() { + return bcs.struct("MessengerProtocol", { + id: bcs.u8(), + }); + } + + static fromFields(fields: Record): MessengerProtocol { + return MessengerProtocol.reified().new({ + id: decodeFromFields("u8", fields.id), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): MessengerProtocol { + if (!isMessengerProtocol(item.type)) { + throw new Error("not a MessengerProtocol type"); + } + + return MessengerProtocol.reified().new({ + id: decodeFromFieldsWithTypes("u8", item.fields.id), + }); + } + + static fromBcs(data: Uint8Array): MessengerProtocol { + return MessengerProtocol.fromFields(MessengerProtocol.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): MessengerProtocol { + return MessengerProtocol.reified().new({ + id: decodeFromJSONField("u8", field.id), + }); + } + + static fromJSON(json: Record): MessengerProtocol { + if (json.$typeName !== MessengerProtocol.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return MessengerProtocol.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): MessengerProtocol { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isMessengerProtocol(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a MessengerProtocol object`); + } + return MessengerProtocol.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): MessengerProtocol { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isMessengerProtocol(data.bcs.type)) { + throw new Error(`object at is not a MessengerProtocol object`); + } + + return MessengerProtocol.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return MessengerProtocol.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching MessengerProtocol object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isMessengerProtocol(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a MessengerProtocol object`); + } + + return MessengerProtocol.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/utils/set/functions.ts b/src/services/models/sui/utils/set/functions.ts new file mode 100644 index 00000000..f1e14730 --- /dev/null +++ b/src/services/models/sui/utils/set/functions.ts @@ -0,0 +1,59 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj } from "../../_framework/util"; +import { Transaction, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface AddArgs { + set: TransactionObjectInput; + key: GenericArg; +} + +export function add(tx: Transaction, typeArg: string, args: AddArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::set::add`, + typeArguments: [typeArg], + arguments: [obj(tx, args.set), generic(tx, `${typeArg}`, args.key)], + }); +} + +export interface ContainsArgs { + set: TransactionObjectInput; + key: GenericArg; +} + +export function contains(tx: Transaction, typeArg: string, args: ContainsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::set::contains`, + typeArguments: [typeArg], + arguments: [obj(tx, args.set), generic(tx, `${typeArg}`, args.key)], + }); +} + +export function destroyEmpty(tx: Transaction, typeArg: string, set: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::set::destroy_empty`, + typeArguments: [typeArg], + arguments: [obj(tx, set)], + }); +} + +export interface RemoveArgs { + set: TransactionObjectInput; + key: GenericArg; +} + +export function remove(tx: Transaction, typeArg: string, args: RemoveArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::set::remove`, + typeArguments: [typeArg], + arguments: [obj(tx, args.set), generic(tx, `${typeArg}`, args.key)], + }); +} + +export function new_(tx: Transaction, typeArg: string) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::set::new`, + typeArguments: [typeArg], + arguments: [], + }); +} diff --git a/src/services/models/sui/utils/set/structs.ts b/src/services/models/sui/utils/set/structs.ts new file mode 100644 index 00000000..70629412 --- /dev/null +++ b/src/services/models/sui/utils/set/structs.ts @@ -0,0 +1,391 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, + ToTypeStr as ToPhantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { Table } from "../../sui/table/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== Empty =============================== */ + +export function isEmpty(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::set::Empty`; +} + +export interface EmptyFields { + dummyField: ToField<"bool">; +} + +export type EmptyReified = Reified; + +export class Empty implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::set::Empty`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = Empty.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = Empty.$isPhantom; + + readonly dummyField: ToField<"bool">; + + private constructor(typeArgs: [], fields: EmptyFields) { + this.$fullTypeName = composeSuiType(Empty.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.dummyField = fields.dummyField; + } + + static reified(): EmptyReified { + return { + typeName: Empty.$typeName, + fullTypeName: composeSuiType(Empty.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: Empty.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => Empty.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Empty.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => Empty.fromBcs(data), + bcs: Empty.bcs, + fromJSONField: (field: any) => Empty.fromJSONField(field), + fromJSON: (json: Record) => Empty.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => Empty.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => Empty.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => Empty.fetch(client, id), + new: (fields: EmptyFields) => { + return new Empty([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Empty.reified(); + } + + static phantom(): PhantomReified> { + return phantom(Empty.reified()); + } + static get p() { + return Empty.phantom(); + } + + static get bcs() { + return bcs.struct("Empty", { + dummy_field: bcs.bool(), + }); + } + + static fromFields(fields: Record): Empty { + return Empty.reified().new({ + dummyField: decodeFromFields("bool", fields.dummy_field), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): Empty { + if (!isEmpty(item.type)) { + throw new Error("not a Empty type"); + } + + return Empty.reified().new({ + dummyField: decodeFromFieldsWithTypes("bool", item.fields.dummy_field), + }); + } + + static fromBcs(data: Uint8Array): Empty { + return Empty.fromFields(Empty.bcs.parse(data)); + } + + toJSONField() { + return { + dummyField: this.dummyField, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): Empty { + return Empty.reified().new({ + dummyField: decodeFromJSONField("bool", field.dummyField), + }); + } + + static fromJSON(json: Record): Empty { + if (json.$typeName !== Empty.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return Empty.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): Empty { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isEmpty(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Empty object`); + } + return Empty.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): Empty { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isEmpty(data.bcs.type)) { + throw new Error(`object at is not a Empty object`); + } + + return Empty.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Empty.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Empty object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isEmpty(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Empty object`); + } + + return Empty.fromSuiObjectData(res.data); + } +} + +/* ============================== Set =============================== */ + +export function isSet(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V1}::set::Set` + "<"); +} + +export interface SetFields { + items: ToField>>; +} + +export type SetReified = Reified, SetFields>; + +export class Set implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::set::Set`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = Set.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = Set.$isPhantom; + + readonly items: ToField>>; + + private constructor(typeArgs: [PhantomToTypeStr], fields: SetFields) { + this.$fullTypeName = composeSuiType(Set.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.items = fields.items; + } + + static reified>(T: T): SetReified> { + return { + typeName: Set.$typeName, + fullTypeName: composeSuiType(Set.$typeName, ...[extractType(T)]) as string, + typeArgs: [extractType(T)] as [PhantomToTypeStr>], + isPhantom: Set.$isPhantom, + reifiedTypeArgs: [T], + fromFields: (fields: Record) => Set.fromFields(T, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => Set.fromFieldsWithTypes(T, item), + fromBcs: (data: Uint8Array) => Set.fromBcs(T, data), + bcs: Set.bcs, + fromJSONField: (field: any) => Set.fromJSONField(T, field), + fromJSON: (json: Record) => Set.fromJSON(T, json), + fromSuiParsedData: (content: SuiParsedData) => Set.fromSuiParsedData(T, content), + fromSuiObjectData: (content: SuiObjectData) => Set.fromSuiObjectData(T, content), + fetch: async (client: SuiClient, id: string) => Set.fetch(client, T, id), + new: (fields: SetFields>) => { + return new Set([extractType(T)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return Set.reified; + } + + static phantom>( + T: T + ): PhantomReified>>> { + return phantom(Set.reified(T)); + } + static get p() { + return Set.phantom; + } + + static get bcs() { + return bcs.struct("Set", { + items: Table.bcs, + }); + } + + static fromFields>( + typeArg: T, + fields: Record + ): Set> { + return Set.reified(typeArg).new({ + items: decodeFromFields(Table.reified(typeArg, reified.phantom(Empty.reified())), fields.items), + }); + } + + static fromFieldsWithTypes>( + typeArg: T, + item: FieldsWithTypes + ): Set> { + if (!isSet(item.type)) { + throw new Error("not a Set type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return Set.reified(typeArg).new({ + items: decodeFromFieldsWithTypes(Table.reified(typeArg, reified.phantom(Empty.reified())), item.fields.items), + }); + } + + static fromBcs>( + typeArg: T, + data: Uint8Array + ): Set> { + return Set.fromFields(typeArg, Set.bcs.parse(data)); + } + + toJSONField() { + return { + items: this.items.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: T, + field: any + ): Set> { + return Set.reified(typeArg).new({ + items: decodeFromJSONField(Table.reified(typeArg, reified.phantom(Empty.reified())), field.items), + }); + } + + static fromJSON>( + typeArg: T, + json: Record + ): Set> { + if (json.$typeName !== Set.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(Set.$typeName, extractType(typeArg)), json.$typeArgs, [typeArg]); + + return Set.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: T, + content: SuiParsedData + ): Set> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isSet(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a Set object`); + } + return Set.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: T, + data: SuiObjectData + ): Set> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isSet(data.bcs.type)) { + throw new Error(`object at is not a Set object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return Set.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return Set.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: T, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching Set object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isSet(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a Set object`); + } + + return Set.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/utils/version/functions.ts b/src/services/models/sui/utils/version/functions.ts new file mode 100644 index 00000000..fc0286e9 --- /dev/null +++ b/src/services/models/sui/utils/version/functions.ts @@ -0,0 +1,45 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { GenericArg, generic, obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface AssertVersionArgs { + id: TransactionObjectInput; + version: bigint | TransactionArgument; +} + +export function assertVersion(tx: Transaction, typeArg: string, args: AssertVersionArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::version::assert_version`, + typeArguments: [typeArg], + arguments: [obj(tx, args.id), pure(tx, args.version, `u64`)], + }); +} + +export interface InitVersionArgs { + cap: GenericArg; + id: TransactionObjectInput; + version: bigint | TransactionArgument; +} + +export function initVersion(tx: Transaction, typeArg: string, args: InitVersionArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::version::init_version`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, args.cap), obj(tx, args.id), pure(tx, args.version, `u64`)], + }); +} + +export interface MigrateVersionArgs { + cap: GenericArg; + id: TransactionObjectInput; + newVersion: bigint | TransactionArgument; +} + +export function migrateVersion(tx: Transaction, typeArg: string, args: MigrateVersionArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::version::migrate_version`, + typeArguments: [typeArg], + arguments: [generic(tx, `${typeArg}`, args.cap), obj(tx, args.id), pure(tx, args.newVersion, `u64`)], + }); +} diff --git a/src/services/models/sui/utils/version/structs.ts b/src/services/models/sui/utils/version/structs.ts new file mode 100644 index 00000000..f3e14977 --- /dev/null +++ b/src/services/models/sui/utils/version/structs.ts @@ -0,0 +1,232 @@ +// @ts-nocheck +import { + PhantomReified, + PhantomToTypeStr, + PhantomTypeArgument, + Reified, + StructClass, + ToField, + ToPhantomTypeArgument, + ToTypeStr, + assertFieldsWithTypesArgsMatch, + assertReifiedTypeArgsMatch, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + extractType, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType, parseTypeName } from "../../_framework/util"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== CurrentVersion =============================== */ + +export function isCurrentVersion(type: string): boolean { + type = compressSuiType(type); + return type.startsWith(`${PKG_V1}::version::CurrentVersion` + "<"); +} + +export interface CurrentVersionFields { + version: ToField<"u64">; +} + +export type CurrentVersionReified = Reified< + CurrentVersion, + CurrentVersionFields +>; + +export class CurrentVersion implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::version::CurrentVersion`; + } + static readonly $numTypeParams = 1; + static readonly $isPhantom = [true] as const; + + readonly $typeName = CurrentVersion.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: [PhantomToTypeStr]; + readonly $isPhantom = CurrentVersion.$isPhantom; + + readonly version: ToField<"u64">; + + private constructor(typeArgs: [PhantomToTypeStr], fields: CurrentVersionFields) { + this.$fullTypeName = composeSuiType(CurrentVersion.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.version = fields.version; + } + + static reified>( + Cap: Cap + ): CurrentVersionReified> { + return { + typeName: CurrentVersion.$typeName, + fullTypeName: composeSuiType(CurrentVersion.$typeName, ...[extractType(Cap)]) as string, + typeArgs: [extractType(Cap)] as [PhantomToTypeStr>], + isPhantom: CurrentVersion.$isPhantom, + reifiedTypeArgs: [Cap], + fromFields: (fields: Record) => CurrentVersion.fromFields(Cap, fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => CurrentVersion.fromFieldsWithTypes(Cap, item), + fromBcs: (data: Uint8Array) => CurrentVersion.fromBcs(Cap, data), + bcs: CurrentVersion.bcs, + fromJSONField: (field: any) => CurrentVersion.fromJSONField(Cap, field), + fromJSON: (json: Record) => CurrentVersion.fromJSON(Cap, json), + fromSuiParsedData: (content: SuiParsedData) => CurrentVersion.fromSuiParsedData(Cap, content), + fromSuiObjectData: (content: SuiObjectData) => CurrentVersion.fromSuiObjectData(Cap, content), + fetch: async (client: SuiClient, id: string) => CurrentVersion.fetch(client, Cap, id), + new: (fields: CurrentVersionFields>) => { + return new CurrentVersion([extractType(Cap)], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return CurrentVersion.reified; + } + + static phantom>( + Cap: Cap + ): PhantomReified>>> { + return phantom(CurrentVersion.reified(Cap)); + } + static get p() { + return CurrentVersion.phantom; + } + + static get bcs() { + return bcs.struct("CurrentVersion", { + version: bcs.u64(), + }); + } + + static fromFields>( + typeArg: Cap, + fields: Record + ): CurrentVersion> { + return CurrentVersion.reified(typeArg).new({ + version: decodeFromFields("u64", fields.version), + }); + } + + static fromFieldsWithTypes>( + typeArg: Cap, + item: FieldsWithTypes + ): CurrentVersion> { + if (!isCurrentVersion(item.type)) { + throw new Error("not a CurrentVersion type"); + } + assertFieldsWithTypesArgsMatch(item, [typeArg]); + + return CurrentVersion.reified(typeArg).new({ + version: decodeFromFieldsWithTypes("u64", item.fields.version), + }); + } + + static fromBcs>( + typeArg: Cap, + data: Uint8Array + ): CurrentVersion> { + return CurrentVersion.fromFields(typeArg, CurrentVersion.bcs.parse(data)); + } + + toJSONField() { + return { + version: this.version.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField>( + typeArg: Cap, + field: any + ): CurrentVersion> { + return CurrentVersion.reified(typeArg).new({ + version: decodeFromJSONField("u64", field.version), + }); + } + + static fromJSON>( + typeArg: Cap, + json: Record + ): CurrentVersion> { + if (json.$typeName !== CurrentVersion.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + assertReifiedTypeArgsMatch(composeSuiType(CurrentVersion.$typeName, extractType(typeArg)), json.$typeArgs, [ + typeArg, + ]); + + return CurrentVersion.fromJSONField(typeArg, json); + } + + static fromSuiParsedData>( + typeArg: Cap, + content: SuiParsedData + ): CurrentVersion> { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isCurrentVersion(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a CurrentVersion object`); + } + return CurrentVersion.fromFieldsWithTypes(typeArg, content); + } + + static fromSuiObjectData>( + typeArg: Cap, + data: SuiObjectData + ): CurrentVersion> { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isCurrentVersion(data.bcs.type)) { + throw new Error(`object at is not a CurrentVersion object`); + } + + const gotTypeArgs = parseTypeName(data.bcs.type).typeArgs; + if (gotTypeArgs.length !== 1) { + throw new Error(`type argument mismatch: expected 1 type argument but got '${gotTypeArgs.length}'`); + } + const gotTypeArg = compressSuiType(gotTypeArgs[0]); + const expectedTypeArg = compressSuiType(extractType(typeArg)); + if (gotTypeArg !== compressSuiType(extractType(typeArg))) { + throw new Error(`type argument mismatch: expected '${expectedTypeArg}' but got '${gotTypeArg}'`); + } + + return CurrentVersion.fromBcs(typeArg, fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return CurrentVersion.fromSuiParsedData(typeArg, data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch>( + client: SuiClient, + typeArg: Cap, + id: string + ): Promise>> { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching CurrentVersion object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isCurrentVersion(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a CurrentVersion object`); + } + + return CurrentVersion.fromSuiObjectData(typeArg, res.data); + } +} diff --git a/src/services/models/sui/wormhole-messenger/events/functions.ts b/src/services/models/sui/wormhole-messenger/events/functions.ts new file mode 100644 index 00000000..30044de1 --- /dev/null +++ b/src/services/models/sui/wormhole-messenger/events/functions.ts @@ -0,0 +1,28 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface MessageReceivedEventArgs { + message: TransactionObjectInput; + sequence: bigint | TransactionArgument; +} + +export function messageReceivedEvent(tx: Transaction, args: MessageReceivedEventArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::events::message_received_event`, + arguments: [obj(tx, args.message), pure(tx, args.sequence, `u64`)], + }); +} + +export interface MessageSentEventArgs { + message: TransactionObjectInput; + sequence: bigint | TransactionArgument; +} + +export function messageSentEvent(tx: Transaction, args: MessageSentEventArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::events::message_sent_event`, + arguments: [obj(tx, args.message), pure(tx, args.sequence, `u64`)], + }); +} diff --git a/src/services/models/sui/wormhole-messenger/events/structs.ts b/src/services/models/sui/wormhole-messenger/events/structs.ts new file mode 100644 index 00000000..b582011e --- /dev/null +++ b/src/services/models/sui/wormhole-messenger/events/structs.ts @@ -0,0 +1,360 @@ +// @ts-nocheck +import { String } from "../../_dependencies/source/0x1/ascii/structs"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + phantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== MessageReceivedEvent =============================== */ + +export function isMessageReceivedEvent(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::events::MessageReceivedEvent`; +} + +export interface MessageReceivedEventFields { + message: ToField; + sequence: ToField<"u64">; +} + +export type MessageReceivedEventReified = Reified; + +export class MessageReceivedEvent implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::events::MessageReceivedEvent`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = MessageReceivedEvent.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = MessageReceivedEvent.$isPhantom; + + readonly message: ToField; + readonly sequence: ToField<"u64">; + + private constructor(typeArgs: [], fields: MessageReceivedEventFields) { + this.$fullTypeName = composeSuiType(MessageReceivedEvent.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.message = fields.message; + this.sequence = fields.sequence; + } + + static reified(): MessageReceivedEventReified { + return { + typeName: MessageReceivedEvent.$typeName, + fullTypeName: composeSuiType(MessageReceivedEvent.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: MessageReceivedEvent.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => MessageReceivedEvent.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => MessageReceivedEvent.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => MessageReceivedEvent.fromBcs(data), + bcs: MessageReceivedEvent.bcs, + fromJSONField: (field: any) => MessageReceivedEvent.fromJSONField(field), + fromJSON: (json: Record) => MessageReceivedEvent.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => MessageReceivedEvent.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => MessageReceivedEvent.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => MessageReceivedEvent.fetch(client, id), + new: (fields: MessageReceivedEventFields) => { + return new MessageReceivedEvent([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return MessageReceivedEvent.reified(); + } + + static phantom(): PhantomReified> { + return phantom(MessageReceivedEvent.reified()); + } + static get p() { + return MessageReceivedEvent.phantom(); + } + + static get bcs() { + return bcs.struct("MessageReceivedEvent", { + message: String.bcs, + sequence: bcs.u64(), + }); + } + + static fromFields(fields: Record): MessageReceivedEvent { + return MessageReceivedEvent.reified().new({ + message: decodeFromFields(String.reified(), fields.message), + sequence: decodeFromFields("u64", fields.sequence), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): MessageReceivedEvent { + if (!isMessageReceivedEvent(item.type)) { + throw new Error("not a MessageReceivedEvent type"); + } + + return MessageReceivedEvent.reified().new({ + message: decodeFromFieldsWithTypes(String.reified(), item.fields.message), + sequence: decodeFromFieldsWithTypes("u64", item.fields.sequence), + }); + } + + static fromBcs(data: Uint8Array): MessageReceivedEvent { + return MessageReceivedEvent.fromFields(MessageReceivedEvent.bcs.parse(data)); + } + + toJSONField() { + return { + message: this.message, + sequence: this.sequence.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): MessageReceivedEvent { + return MessageReceivedEvent.reified().new({ + message: decodeFromJSONField(String.reified(), field.message), + sequence: decodeFromJSONField("u64", field.sequence), + }); + } + + static fromJSON(json: Record): MessageReceivedEvent { + if (json.$typeName !== MessageReceivedEvent.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return MessageReceivedEvent.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): MessageReceivedEvent { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isMessageReceivedEvent(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a MessageReceivedEvent object`); + } + return MessageReceivedEvent.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): MessageReceivedEvent { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isMessageReceivedEvent(data.bcs.type)) { + throw new Error(`object at is not a MessageReceivedEvent object`); + } + + return MessageReceivedEvent.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return MessageReceivedEvent.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching MessageReceivedEvent object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isMessageReceivedEvent(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a MessageReceivedEvent object`); + } + + return MessageReceivedEvent.fromSuiObjectData(res.data); + } +} + +/* ============================== MessageSentEvent =============================== */ + +export function isMessageSentEvent(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::events::MessageSentEvent`; +} + +export interface MessageSentEventFields { + message: ToField; + sequence: ToField<"u64">; +} + +export type MessageSentEventReified = Reified; + +export class MessageSentEvent implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::events::MessageSentEvent`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = MessageSentEvent.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = MessageSentEvent.$isPhantom; + + readonly message: ToField; + readonly sequence: ToField<"u64">; + + private constructor(typeArgs: [], fields: MessageSentEventFields) { + this.$fullTypeName = composeSuiType(MessageSentEvent.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.message = fields.message; + this.sequence = fields.sequence; + } + + static reified(): MessageSentEventReified { + return { + typeName: MessageSentEvent.$typeName, + fullTypeName: composeSuiType(MessageSentEvent.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: MessageSentEvent.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => MessageSentEvent.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => MessageSentEvent.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => MessageSentEvent.fromBcs(data), + bcs: MessageSentEvent.bcs, + fromJSONField: (field: any) => MessageSentEvent.fromJSONField(field), + fromJSON: (json: Record) => MessageSentEvent.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => MessageSentEvent.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => MessageSentEvent.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => MessageSentEvent.fetch(client, id), + new: (fields: MessageSentEventFields) => { + return new MessageSentEvent([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return MessageSentEvent.reified(); + } + + static phantom(): PhantomReified> { + return phantom(MessageSentEvent.reified()); + } + static get p() { + return MessageSentEvent.phantom(); + } + + static get bcs() { + return bcs.struct("MessageSentEvent", { + message: String.bcs, + sequence: bcs.u64(), + }); + } + + static fromFields(fields: Record): MessageSentEvent { + return MessageSentEvent.reified().new({ + message: decodeFromFields(String.reified(), fields.message), + sequence: decodeFromFields("u64", fields.sequence), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): MessageSentEvent { + if (!isMessageSentEvent(item.type)) { + throw new Error("not a MessageSentEvent type"); + } + + return MessageSentEvent.reified().new({ + message: decodeFromFieldsWithTypes(String.reified(), item.fields.message), + sequence: decodeFromFieldsWithTypes("u64", item.fields.sequence), + }); + } + + static fromBcs(data: Uint8Array): MessageSentEvent { + return MessageSentEvent.fromFields(MessageSentEvent.bcs.parse(data)); + } + + toJSONField() { + return { + message: this.message, + sequence: this.sequence.toString(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): MessageSentEvent { + return MessageSentEvent.reified().new({ + message: decodeFromJSONField(String.reified(), field.message), + sequence: decodeFromJSONField("u64", field.sequence), + }); + } + + static fromJSON(json: Record): MessageSentEvent { + if (json.$typeName !== MessageSentEvent.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return MessageSentEvent.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): MessageSentEvent { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isMessageSentEvent(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a MessageSentEvent object`); + } + return MessageSentEvent.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): MessageSentEvent { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isMessageSentEvent(data.bcs.type)) { + throw new Error(`object at is not a MessageSentEvent object`); + } + + return MessageSentEvent.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return MessageSentEvent.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching MessageSentEvent object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isMessageSentEvent(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a MessageSentEvent object`); + } + + return MessageSentEvent.fromSuiObjectData(res.data); + } +} diff --git a/src/services/models/sui/wormhole-messenger/index.ts b/src/services/models/sui/wormhole-messenger/index.ts new file mode 100644 index 00000000..12959240 --- /dev/null +++ b/src/services/models/sui/wormhole-messenger/index.ts @@ -0,0 +1,33 @@ +// @ts-nocheck +import { compressSuiType } from "../_framework/util"; + +class PackageAddress { + private static $PACKAGE_ID = ""; + private static $PUBLISHED_AT = ""; + private static $PKG_V = []; + get PACKAGE_ID() { + return compressSuiType(PackageAddress.$PACKAGE_ID); + } + get PUBLISHED_AT() { + return compressSuiType(PackageAddress.$PUBLISHED_AT); + } + get PKG_V1() { + return compressSuiType(PackageAddress.$PKG_V[1]); + } + setPackageId(address: string): void { + PackageAddress.$PACKAGE_ID = address; + } + setPublishedAt(address: string): void { + PackageAddress.$PUBLISHED_AT = address; + } + setPkgV(v: number, address: string): void { + PackageAddress.$PKG_V[v] = address; + } + setAddress(address: string, pkgV1?: string) { + PackageAddress.$PACKAGE_ID = address; + PackageAddress.$PUBLISHED_AT = address; + PackageAddress.$PKG_V[1] = pkgV1 || address; + } +} +const packageAddress = new PackageAddress(); +export = packageAddress; diff --git a/src/services/models/sui/wormhole-messenger/init.ts b/src/services/models/sui/wormhole-messenger/init.ts new file mode 100644 index 00000000..286cbc9b --- /dev/null +++ b/src/services/models/sui/wormhole-messenger/init.ts @@ -0,0 +1,11 @@ +// @ts-nocheck +import * as events from "./events/structs"; +import * as wormholeMessenger from "./wormhole-messenger/structs"; +import { StructClassLoader } from "../_framework/loader"; + +export function registerClasses(loader: StructClassLoader) { + loader.register(events.MessageReceivedEvent); + loader.register(events.MessageSentEvent); + loader.register(wormholeMessenger.AdminCap); + loader.register(wormholeMessenger.WormholeMessenger); +} diff --git a/src/services/models/sui/wormhole-messenger/wh-messenger-interface/functions.ts b/src/services/models/sui/wormhole-messenger/wh-messenger-interface/functions.ts new file mode 100644 index 00000000..eb7cd37d --- /dev/null +++ b/src/services/models/sui/wormhole-messenger/wh-messenger-interface/functions.ts @@ -0,0 +1,219 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export interface MigrateArgs { + adminCap: TransactionObjectInput; + wormholeMessenger: TransactionObjectInput; +} + +export function migrate(tx: Transaction, args: MigrateArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wh_messenger_interface::migrate`, + arguments: [obj(tx, args.adminCap), obj(tx, args.wormholeMessenger)], + }); +} + +export function gasBalanceValue(tx: Transaction, messenger: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wh_messenger_interface::gas_balance_value`, + arguments: [obj(tx, messenger)], + }); +} + +export interface GetGasUsageArgs { + messenger: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getGasUsage(tx: Transaction, args: GetGasUsageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wh_messenger_interface::get_gas_usage`, + arguments: [obj(tx, args.messenger), pure(tx, args.chainId, `u8`)], + }); +} + +export function getOtherChainIds(tx: Transaction, messenger: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wh_messenger_interface::get_other_chain_ids`, + arguments: [obj(tx, messenger)], + }); +} + +export interface GetTransactionCostArgs { + messenger: TransactionObjectInput; + wormholeState: TransactionObjectInput; + gasOracle: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getTransactionCost(tx: Transaction, args: GetTransactionCostArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wh_messenger_interface::get_transaction_cost`, + arguments: [ + obj(tx, args.messenger), + obj(tx, args.wormholeState), + obj(tx, args.gasOracle), + pure(tx, args.chainId, `u8`), + ], + }); +} + +export interface InitEmitterArgs { + adminCap: TransactionObjectInput; + whMessenger: TransactionObjectInput; + wormholeState: TransactionObjectInput; +} + +export function initEmitter(tx: Transaction, args: InitEmitterArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wh_messenger_interface::init_emitter`, + arguments: [obj(tx, args.adminCap), obj(tx, args.whMessenger), obj(tx, args.wormholeState)], + }); +} + +export interface ReceiveMessageArgs { + whMessenger: TransactionObjectInput; + encodedMsg: Array | TransactionArgument; + wormholeState: TransactionObjectInput; + theClock: TransactionObjectInput; +} + +export function receiveMessage(tx: Transaction, args: ReceiveMessageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wh_messenger_interface::receive_message`, + arguments: [ + obj(tx, args.whMessenger), + pure(tx, args.encodedMsg, `vector`), + obj(tx, args.wormholeState), + obj(tx, args.theClock), + ], + }); +} + +export interface RegisterWormholeMessengerArgs { + adminCap: TransactionObjectInput; + whMessenger: TransactionObjectInput; + chainId: number | TransactionArgument; + whAddress: TransactionObjectInput; +} + +export function registerWormholeMessenger(tx: Transaction, args: RegisterWormholeMessengerArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wh_messenger_interface::register_wormhole_messenger`, + arguments: [ + obj(tx, args.adminCap), + obj(tx, args.whMessenger), + pure(tx, args.chainId, `u16`), + obj(tx, args.whAddress), + ], + }); +} + +export interface SendMessageArgs { + whMessenger: TransactionObjectInput; + wormholeState: TransactionObjectInput; + gasOracle: TransactionObjectInput; + payload: TransactionObjectInput; + sender: TransactionObjectInput; + theClock: TransactionObjectInput; + coin: TransactionObjectInput; +} + +export function sendMessage(tx: Transaction, args: SendMessageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wh_messenger_interface::send_message`, + arguments: [ + obj(tx, args.whMessenger), + obj(tx, args.wormholeState), + obj(tx, args.gasOracle), + obj(tx, args.payload), + obj(tx, args.sender), + obj(tx, args.theClock), + obj(tx, args.coin), + ], + }); +} + +export interface SetGasUsageArgs { + adminCap: TransactionObjectInput; + whMessenger: TransactionObjectInput; + chainId: number | TransactionArgument; + gasAmount: bigint | TransactionArgument; +} + +export function setGasUsage(tx: Transaction, args: SetGasUsageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wh_messenger_interface::set_gas_usage`, + arguments: [ + obj(tx, args.adminCap), + obj(tx, args.whMessenger), + pure(tx, args.chainId, `u8`), + pure(tx, args.gasAmount, `u64`), + ], + }); +} + +export interface SetOtherChainsArgs { + adminCap: TransactionObjectInput; + whMessenger: TransactionObjectInput; + otherChainIds: Array | TransactionArgument; +} + +export function setOtherChains(tx: Transaction, args: SetOtherChainsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wh_messenger_interface::set_other_chains`, + arguments: [obj(tx, args.adminCap), obj(tx, args.whMessenger), pure(tx, args.otherChainIds, `vector`)], + }); +} + +export interface UnregisterWormholeMessengerArgs { + adminCap: TransactionObjectInput; + whMessenger: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function unregisterWormholeMessenger(tx: Transaction, args: UnregisterWormholeMessengerArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wh_messenger_interface::unregister_wormhole_messenger`, + arguments: [obj(tx, args.adminCap), obj(tx, args.whMessenger), pure(tx, args.chainId, `u16`)], + }); +} + +export interface WithdrawFeeArgs { + adminCap: TransactionObjectInput; + whMessenger: TransactionObjectInput; + amount: bigint | TransactionArgument; +} + +export function withdrawFee(tx: Transaction, args: WithdrawFeeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wh_messenger_interface::withdraw_fee`, + arguments: [obj(tx, args.adminCap), obj(tx, args.whMessenger), pure(tx, args.amount, `u64`)], + }); +} + +export interface HasReceivedMessageArgs { + messenger: TransactionObjectInput; + message: TransactionObjectInput; +} + +export function hasReceivedMessage(tx: Transaction, args: HasReceivedMessageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wh_messenger_interface::has_received_message`, + arguments: [obj(tx, args.messenger), obj(tx, args.message)], + }); +} + +export interface HasSentMessagesArgs { + messenger: TransactionObjectInput; + message: TransactionObjectInput; +} + +export function hasSentMessages(tx: Transaction, args: HasSentMessagesArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wh_messenger_interface::has_sent_messages`, + arguments: [obj(tx, args.messenger), obj(tx, args.message)], + }); +} diff --git a/src/services/models/sui/wormhole-messenger/wormhole-messenger/functions.ts b/src/services/models/sui/wormhole-messenger/wormhole-messenger/functions.ts new file mode 100644 index 00000000..a774466b --- /dev/null +++ b/src/services/models/sui/wormhole-messenger/wormhole-messenger/functions.ts @@ -0,0 +1,237 @@ +// @ts-nocheck +import { PUBLISHED_AT } from ".."; +import { obj, pure } from "../../_framework/util"; +import { Transaction, TransactionArgument, TransactionObjectInput } from "@mysten/sui/transactions"; + +export function getId(tx: Transaction, messenger: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::get_id`, + arguments: [obj(tx, messenger)], + }); +} + +export function getVersion(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::get_version`, + arguments: [], + }); +} + +export function init(tx: Transaction) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::init`, + arguments: [], + }); +} + +export interface MigrateArgs { + adminCap: TransactionObjectInput; + wormholeMessenger: TransactionObjectInput; +} + +export function migrate(tx: Transaction, args: MigrateArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::migrate`, + arguments: [obj(tx, args.adminCap), obj(tx, args.wormholeMessenger)], + }); +} + +export function gasBalanceValue(tx: Transaction, messenger: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::gas_balance_value`, + arguments: [obj(tx, messenger)], + }); +} + +export function getGasUsage(tx: Transaction, messenger: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::get_gas_usage`, + arguments: [obj(tx, messenger)], + }); +} + +export function getOtherChainIds(tx: Transaction, messenger: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::get_other_chain_ids`, + arguments: [obj(tx, messenger)], + }); +} + +export function getOtherWormholeMessengers(tx: Transaction, messenger: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::get_other_wormhole_messengers`, + arguments: [obj(tx, messenger)], + }); +} + +export function getReceivedMessages(tx: Transaction, messenger: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::get_received_messages`, + arguments: [obj(tx, messenger)], + }); +} + +export function getSentMessages(tx: Transaction, messenger: TransactionObjectInput) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::get_sent_messages`, + arguments: [obj(tx, messenger)], + }); +} + +export interface GetTransactionCostArgs { + messenger: TransactionObjectInput; + wormholeState: TransactionObjectInput; + gasOracle: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function getTransactionCost(tx: Transaction, args: GetTransactionCostArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::get_transaction_cost`, + arguments: [ + obj(tx, args.messenger), + obj(tx, args.wormholeState), + obj(tx, args.gasOracle), + pure(tx, args.chainId, `u8`), + ], + }); +} + +export interface InitEmitterArgs { + whMessenger: TransactionObjectInput; + wormholeState: TransactionObjectInput; +} + +export function initEmitter(tx: Transaction, args: InitEmitterArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::init_emitter`, + arguments: [obj(tx, args.whMessenger), obj(tx, args.wormholeState)], + }); +} + +export interface ReceiveMessageArgs { + whMessenger: TransactionObjectInput; + encodedMsg: Array | TransactionArgument; + wormholeState: TransactionObjectInput; + theClock: TransactionObjectInput; +} + +export function receiveMessage(tx: Transaction, args: ReceiveMessageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::receive_message`, + arguments: [ + obj(tx, args.whMessenger), + pure(tx, args.encodedMsg, `vector`), + obj(tx, args.wormholeState), + obj(tx, args.theClock), + ], + }); +} + +export interface ReceiveMessageInnerArgs { + whMessenger: TransactionObjectInput; + sequence: bigint | TransactionArgument; + emitterChainId: number | TransactionArgument; + emitterAddress: TransactionObjectInput; + payload: TransactionObjectInput; +} + +export function receiveMessageInner(tx: Transaction, args: ReceiveMessageInnerArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::receive_message_inner`, + arguments: [ + obj(tx, args.whMessenger), + pure(tx, args.sequence, `u64`), + pure(tx, args.emitterChainId, `u16`), + obj(tx, args.emitterAddress), + obj(tx, args.payload), + ], + }); +} + +export interface RegisterWormholeMessengerArgs { + whMessenger: TransactionObjectInput; + chainId: number | TransactionArgument; + whAddress: TransactionObjectInput; +} + +export function registerWormholeMessenger(tx: Transaction, args: RegisterWormholeMessengerArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::register_wormhole_messenger`, + arguments: [obj(tx, args.whMessenger), pure(tx, args.chainId, `u16`), obj(tx, args.whAddress)], + }); +} + +export interface SendMessageArgs { + whMessenger: TransactionObjectInput; + wormholeState: TransactionObjectInput; + gasOracle: TransactionObjectInput; + payload: TransactionObjectInput; + sender: TransactionObjectInput; + theClock: TransactionObjectInput; + coin: TransactionObjectInput; +} + +export function sendMessage(tx: Transaction, args: SendMessageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::send_message`, + arguments: [ + obj(tx, args.whMessenger), + obj(tx, args.wormholeState), + obj(tx, args.gasOracle), + obj(tx, args.payload), + obj(tx, args.sender), + obj(tx, args.theClock), + obj(tx, args.coin), + ], + }); +} + +export interface SetGasUsageArgs { + whMessenger: TransactionObjectInput; + chainId: number | TransactionArgument; + gasAmount: bigint | TransactionArgument; +} + +export function setGasUsage(tx: Transaction, args: SetGasUsageArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::set_gas_usage`, + arguments: [obj(tx, args.whMessenger), pure(tx, args.chainId, `u8`), pure(tx, args.gasAmount, `u64`)], + }); +} + +export interface SetOtherChainsArgs { + whMessenger: TransactionObjectInput; + otherChainIds: Array | TransactionArgument; +} + +export function setOtherChains(tx: Transaction, args: SetOtherChainsArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::set_other_chains`, + arguments: [obj(tx, args.whMessenger), pure(tx, args.otherChainIds, `vector`)], + }); +} + +export interface UnregisterWormholeMessengerArgs { + whMessenger: TransactionObjectInput; + chainId: number | TransactionArgument; +} + +export function unregisterWormholeMessenger(tx: Transaction, args: UnregisterWormholeMessengerArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::unregister_wormhole_messenger`, + arguments: [obj(tx, args.whMessenger), pure(tx, args.chainId, `u16`)], + }); +} + +export interface WithdrawFeeArgs { + whMessenger: TransactionObjectInput; + amount: bigint | TransactionArgument; +} + +export function withdrawFee(tx: Transaction, args: WithdrawFeeArgs) { + return tx.moveCall({ + target: `${PUBLISHED_AT}::wormhole_messenger::withdraw_fee`, + arguments: [obj(tx, args.whMessenger), pure(tx, args.amount, `u64`)], + }); +} diff --git a/src/services/models/sui/wormhole-messenger/wormhole-messenger/structs.ts b/src/services/models/sui/wormhole-messenger/wormhole-messenger/structs.ts new file mode 100644 index 00000000..e43c248c --- /dev/null +++ b/src/services/models/sui/wormhole-messenger/wormhole-messenger/structs.ts @@ -0,0 +1,430 @@ +// @ts-nocheck +import * as reified from "../../_framework/reified"; +import { Option } from "../../_dependencies/source/0x1/option/structs"; +import { EmitterCap } from "../../_dependencies/source/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/emitter/structs"; +import { + PhantomReified, + Reified, + StructClass, + ToField, + ToTypeStr, + decodeFromFields, + decodeFromFieldsWithTypes, + decodeFromJSONField, + fieldToJSON, + phantom, + ToTypeStr as ToPhantom, +} from "../../_framework/reified"; +import { FieldsWithTypes, composeSuiType, compressSuiType } from "../../_framework/util"; +import { Vector } from "../../_framework/vector"; +import { Balance } from "../../sui/balance/structs"; +import { UID } from "../../sui/object/structs"; +import { SUI } from "../../sui/sui/structs"; +import { Table } from "../../sui/table/structs"; +import { Bytes32 } from "../../utils/bytes32/structs"; +import { Message } from "../../utils/message/structs"; +import { Set } from "../../utils/set/structs"; +import { PKG_V1 } from "../index"; +import { bcs } from "@mysten/sui/bcs"; +import { SuiClient, SuiObjectData, SuiParsedData } from "@mysten/sui/client"; +import { fromB64 } from "@mysten/sui/utils"; + +/* ============================== AdminCap =============================== */ + +export function isAdminCap(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::wormhole_messenger::AdminCap`; +} + +export interface AdminCapFields { + id: ToField; +} + +export type AdminCapReified = Reified; + +export class AdminCap implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::wormhole_messenger::AdminCap`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = AdminCap.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = AdminCap.$isPhantom; + + readonly id: ToField; + + private constructor(typeArgs: [], fields: AdminCapFields) { + this.$fullTypeName = composeSuiType(AdminCap.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + } + + static reified(): AdminCapReified { + return { + typeName: AdminCap.$typeName, + fullTypeName: composeSuiType(AdminCap.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: AdminCap.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => AdminCap.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => AdminCap.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => AdminCap.fromBcs(data), + bcs: AdminCap.bcs, + fromJSONField: (field: any) => AdminCap.fromJSONField(field), + fromJSON: (json: Record) => AdminCap.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => AdminCap.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => AdminCap.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => AdminCap.fetch(client, id), + new: (fields: AdminCapFields) => { + return new AdminCap([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return AdminCap.reified(); + } + + static phantom(): PhantomReified> { + return phantom(AdminCap.reified()); + } + static get p() { + return AdminCap.phantom(); + } + + static get bcs() { + return bcs.struct("AdminCap", { + id: UID.bcs, + }); + } + + static fromFields(fields: Record): AdminCap { + return AdminCap.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): AdminCap { + if (!isAdminCap(item.type)) { + throw new Error("not a AdminCap type"); + } + + return AdminCap.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + }); + } + + static fromBcs(data: Uint8Array): AdminCap { + return AdminCap.fromFields(AdminCap.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): AdminCap { + return AdminCap.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + }); + } + + static fromJSON(json: Record): AdminCap { + if (json.$typeName !== AdminCap.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return AdminCap.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): AdminCap { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isAdminCap(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a AdminCap object`); + } + return AdminCap.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): AdminCap { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isAdminCap(data.bcs.type)) { + throw new Error(`object at is not a AdminCap object`); + } + + return AdminCap.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return AdminCap.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching AdminCap object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isAdminCap(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a AdminCap object`); + } + + return AdminCap.fromSuiObjectData(res.data); + } +} + +/* ============================== WormholeMessenger =============================== */ + +export function isWormholeMessenger(type: string): boolean { + type = compressSuiType(type); + return type === `${PKG_V1}::wormhole_messenger::WormholeMessenger`; +} + +export interface WormholeMessengerFields { + id: ToField; + emitterCap: ToField>; + receivedMessages: ToField>>; + sentMessages: ToField>>; + otherWormholeMessengers: ToField>>; + otherChainIds: ToField>; + gasUsage: ToField>; + gasBalance: ToField>>; +} + +export type WormholeMessengerReified = Reified; + +export class WormholeMessenger implements StructClass { + __StructClass = true as const; + + static get $typeName() { + return `${PKG_V1}::wormhole_messenger::WormholeMessenger`; + } + static readonly $numTypeParams = 0; + static readonly $isPhantom = [] as const; + + readonly $typeName = WormholeMessenger.$typeName; + readonly $fullTypeName: string; + readonly $typeArgs: []; + readonly $isPhantom = WormholeMessenger.$isPhantom; + + readonly id: ToField; + readonly emitterCap: ToField>; + readonly receivedMessages: ToField>>; + readonly sentMessages: ToField>>; + readonly otherWormholeMessengers: ToField>>; + readonly otherChainIds: ToField>; + readonly gasUsage: ToField>; + readonly gasBalance: ToField>>; + + private constructor(typeArgs: [], fields: WormholeMessengerFields) { + this.$fullTypeName = composeSuiType(WormholeMessenger.$typeName, ...typeArgs) as string; + this.$typeArgs = typeArgs; + + this.id = fields.id; + this.emitterCap = fields.emitterCap; + this.receivedMessages = fields.receivedMessages; + this.sentMessages = fields.sentMessages; + this.otherWormholeMessengers = fields.otherWormholeMessengers; + this.otherChainIds = fields.otherChainIds; + this.gasUsage = fields.gasUsage; + this.gasBalance = fields.gasBalance; + } + + static reified(): WormholeMessengerReified { + return { + typeName: WormholeMessenger.$typeName, + fullTypeName: composeSuiType(WormholeMessenger.$typeName, ...[]) as string, + typeArgs: [] as [], + isPhantom: WormholeMessenger.$isPhantom, + reifiedTypeArgs: [], + fromFields: (fields: Record) => WormholeMessenger.fromFields(fields), + fromFieldsWithTypes: (item: FieldsWithTypes) => WormholeMessenger.fromFieldsWithTypes(item), + fromBcs: (data: Uint8Array) => WormholeMessenger.fromBcs(data), + bcs: WormholeMessenger.bcs, + fromJSONField: (field: any) => WormholeMessenger.fromJSONField(field), + fromJSON: (json: Record) => WormholeMessenger.fromJSON(json), + fromSuiParsedData: (content: SuiParsedData) => WormholeMessenger.fromSuiParsedData(content), + fromSuiObjectData: (content: SuiObjectData) => WormholeMessenger.fromSuiObjectData(content), + fetch: async (client: SuiClient, id: string) => WormholeMessenger.fetch(client, id), + new: (fields: WormholeMessengerFields) => { + return new WormholeMessenger([], fields); + }, + kind: "StructClassReified", + }; + } + + static get r() { + return WormholeMessenger.reified(); + } + + static phantom(): PhantomReified> { + return phantom(WormholeMessenger.reified()); + } + static get p() { + return WormholeMessenger.phantom(); + } + + static get bcs() { + return bcs.struct("WormholeMessenger", { + id: UID.bcs, + emitter_cap: Option.bcs(EmitterCap.bcs), + received_messages: Set.bcs, + sent_messages: Set.bcs, + other_wormhole_messengers: Table.bcs, + other_chain_ids: bcs.vector(bcs.bool()), + gas_usage: Table.bcs, + gas_balance: Balance.bcs, + }); + } + + static fromFields(fields: Record): WormholeMessenger { + return WormholeMessenger.reified().new({ + id: decodeFromFields(UID.reified(), fields.id), + emitterCap: decodeFromFields(Option.reified(EmitterCap.reified()), fields.emitter_cap), + receivedMessages: decodeFromFields(Set.reified(reified.phantom(Message.reified())), fields.received_messages), + sentMessages: decodeFromFields(Set.reified(reified.phantom(Message.reified())), fields.sent_messages), + otherWormholeMessengers: decodeFromFields( + Table.reified(reified.phantom("u16"), reified.phantom(Bytes32.reified())), + fields.other_wormhole_messengers + ), + otherChainIds: decodeFromFields(reified.vector("bool"), fields.other_chain_ids), + gasUsage: decodeFromFields(Table.reified(reified.phantom("u8"), reified.phantom("u64")), fields.gas_usage), + gasBalance: decodeFromFields(Balance.reified(reified.phantom(SUI.reified())), fields.gas_balance), + }); + } + + static fromFieldsWithTypes(item: FieldsWithTypes): WormholeMessenger { + if (!isWormholeMessenger(item.type)) { + throw new Error("not a WormholeMessenger type"); + } + + return WormholeMessenger.reified().new({ + id: decodeFromFieldsWithTypes(UID.reified(), item.fields.id), + emitterCap: decodeFromFieldsWithTypes(Option.reified(EmitterCap.reified()), item.fields.emitter_cap), + receivedMessages: decodeFromFieldsWithTypes( + Set.reified(reified.phantom(Message.reified())), + item.fields.received_messages + ), + sentMessages: decodeFromFieldsWithTypes( + Set.reified(reified.phantom(Message.reified())), + item.fields.sent_messages + ), + otherWormholeMessengers: decodeFromFieldsWithTypes( + Table.reified(reified.phantom("u16"), reified.phantom(Bytes32.reified())), + item.fields.other_wormhole_messengers + ), + otherChainIds: decodeFromFieldsWithTypes(reified.vector("bool"), item.fields.other_chain_ids), + gasUsage: decodeFromFieldsWithTypes( + Table.reified(reified.phantom("u8"), reified.phantom("u64")), + item.fields.gas_usage + ), + gasBalance: decodeFromFieldsWithTypes(Balance.reified(reified.phantom(SUI.reified())), item.fields.gas_balance), + }); + } + + static fromBcs(data: Uint8Array): WormholeMessenger { + return WormholeMessenger.fromFields(WormholeMessenger.bcs.parse(data)); + } + + toJSONField() { + return { + id: this.id, + emitterCap: fieldToJSON>(`${Option.$typeName}<${EmitterCap.$typeName}>`, this.emitterCap), + receivedMessages: this.receivedMessages.toJSONField(), + sentMessages: this.sentMessages.toJSONField(), + otherWormholeMessengers: this.otherWormholeMessengers.toJSONField(), + otherChainIds: fieldToJSON>(`vector`, this.otherChainIds), + gasUsage: this.gasUsage.toJSONField(), + gasBalance: this.gasBalance.toJSONField(), + }; + } + + toJSON() { + return { + $typeName: this.$typeName, + $typeArgs: this.$typeArgs, + ...this.toJSONField(), + }; + } + + static fromJSONField(field: any): WormholeMessenger { + return WormholeMessenger.reified().new({ + id: decodeFromJSONField(UID.reified(), field.id), + emitterCap: decodeFromJSONField(Option.reified(EmitterCap.reified()), field.emitterCap), + receivedMessages: decodeFromJSONField(Set.reified(reified.phantom(Message.reified())), field.receivedMessages), + sentMessages: decodeFromJSONField(Set.reified(reified.phantom(Message.reified())), field.sentMessages), + otherWormholeMessengers: decodeFromJSONField( + Table.reified(reified.phantom("u16"), reified.phantom(Bytes32.reified())), + field.otherWormholeMessengers + ), + otherChainIds: decodeFromJSONField(reified.vector("bool"), field.otherChainIds), + gasUsage: decodeFromJSONField(Table.reified(reified.phantom("u8"), reified.phantom("u64")), field.gasUsage), + gasBalance: decodeFromJSONField(Balance.reified(reified.phantom(SUI.reified())), field.gasBalance), + }); + } + + static fromJSON(json: Record): WormholeMessenger { + if (json.$typeName !== WormholeMessenger.$typeName) { + throw new Error("not a WithTwoGenerics json object"); + } + + return WormholeMessenger.fromJSONField(json); + } + + static fromSuiParsedData(content: SuiParsedData): WormholeMessenger { + if (content.dataType !== "moveObject") { + throw new Error("not an object"); + } + if (!isWormholeMessenger(content.type)) { + throw new Error(`object at ${(content.fields as any).id} is not a WormholeMessenger object`); + } + return WormholeMessenger.fromFieldsWithTypes(content); + } + + static fromSuiObjectData(data: SuiObjectData): WormholeMessenger { + if (data.bcs) { + if (data.bcs.dataType !== "moveObject" || !isWormholeMessenger(data.bcs.type)) { + throw new Error(`object at is not a WormholeMessenger object`); + } + + return WormholeMessenger.fromBcs(fromB64(data.bcs.bcsBytes)); + } + if (data.content) { + return WormholeMessenger.fromSuiParsedData(data.content); + } + throw new Error( + "Both `bcs` and `content` fields are missing from the data. Include `showBcs` or `showContent` in the request." + ); + } + + static async fetch(client: SuiClient, id: string): Promise { + const res = await client.getObject({ id, options: { showBcs: true } }); + if (res.error) { + throw new Error(`error fetching WormholeMessenger object at id ${id}: ${res.error.code}`); + } + if (res.data?.bcs?.dataType !== "moveObject" || !isWormholeMessenger(res.data.bcs.type)) { + throw new Error(`object at id ${id} is not a WormholeMessenger object`); + } + + return WormholeMessenger.fromSuiObjectData(res.data); + } +} diff --git a/src/services/token/evm/index.ts b/src/services/token/evm/index.ts index 747ae2e6..a8f34ce2 100644 --- a/src/services/token/evm/index.ts +++ b/src/services/token/evm/index.ts @@ -19,7 +19,7 @@ export class EvmTokenService extends ChainTokenService { constructor( public web3: EssentialWeb3, - public api: AllbridgeCoreClient, + public api: AllbridgeCoreClient ) { super(); } @@ -69,7 +69,7 @@ export class EvmTokenService extends ChainTokenService { const approveMethod = tokenContract.methods.approve( spender, - amount == undefined ? MAX_AMOUNT : amountToHex(amount), + amount == undefined ? MAX_AMOUNT : amountToHex(amount) ); return Promise.resolve({ diff --git a/src/services/token/index.ts b/src/services/token/index.ts index 5d75d24b..4d2fa6df 100644 --- a/src/services/token/index.ts +++ b/src/services/token/index.ts @@ -22,6 +22,7 @@ import { } from "./models"; import { SolanaTokenService } from "./sol"; import { SrbTokenService } from "./srb"; +import { SuiTokenService } from "./sui"; import { TronTokenService } from "./trx"; export interface TokenService { @@ -42,12 +43,12 @@ export class DefaultTokenService implements TokenService { constructor( readonly api: AllbridgeCoreClient, readonly nodeRpcUrlsConfig: NodeRpcUrlsConfig, - readonly params: AllbridgeCoreSdkOptions, + readonly params: AllbridgeCoreSdkOptions ) {} async getAllowance(params: GetAllowanceParams, provider?: Provider): Promise { const allowanceInt = await this.getChainTokenService(params.token.chainSymbol, params.owner, provider).getAllowance( - params, + params ); return convertIntAmountToFloat(allowanceInt, params.token.decimals).toFixed(); } @@ -56,7 +57,7 @@ export class DefaultTokenService implements TokenService { validateAmountGtZero(params.amount); validateAmountDecimals("amount", params.amount, params.token.decimals); return this.getChainTokenService(params.token.chainSymbol, params.owner, provider).checkAllowance( - this.prepareCheckAllowanceParams(params), + this.prepareCheckAllowanceParams(params) ); } @@ -66,7 +67,7 @@ export class DefaultTokenService implements TokenService { validateAmountDecimals("amount", approveData.amount, approveData.token.decimals); } return this.getChainTokenService(approveData.token.chainSymbol, approveData.owner, provider).approve( - this.prepareApproveParams(approveData), + this.prepareApproveParams(approveData) ); } @@ -78,7 +79,7 @@ export class DefaultTokenService implements TokenService { return this.getChainTokenService( approveData.token.chainSymbol, approveData.owner, - provider, + provider ).buildRawTransactionApprove(this.prepareApproveParams(approveData)); } @@ -86,7 +87,7 @@ export class DefaultTokenService implements TokenService { const tokenBalance = await this.getChainTokenService( params.token.chainSymbol, params.account, - provider, + provider ).getTokenBalance(params); if (params.token.decimals) { return convertIntAmountToFloat(tokenBalance, params.token.decimals).toFixed(); @@ -98,13 +99,13 @@ export class DefaultTokenService implements TokenService { const tokenBalance = await this.getChainTokenService( params.chainSymbol, params.account, - provider, + provider ).getNativeTokenBalance(params); return { [AmountFormat.INT]: tokenBalance, [AmountFormat.FLOAT]: convertIntAmountToFloat( tokenBalance, - Chains.getChainDecimalsByType(Chains.getChainProperty(params.chainSymbol).chainType), + Chains.getChainDecimalsByType(Chains.getChainProperty(params.chainSymbol).chainType) ).toFixed(), }; } @@ -136,6 +137,9 @@ export class DefaultTokenService implements TokenService { case ChainType.SRB: { return new SrbTokenService(this.nodeRpcUrlsConfig, this.params, this.api); } + case ChainType.SUI: { + return new SuiTokenService(this.nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol), this.api); + } } } diff --git a/src/services/token/sol/index.ts b/src/services/token/sol/index.ts index 07411f91..246a0752 100644 --- a/src/services/token/sol/index.ts +++ b/src/services/token/sol/index.ts @@ -16,7 +16,7 @@ export class SolanaTokenService extends ChainTokenService { constructor( public solanaRpcUrl: string, - public api: AllbridgeCoreClient, + public api: AllbridgeCoreClient ) { super(); } @@ -41,7 +41,7 @@ export class SolanaTokenService extends ChainTokenService { { preflightCommitment: "confirmed", commitment: "confirmed", - }, + } ); } diff --git a/src/services/token/srb/index.ts b/src/services/token/srb/index.ts index 6c219fb8..1b7b3ce2 100644 --- a/src/services/token/srb/index.ts +++ b/src/services/token/srb/index.ts @@ -19,7 +19,7 @@ export class SrbTokenService extends ChainTokenService { constructor( readonly nodeRpcUrlsConfig: NodeRpcUrlsConfig, readonly params: AllbridgeCoreSdkOptions, - readonly api: AllbridgeCoreClient, + readonly api: AllbridgeCoreClient ) { super(); } @@ -50,12 +50,12 @@ export class SrbTokenService extends ChainTokenService { (balance): balance is BalanceLineAsset => (balance.asset_type === "credit_alphanum4" || balance.asset_type === "credit_alphanum12") && balance.asset_code == symbol && - balance.asset_issuer == srbTokenAddress, + balance.asset_issuer == srbTokenAddress ); if (balanceInfo?.balance) { return convertFloatAmountToInt( balanceInfo.balance, - Chains.getChainDecimalsByType(Chains.getChainProperty(params.token.chainSymbol).chainType), + Chains.getChainDecimalsByType(Chains.getChainProperty(params.token.chainSymbol).chainType) ).toFixed(); } return "0"; @@ -70,7 +70,7 @@ export class SrbTokenService extends ChainTokenService { if (nativeBalance?.balance) { return convertFloatAmountToInt( nativeBalance.balance, - Chains.getChainDecimalsByType(Chains.getChainProperty(params.chainSymbol).chainType), + Chains.getChainDecimalsByType(Chains.getChainProperty(params.chainSymbol).chainType) ).toFixed(); } return "0"; diff --git a/src/services/token/sui/index.ts b/src/services/token/sui/index.ts new file mode 100644 index 00000000..1c503371 --- /dev/null +++ b/src/services/token/sui/index.ts @@ -0,0 +1,61 @@ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { SuiClient } from "@mysten/sui/client"; +import { CoinStruct } from "@mysten/sui/src/client/types/generated"; +import { ChainType } from "../../../chains/chain.enums"; +import { AllbridgeCoreClient } from "../../../client/core-api/core-client-base"; +import { MethodNotSupportedError, SdkError } from "../../../exceptions"; +import { GetNativeTokenBalanceParams } from "../../bridge/models"; +import { RawTransaction, TransactionResponse } from "../../models"; +import { fetchAllPagesRecursive } from "../../utils/sui/paginated"; +import { ApproveParamsDto, ChainTokenService, GetAllowanceParamsDto, GetTokenBalanceParams } from "../models"; + +export class SuiTokenService extends ChainTokenService { + chainType: ChainType.SUI = ChainType.SUI; + private suiClient: SuiClient; + + constructor( + public suiRpcUrl: string, + public api: AllbridgeCoreClient + ) { + super(); + this.suiClient = new SuiClient({ + url: this.suiRpcUrl, + }); + } + + approve(params: ApproveParamsDto): Promise { + throw new MethodNotSupportedError(); + } + + buildRawTransactionApprove(params: ApproveParamsDto): Promise { + throw new MethodNotSupportedError(); + } + + getAllowance(params: GetAllowanceParamsDto): Promise { + throw new MethodNotSupportedError(); + } + + async getTokenBalance(params: GetTokenBalanceParams): Promise { + if (!params.token.originTokenAddress) { + throw new SdkError("SUI token must contain 'originTokenAddress'"); + } + const balance = await this.suiClient.getBalance({ + owner: params.account, + coinType: params.token.originTokenAddress, + }); + return balance.totalBalance; + } + + async getNativeTokenBalance(params: GetNativeTokenBalanceParams): Promise { + const coinsData: CoinStruct[] = await fetchAllPagesRecursive((cursor: string | null | undefined) => + this.suiClient.getCoins({ + owner: params.account, + cursor, + }) + ); + if (coinsData.length === 0) { + return "0"; + } + return coinsData.reduce((total, element) => total + BigInt(element.balance), BigInt(0)).toString(); + } +} diff --git a/src/services/token/trx/index.ts b/src/services/token/trx/index.ts index f21f86f3..27cd692b 100644 --- a/src/services/token/trx/index.ts +++ b/src/services/token/trx/index.ts @@ -17,7 +17,7 @@ export class TronTokenService extends ChainTokenService { constructor( public tronWeb: TronWeb, - public api: AllbridgeCoreClient, + public api: AllbridgeCoreClient ) { super(); } @@ -69,7 +69,7 @@ export class TronTokenService extends ChainTokenService { methodSignature: string, parameters: SmartContractMethodParameter[], value: string, - fromAddress: string, + fromAddress: string ): Promise { const transactionObject = await this.tronWeb.transactionBuilder.triggerSmartContract( contractAddress, @@ -78,7 +78,7 @@ export class TronTokenService extends ChainTokenService { callValue: +value, }, parameters, - fromAddress, + fromAddress ); if (!transactionObject?.result?.result) { throw new SdkError("Unknown error: " + JSON.stringify(transactionObject, null, 2)); diff --git a/src/services/utils/calculation/index.ts b/src/services/utils/calculation/index.ts index a84caa24..01409e52 100644 --- a/src/services/utils/calculation/index.ts +++ b/src/services/utils/calculation/index.ts @@ -7,7 +7,7 @@ export function depositAmountToVUsd( aValue: string, dValue: string, tokenBalance: string, - vUsdBalance: string, + vUsdBalance: string ): string { const amountSP = convertFloatAmountToInt(amount, SYSTEM_PRECISION); const amountSPBig = Big(amountSP); diff --git a/src/services/utils/sol/accounts.ts b/src/services/utils/sol/accounts.ts index 2fe1dae7..43660228 100644 --- a/src/services/utils/sol/accounts.ts +++ b/src/services/utils/sol/accounts.ts @@ -16,7 +16,7 @@ export async function getConfigAccount(programId: PublicKey): Promise export async function getLockAccount(nonce: number[], bridgeProgramId: PublicKey): Promise { const [lockPda] = await PublicKey.findProgramAddress( [anchor.utils.bytes.utf8.encode("lock"), Uint8Array.from(nonce)], - bridgeProgramId, + bridgeProgramId ); return lockPda; } @@ -24,7 +24,7 @@ export async function getLockAccount(nonce: number[], bridgeProgramId: PublicKey export async function getPriceAccount(chainId: number, gasOracleProgramId: PublicKey): Promise { const [pricePda] = await PublicKey.findProgramAddress( [anchor.utils.bytes.utf8.encode("price_v2"), Uint8Array.from([chainId])], - gasOracleProgramId, + gasOracleProgramId ); return pricePda; } @@ -37,7 +37,7 @@ export async function getAuthorityAccount(bridgeProgramId: PublicKey): Promise

{ const [poolAuthority] = await PublicKey.findProgramAddress([cctpBridgeAccount.toBuffer()], cctpBridgeProgramId); return poolAuthority; @@ -46,7 +46,7 @@ export async function getCctpAuthorityAccount( export async function getBridgeTokenAccount(mintAccount: PublicKey, bridgeProgramId: PublicKey): Promise { const [poolPda] = await PublicKey.findProgramAddress( [anchor.utils.bytes.utf8.encode("token"), mintAccount.toBytes()], - bridgeProgramId, + bridgeProgramId ); return poolPda; } @@ -54,11 +54,11 @@ export async function getBridgeTokenAccount(mintAccount: PublicKey, bridgeProgra export async function getOtherChainTokenAccount( chainId: number, token: Buffer, - bridgeProgramId: PublicKey, + bridgeProgramId: PublicKey ): Promise { const [otherChainTokenPda] = await PublicKey.findProgramAddress( [anchor.utils.bytes.utf8.encode("other_bridge_token"), Buffer.from([chainId]), token], - bridgeProgramId, + bridgeProgramId ); return otherChainTokenPda; } @@ -66,7 +66,7 @@ export async function getOtherChainTokenAccount( export async function getChainBridgeAccount(chainId: number, bridgeProgramId: PublicKey): Promise { const [chainBridgePda] = await PublicKey.findProgramAddress( [anchor.utils.bytes.utf8.encode("chain_bridge"), Uint8Array.from([chainId])], - bridgeProgramId, + bridgeProgramId ); return chainBridgePda; } @@ -74,18 +74,18 @@ export async function getChainBridgeAccount(chainId: number, bridgeProgramId: Pu export async function getGasUsageAccount(chainId: number, messengerProgramId: PublicKey): Promise { const [chainBridgePda] = await PublicKey.findProgramAddress( [anchor.utils.bytes.utf8.encode("gas_usage"), Uint8Array.from([chainId])], - messengerProgramId, + messengerProgramId ); return chainBridgePda; } export async function getSendMessageAccount( messageWithSigner: Uint8Array, - messengerProgramId: PublicKey, + messengerProgramId: PublicKey ): Promise { const [sentMessagePda] = await PublicKey.findProgramAddress( [anchor.utils.bytes.utf8.encode("sent_message"), messageWithSigner], - messengerProgramId, + messengerProgramId ); return sentMessagePda; } @@ -93,11 +93,11 @@ export async function getSendMessageAccount( export async function getUserDepositAccount( userPublicKey: PublicKey, tokenMintAccount: PublicKey, - bridgeProgramId: PublicKey, + bridgeProgramId: PublicKey ): Promise { const [userDepositPda] = await PublicKey.findProgramAddress( [anchor.utils.bytes.utf8.encode("user_deposit"), tokenMintAccount.toBytes(), userPublicKey.toBytes()], - bridgeProgramId, + bridgeProgramId ); return userDepositPda; } @@ -105,7 +105,7 @@ export async function getUserDepositAccount( export async function getCctpBridgeAccount(mintAccount: PublicKey, cctpBridgeProgramId: PublicKey): Promise { const [configPda] = await PublicKey.findProgramAddress( [anchor.utils.bytes.utf8.encode("cctp_bridge"), mintAccount.toBytes()], - cctpBridgeProgramId, + cctpBridgeProgramId ); return configPda; } @@ -113,7 +113,7 @@ export async function getCctpBridgeAccount(mintAccount: PublicKey, cctpBridgePro export async function getCctpBridgeTokenAccount(token: PublicKey, cctpBridgeProgramId: PublicKey): Promise { const [poolPda] = await PublicKey.findProgramAddress( [anchor.utils.bytes.utf8.encode("token"), token.toBytes()], - cctpBridgeProgramId, + cctpBridgeProgramId ); return poolPda; } @@ -121,7 +121,7 @@ export async function getCctpBridgeTokenAccount(token: PublicKey, cctpBridgeProg export function getCctpLockAccount(cctpBridgeProgramId: PublicKey, messageSentEventDataAccount: PublicKey): PublicKey { const [tokenMessengerEventAuthority] = PublicKey.findProgramAddressSync( [anchor.utils.bytes.utf8.encode("lock"), messageSentEventDataAccount.toBuffer()], - cctpBridgeProgramId, + cctpBridgeProgramId ); return tokenMessengerEventAuthority; } @@ -130,7 +130,7 @@ export function getCctpAccounts( domain: number, mintAccount: PublicKey, cctpTransmitterProgramId: PublicKey, - cctpTokenMessengerMinter: PublicKey, + cctpTokenMessengerMinter: PublicKey ) { const messageTransmitterAccount = findProgramAddress("message_transmitter", cctpTransmitterProgramId); const tokenMessenger = findProgramAddress("token_messenger", cctpTokenMessengerMinter); @@ -155,7 +155,7 @@ export function getCctpAccounts( function findProgramAddress( label: string, programId: PublicKey, - extraSeeds: (string | number[] | Buffer | PublicKey)[] = [], + extraSeeds: (string | number[] | Buffer | PublicKey)[] = [] ): PublicKey { const seeds = [Buffer.from(anchor.utils.bytes.utf8.encode(label))]; for (const extraSeed of extraSeeds) { diff --git a/src/services/utils/sol/anchor-provider.ts b/src/services/utils/sol/anchor-provider.ts index 7f56bfa2..887aa70b 100644 --- a/src/services/utils/sol/anchor-provider.ts +++ b/src/services/utils/sol/anchor-provider.ts @@ -13,6 +13,6 @@ export function buildAnchorProvider(solanaRpcUrl: string, accountAddress: string { preflightCommitment: "confirmed", commitment: "confirmed", - }, + } ); } diff --git a/src/services/utils/sol/compute-budget.ts b/src/services/utils/sol/compute-budget.ts index 84fe3955..08f23396 100644 --- a/src/services/utils/sol/compute-budget.ts +++ b/src/services/utils/sol/compute-budget.ts @@ -16,7 +16,7 @@ import { SolanaAutoTxFee, TxFeeParams } from "../../models"; export async function addUnitLimitAndUnitPriceToTx( transaction: Transaction, txFeeParams: TxFeeParams | undefined, - solanaRpcUrl: string, + solanaRpcUrl: string ) { const connection = new Connection(solanaRpcUrl, "confirmed"); /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */ @@ -27,7 +27,7 @@ export async function addUnitLimitAndUnitPriceToTx( export async function addUnitLimitAndUnitPriceToVersionedTx( transaction: VersionedTransaction, txFeeParams: TxFeeParams | undefined, - solanaRpcUrl: string, + solanaRpcUrl: string ) { const connection = new Connection(solanaRpcUrl, "confirmed"); const addressLookupTableAccounts = await fetchAddressLookupTableAccountsFromTx(transaction, connection); @@ -52,7 +52,7 @@ async function addUnitLimitAndUnitPriceToInstructions( instructions: TransactionInstruction[], simUnitsConsumed: number, txFeeParams: TxFeeParams | undefined, - connection: Connection, + connection: Connection ) { if (simUnitsConsumed > 0) { const units = updateUnitLimit(simUnitsConsumed, instructions); @@ -77,7 +77,7 @@ function updateUnitLimit(simUnitsConsumed: number, instructions: TransactionInst const computeUnitLimitIndex = instructions.findIndex( (instruction) => instruction.programId.equals(ComputeBudgetProgram.programId) && - ComputeBudgetInstruction.decodeInstructionType(instruction) === "SetComputeUnitLimit", + ComputeBudgetInstruction.decodeInstructionType(instruction) === "SetComputeUnitLimit" ); const units = Number((simUnitsConsumed * 1.3).toFixed(0)); const computeUnitLimitInstruction = ComputeBudgetProgram.setComputeUnitLimit({ @@ -94,12 +94,12 @@ function updateUnitLimit(simUnitsConsumed: number, instructions: TransactionInst async function updateUnitPrice( instructions: TransactionInstruction[], connection: Connection, - pricePerUnitInMicroLamports?: string, + pricePerUnitInMicroLamports?: string ): Promise { const computeUnitPriceIndex = instructions.findIndex( (instruction) => instruction.programId.equals(ComputeBudgetProgram.programId) && - ComputeBudgetInstruction.decodeInstructionType(instruction) === "SetComputeUnitPrice", + ComputeBudgetInstruction.decodeInstructionType(instruction) === "SetComputeUnitPrice" ); const unitPrice = pricePerUnitInMicroLamports ? BigInt(pricePerUnitInMicroLamports) diff --git a/src/services/utils/sol/index.ts b/src/services/utils/sol/index.ts index 9bcd0a65..162c6daf 100644 --- a/src/services/utils/sol/index.ts +++ b/src/services/utils/sol/index.ts @@ -16,7 +16,7 @@ export async function getTokenAccountData(account: PublicKey, provider: Provider export async function getVUsdAmount( amount: string, bridge: Program, - poolAccount: PublicKey, + poolAccount: PublicKey ): Promise { const poolAccountInfo = await bridge.account.pool.fetch(poolAccount); const decimals = poolAccountInfo.decimals; @@ -56,7 +56,7 @@ export function getMessage(args: { { t: "uint256", v: sourceChainId }, { t: "bytes32", v: receiveToken }, { t: "uint256", v: nonce }, - { t: "uint8", v: messenger }, + { t: "uint8", v: messenger } ); if (!message) { @@ -70,7 +70,7 @@ export function getMessage(args: { const messageWithSigner = Web3.utils.encodePacked( { t: "bytes32", v: "0x" + hashBuffer.toString("hex") }, - { t: "bytes32", v: chainBridge }, + { t: "bytes32", v: chainBridge } ); if (!messageWithSigner) { diff --git a/src/services/utils/sui/coins.ts b/src/services/utils/sui/coins.ts new file mode 100644 index 00000000..28209eaa --- /dev/null +++ b/src/services/utils/sui/coins.ts @@ -0,0 +1,43 @@ +import { CoinStruct } from "@mysten/sui/client"; +import { Transaction } from "@mysten/sui/transactions"; + +export function getCoinsWithAmounts(amounts: string[], coins: CoinStruct[], tx: Transaction) { + if (coins.length === 0 || !coins[0]) { + return []; + } + const firstCoin = coins[0]; + const requiredAmount = amounts.reduce((total, amount) => total + BigInt(amount), BigInt(0)); + + let currentBalance = BigInt(firstCoin.balance); + const accumulatedCoins: CoinStruct[] = []; + + for (const coin of coins.slice(1)) { + if (currentBalance > requiredAmount) { + return splitAndMergeCoins(tx, firstCoin, accumulatedCoins, amounts); + } else { + currentBalance += BigInt(coin.balance); + accumulatedCoins.push(coin); + } + } + + if (currentBalance >= requiredAmount) { + return splitAndMergeCoins(tx, firstCoin, accumulatedCoins, amounts); + } else { + return []; + } +} + +function splitAndMergeCoins(tx: Transaction, firstCoin: CoinStruct, accumulatedCoins: CoinStruct[], amounts: string[]) { + const pureAmounts = amounts.map((amount) => { + return tx.pure.u64(amount); + }); + if (accumulatedCoins.length > 0) { + tx.mergeCoins( + firstCoin.coinObjectId, + accumulatedCoins.map((c) => c.coinObjectId) + ); + return tx.splitCoins(firstCoin.coinObjectId, pureAmounts); + } + + return tx.splitCoins(firstCoin.coinObjectId, pureAmounts); +} diff --git a/src/services/utils/sui/paginated.ts b/src/services/utils/sui/paginated.ts new file mode 100644 index 00000000..f3bc58b8 --- /dev/null +++ b/src/services/utils/sui/paginated.ts @@ -0,0 +1,20 @@ +interface PaginatedResults { + data: Data[]; + hasNextPage: boolean; + nextCursor?: string | null; +} + +export async function fetchAllPagesRecursive>( + fetchFunction: (cursor?: string | null) => Promise, + cursor?: string | null, + accumulatedData: Data[] = [] +): Promise { + const result = await fetchFunction(cursor); + const newAccumulatedData = accumulatedData.concat(result.data); + + if (result.hasNextPage && result.nextCursor) { + return fetchAllPagesRecursive(fetchFunction, result.nextCursor, newAccumulatedData); + } else { + return newAccumulatedData; + } +} diff --git a/src/services/utils/sui/view.ts b/src/services/utils/sui/view.ts new file mode 100644 index 00000000..bee39835 --- /dev/null +++ b/src/services/utils/sui/view.ts @@ -0,0 +1,33 @@ +import { SuiClient } from "@mysten/sui/client"; +import { Transaction } from "@mysten/sui/transactions"; +import { Reified, toBcs, ToJSON, TypeArgument } from "../../models/sui/_framework/reified"; + +const mockSender = "0x0000000000000000000000000000000000000000000000000000000000000000"; + +export async function suiView( + client: SuiClient, + tx: Transaction, + reified: Reified +): Promise> { + const inspectionResult = await client.devInspectTransactionBlock({ + sender: mockSender, + transactionBlock: tx, + }); + if (inspectionResult.effects.status.status !== "success") { + throw new Error(`inspectionResult failed. ${JSON.stringify(inspectionResult, null, 2)}`); + } + + const returnValue = inspectionResult.results?.pop()?.returnValues?.pop(); + + if (!returnValue) { + throw new Error(`Something with inspectionResult went wrong. ${JSON.stringify(inspectionResult, null, 2)}`); + } + + const [data, _type] = returnValue; + + if (typeof reified === "object") { + return reified.fromBcs(Uint8Array.from(data)).toJSONField() as ToJSON; + } else { + return toBcs(reified).parse(Uint8Array.from(data)); + } +} diff --git a/src/tokens-info/tokens-info.model.ts b/src/tokens-info/tokens-info.model.ts index c7964b4f..63d6b8ee 100644 --- a/src/tokens-info/tokens-info.model.ts +++ b/src/tokens-info/tokens-info.model.ts @@ -37,6 +37,11 @@ export interface ChainDetails extends BasicChainProperties { * Number of confirmations required */ confirmations: number; + /** + * Sui addresses + * Optional. Defined for SUI + */ + suiAddresses?: SuiAddresses; } /** @@ -118,6 +123,41 @@ export interface Token { * Token LP rate */ lpRate: string; + /** + * Sui addresses + * Optional. Defined for SUI + */ + suiAddresses?: SuiAddresses; +} + +export interface SuiAddresses { + bridgeAddress: string; + bridgeAddressOrigin?: string; + bridgeObjectAddress: string; + + allbridgeMessengerAddress: string; + allbridgeMessengerAddressOrigin?: string; + allbridgeMessengerObjectAddress: string; + + gasOracleAddress: string; + gasOracleAddressOrigin?: string; + gasOracleObjectAddress: string; + + utilsAddress: string; + + wormholeMessengerAddress: string; + wormholeMessengerAddressOrigin?: string; + wormholeMessengerObjectAddress: string; + wormholeStateObjectAddress: string; + + cctpAddress: string; + cctpAddressOrigin?: string; + cctpObjectAddress: string; + + cctpDenyListObjectAddress: string; + cctpMessageTransmitterStateObjectAddress: string; + cctpTokenMessengerMinterStateObjectAddress: string; + cctpTreasuryObjectAddress: string; } /** diff --git a/src/utils/calculation/index.ts b/src/utils/calculation/index.ts index e5812069..f8298793 100644 --- a/src/utils/calculation/index.ts +++ b/src/utils/calculation/index.ts @@ -46,7 +46,7 @@ export function calculatePoolInfoImbalance(poolInfo: Pick, - poolInfo: Omit, + poolInfo: Omit ): string { const amountValue = Big(amount); if (amountValue.lte(0)) { @@ -63,7 +63,7 @@ export function swapToVUsd( export function swapFromVUsd( amount: BigSource, { feeShare, decimals }: Pick, - poolInfo: Pick, + poolInfo: Pick ): string { const amountValue = Big(amount); if (amountValue.lte(0)) { @@ -78,7 +78,7 @@ export function swapFromVUsd( export function getSwapFromVUsdPoolInfo( vUsdAmount: BigSource, - poolInfo: Omit, + poolInfo: Omit ): Pick { const amountValue = Big(vUsdAmount); if (amountValue.lte(0)) { @@ -103,7 +103,7 @@ export function getSwapFromVUsdPoolInfo( export function swapToVUsdReverse( amount: BigSource, { feeShare, decimals }: Pick, - poolInfo: Omit, + poolInfo: Omit ): Big { if (Big(amount).lte(0)) { return Big(0); @@ -129,7 +129,7 @@ export function swapToVUsdReverse( export function swapFromVUsdReverse( amount: BigSource, { feeShare, decimals }: Pick, - poolInfo: Omit, + poolInfo: Omit ): Big { if (Big(amount).lte(0)) { return Big(0); diff --git a/src/utils/calculation/swap-and-bridge-details.ts b/src/utils/calculation/swap-and-bridge-details.ts index 21546185..14f4c301 100644 --- a/src/utils/calculation/swap-and-bridge-details.ts +++ b/src/utils/calculation/swap-and-bridge-details.ts @@ -17,7 +17,7 @@ export function getSendAmountDetails( sourceToken: TokenWithChainDetails, sourcePool: PoolInfo, destToken: TokenWithChainDetails, - destPool: PoolInfo, + destPool: PoolInfo ): SendAmountDetails { const vUsd = swapToVUsd(amountInTokenPrecision, sourceToken, sourcePool); const vUsdInTokenPrecision = fromSystemPrecision(vUsd, sourceToken.decimals); @@ -33,7 +33,7 @@ export function getSendAmountDetails( .toFixed(), swap: convertIntAmountToFloat( Big(amountInTokenPrecision).minus(vUsdInTokenPrecision).minus(swapToFeeInt), - sourceToken.decimals, + sourceToken.decimals ) .neg() .round(sourceToken.decimals, Big.roundUp) @@ -46,7 +46,7 @@ export function getSendAmountDetails( .toFixed(), swap: convertIntAmountToFloat( fromSystemPrecision(vUsd, destToken.decimals).minus(result).minus(swapFromFeeInt), - destToken.decimals, + destToken.decimals ) .neg() .round(destToken.decimals, Big.roundUp) diff --git a/src/utils/calculation/swap-and-bridge-fee-calc.ts b/src/utils/calculation/swap-and-bridge-fee-calc.ts index 61757722..bf223109 100644 --- a/src/utils/calculation/swap-and-bridge-fee-calc.ts +++ b/src/utils/calculation/swap-and-bridge-fee-calc.ts @@ -27,17 +27,17 @@ export interface SwapFromVUsdCalcResult { export function swapAndBridgeFeeCalculation( amountInTokenPrecision: string, sourcePoolInfo: SwapPoolInfo, - destinationPoolInfo: SwapPoolInfo, + destinationPoolInfo: SwapPoolInfo ): SwapAndBridgeCalculationData { const swapToVUsdCalcResult = swapToVUsd( amountInTokenPrecision, { decimals: sourcePoolInfo.decimals, feeShare: sourcePoolInfo.feeShare }, - sourcePoolInfo.poolInfo, + sourcePoolInfo.poolInfo ); const swapFromVUsdCalcResult = swapFromVUsd( swapToVUsdCalcResult.amountIncludingCommissionInSystemPrecision, { decimals: destinationPoolInfo.decimals, feeShare: destinationPoolInfo.feeShare }, - destinationPoolInfo.poolInfo, + destinationPoolInfo.poolInfo ); return { swapToVUsdCalcResult, swapFromVUsdCalcResult }; } @@ -45,17 +45,17 @@ export function swapAndBridgeFeeCalculation( export function swapAndBridgeFeeCalculationReverse( amountInTokenPrecision: string, sourcePoolInfo: SwapPoolInfo, - destinationPoolInfo: SwapPoolInfo, + destinationPoolInfo: SwapPoolInfo ): SwapAndBridgeCalculationData { const swapToVUsdCalcResult = swapToVUsdReverse( amountInTokenPrecision, { decimals: destinationPoolInfo.decimals, feeShare: destinationPoolInfo.feeShare }, - destinationPoolInfo.poolInfo, + destinationPoolInfo.poolInfo ); const swapFromVUsdCalcResult = swapFromVUsdReverse( swapToVUsdCalcResult.amountIncludingCommissionInSystemPrecision, { decimals: sourcePoolInfo.decimals, feeShare: sourcePoolInfo.feeShare }, - sourcePoolInfo.poolInfo, + sourcePoolInfo.poolInfo ); return { swapToVUsdCalcResult, @@ -66,7 +66,7 @@ export function swapAndBridgeFeeCalculationReverse( function swapToVUsd( amount: BigSource, { feeShare, decimals }: Pick, - poolInfo: Omit, + poolInfo: Omit ): SwapToVUsdCalcResult { const amountValue = Big(amount); const fee = amountValue.times(feeShare); @@ -90,7 +90,7 @@ function calcSwapToVUsd(amountInSystemPrecision: Big, poolInfo: Omit, - poolInfo: Omit, + poolInfo: Omit ): SwapFromVUsdCalcResult { if (Big(amount).eq(0)) { return { @@ -115,7 +115,7 @@ function swapFromVUsd( function swapToVUsdReverse( amountInTokenPrecision: BigSource, { feeShare, decimals }: Pick, - poolInfo: PoolInfo, + poolInfo: PoolInfo ): SwapToVUsdCalcResult { const reversedFeeShare = Big(feeShare).div(Big(1).minus(feeShare)); const fee = Big(amountInTokenPrecision).times(reversedFeeShare); @@ -124,11 +124,11 @@ function swapToVUsdReverse( bridgeFeeInTokenPrecision: fee.round().toFixed(), amountIncludingCommissionInSystemPrecision: calcSwapToVUsdReverse( toSystemPrecision(amountWithFee, decimals), - poolInfo, + poolInfo ), amountExcludingCommissionInSystemPrecision: calcSwapToVUsdReverse( toSystemPrecision(amountInTokenPrecision, decimals), - poolInfo, + poolInfo ), }; } @@ -142,7 +142,7 @@ function calcSwapToVUsdReverse(amountInSystemPrecision: Big, poolInfo: PoolInfo) function swapFromVUsdReverse( amountInSystemPrecision: BigSource, { feeShare, decimals }: Pick, - poolInfo: PoolInfo, + poolInfo: PoolInfo ): SwapFromVUsdCalcResult { if (Big(amountInSystemPrecision).eq(0)) { return { diff --git a/src/utils/index.ts b/src/utils/index.ts index d8f93e2e..aa1ee3cf 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -17,7 +17,7 @@ export class DefaultUtils implements Utils { constructor( readonly nodeRpcUrlsConfig: NodeRpcUrlsConfig, - params: AllbridgeCoreSdkOptions, + params: AllbridgeCoreSdkOptions ) { this.srb = new DefaultSrbUtils(nodeRpcUrlsConfig, params); this.sol = new DefaultSolUtils(nodeRpcUrlsConfig, params); diff --git a/src/utils/sol/index.ts b/src/utils/sol/index.ts index 30083ba1..a197b6cc 100644 --- a/src/utils/sol/index.ts +++ b/src/utils/sol/index.ts @@ -19,7 +19,7 @@ export interface SolUtils { export class DefaultSolUtils implements SolUtils { constructor( readonly nodeRpcUrlsConfig: NodeRpcUrlsConfig, - readonly params: AllbridgeCoreSdkOptions, + readonly params: AllbridgeCoreSdkOptions ) {} async addMemoToTx(transaction: VersionedTransaction, memo: string): Promise { diff --git a/src/utils/sol/utils.ts b/src/utils/sol/utils.ts index dfc75092..a1b4c946 100644 --- a/src/utils/sol/utils.ts +++ b/src/utils/sol/utils.ts @@ -3,7 +3,7 @@ import { SdkError } from "../../exceptions"; export async function fetchAddressLookupTableAccountsFromTx( transaction: VersionedTransaction, - connection: Connection, + connection: Connection ): Promise { return await Promise.all( transaction.message.addressTableLookups.map(async (lookup) => { @@ -15,9 +15,9 @@ export async function fetchAddressLookupTableAccountsFromTx( throw new SdkError("Cannot get AccountInfo"); } return res.data; - }), + }) ), }); - }), + }) ); } diff --git a/src/utils/srb/index.ts b/src/utils/srb/index.ts index f8997b65..0c0231a9 100644 --- a/src/utils/srb/index.ts +++ b/src/utils/srb/index.ts @@ -78,7 +78,7 @@ const SEND_TRANSACTION_TIMEOUT = 180; export class DefaultSrbUtils implements SrbUtils { constructor( readonly nodeRpcUrlsConfig: NodeRpcUrlsConfig, - readonly params: AllbridgeCoreSdkOptions, + readonly params: AllbridgeCoreSdkOptions ) {} async buildChangeTrustLineXdrTx(params: TrustLineParams): Promise { @@ -119,7 +119,7 @@ export class DefaultSrbUtils implements SrbUtils { (balance): balance is BalanceLineAsset => (balance.asset_type === "credit_alphanum4" || balance.asset_type === "credit_alphanum12") && balance.asset_code == symbol && - balance.asset_issuer == srbTokenAddress, + balance.asset_issuer == srbTokenAddress ); } @@ -127,7 +127,7 @@ export class DefaultSrbUtils implements SrbUtils { const stellar = new Horizon.Server(this.nodeRpcUrlsConfig.getNodeRpcUrl(ChainSymbol.STLR)); const transaction = StellarTransactionBuilder.fromXDR( xdrTx, - this.nodeRpcUrlsConfig.getNodeRpcUrl(ChainSymbol.STLR), + this.nodeRpcUrlsConfig.getNodeRpcUrl(ChainSymbol.STLR) ); return await stellar.submitTransaction(transaction); } @@ -162,7 +162,7 @@ export class DefaultSrbUtils implements SrbUtils { const getTransactionResponseAll = await withExponentialBackoff( () => server.getTransaction(hash), (resp) => resp.status === SorobanRpc.Api.GetTransactionStatus.NOT_FOUND, - secondsToWait, + secondsToWait ); if (getTransactionResponseAll.length === 0) { diff --git a/src/utils/utils.ts b/src/utils/utils.ts index cef8c526..c99ad63f 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -5,7 +5,7 @@ import { PoolInfo, TokenWithChainDetails } from "../tokens-info"; export async function getPoolInfoByToken( api: AllbridgeCoreClientPoolsExt, - sourceChainToken: TokenWithChainDetails, + sourceChainToken: TokenWithChainDetails ): Promise { return await api.getPoolInfoByKey({ chainSymbol: sourceChainToken.chainSymbol, @@ -42,7 +42,7 @@ export async function promiseWithTimeoutAndRetries( toTry: () => Promise, msg: string, maxRetries: number, - timeoutMs: number, + timeoutMs: number ): Promise { if (maxRetries < 1) throw new Error(`Bad argument: 'maxRetries' must be greater than 0, but ${maxRetries} was received.`); @@ -65,7 +65,7 @@ export async function withExponentialBackoff( keepWaitingIf: (result: T) => boolean, secondsToWait: number, exponentialFactor = 1.5, - verbose = false, + verbose = false ): Promise { const attempts: T[] = []; @@ -88,7 +88,7 @@ export async function withExponentialBackoff( console.info( `Waiting ${waitTime}ms before trying again (bringing the total wait time to ${totalWaitTime}ms so far, of total ${ secondsToWait * 1000 - }ms)`, + }ms)` ); } await new Promise((res) => setTimeout(res, waitTime)); @@ -109,8 +109,8 @@ export async function withExponentialBackoff( `${count}. Called ${fn.name}; ${attempts.length} prev attempts. Most recent: ${JSON.stringify( attempts[attempts.length - 1], null, - 2, - )}`, + 2 + )}` ); } } diff --git a/tsconfig.json b/tsconfig.json index 0da962f9..ffedb4f5 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -22,7 +22,6 @@ "declaration": true, "resolveJsonModule": true, "allowJs": true, - "strictNullChecks": true, "noUncheckedIndexedAccess": true, "allowSyntheticDefaultImports": true, "inlineSources": true,