From 3fa4a7e624acc3cd06bb9fc1cbc19ed5a232fa76 Mon Sep 17 00:00:00 2001 From: Mike MacCana Date: Wed, 1 Apr 2026 12:21:09 -0400 Subject: [PATCH 1/6] Fix: this repo uses biome, configure vscode to use biome, and remove unnecessary prettierrc files --- .vscode/settings.json | 4 ++++ .../account-data-as-seed/anchor/.prettierrc | 10 ---------- .../transfer-hook/allow-block-list-token/.prettierrc | 7 ------- 3 files changed, 4 insertions(+), 17 deletions(-) create mode 100644 .vscode/settings.json delete mode 100644 tokens/token-2022/transfer-hook/account-data-as-seed/anchor/.prettierrc delete mode 100644 tokens/token-2022/transfer-hook/allow-block-list-token/.prettierrc diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..71c603b27 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "editor.defaultFormatter": "biomejs.biome", + "editor.formatOnSave": true +} diff --git a/tokens/token-2022/transfer-hook/account-data-as-seed/anchor/.prettierrc b/tokens/token-2022/transfer-hook/account-data-as-seed/anchor/.prettierrc deleted file mode 100644 index d2f009f9d..000000000 --- a/tokens/token-2022/transfer-hook/account-data-as-seed/anchor/.prettierrc +++ /dev/null @@ -1,10 +0,0 @@ -{ - "tabWidth": 2, - "useTabs": false, - "singleQuote": false, - "printWidth": 80, - "trailingComma": "all", - "arrowParens": "avoid", - "endOfLine": "auto", - "proseWrap": "always" -} diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/.prettierrc b/tokens/token-2022/transfer-hook/allow-block-list-token/.prettierrc deleted file mode 100644 index d6c3437b9..000000000 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/.prettierrc +++ /dev/null @@ -1,7 +0,0 @@ -{ - "arrowParens": "always", - "printWidth": 120, - "semi": false, - "singleQuote": true, - "trailingComma": "all" -} From 646891b502260c6929540cdf1513d5b2b20a70cc Mon Sep 17 00:00:00 2001 From: Mike MacCana Date: Wed, 1 Apr 2026 12:21:34 -0400 Subject: [PATCH 2/6] Fix: this project uses pnpm, remove yarn.lock file. --- yarn.lock | 153 ------------------------------------------------------ 1 file changed, 153 deletions(-) delete mode 100644 yarn.lock diff --git a/yarn.lock b/yarn.lock deleted file mode 100644 index a46b42c19..000000000 --- a/yarn.lock +++ /dev/null @@ -1,153 +0,0 @@ -# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -# yarn lockfile v1 - - -"@biomejs/biome@1.7.3": - version "1.7.3" - resolved "https://registry.npmjs.org/@biomejs/biome/-/biome-1.7.3.tgz" - integrity sha512-ogFQI+fpXftr+tiahA6bIXwZ7CSikygASdqMtH07J2cUzrpjyTMVc9Y97v23c7/tL1xCZhM+W9k4hYIBm7Q6cQ== - optionalDependencies: - "@biomejs/cli-darwin-arm64" "1.7.3" - "@biomejs/cli-darwin-x64" "1.7.3" - "@biomejs/cli-linux-arm64" "1.7.3" - "@biomejs/cli-linux-arm64-musl" "1.7.3" - "@biomejs/cli-linux-x64" "1.7.3" - "@biomejs/cli-linux-x64-musl" "1.7.3" - "@biomejs/cli-win32-arm64" "1.7.3" - "@biomejs/cli-win32-x64" "1.7.3" - -"@biomejs/cli-darwin-arm64@1.7.3": - version "1.7.3" - resolved "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-1.7.3.tgz" - integrity sha512-eDvLQWmGRqrPIRY7AIrkPHkQ3visEItJKkPYSHCscSDdGvKzYjmBJwG1Gu8+QC5ed6R7eiU63LEC0APFBobmfQ== - -"@cspotcode/source-map-support@^0.8.0": - version "0.8.1" - resolved "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz" - integrity sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw== - dependencies: - "@jridgewell/trace-mapping" "0.3.9" - -"@jridgewell/resolve-uri@^3.0.3": - version "3.1.1" - resolved "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz" - integrity sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA== - -"@jridgewell/sourcemap-codec@^1.4.10": - version "1.4.15" - resolved "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz" - integrity sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg== - -"@jridgewell/trace-mapping@0.3.9": - version "0.3.9" - resolved "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz" - integrity sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ== - dependencies: - "@jridgewell/resolve-uri" "^3.0.3" - "@jridgewell/sourcemap-codec" "^1.4.10" - -"@tsconfig/node10@^1.0.7": - version "1.0.9" - resolved "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.9.tgz" - integrity sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA== - -"@tsconfig/node12@^1.0.7": - version "1.0.11" - resolved "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz" - integrity sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag== - -"@tsconfig/node14@^1.0.0": - version "1.0.3" - resolved "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz" - integrity sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow== - -"@tsconfig/node16@^1.0.2": - version "1.0.4" - resolved "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz" - integrity sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA== - -"@types/node@*", "@types/node@^20.9.0": - version "20.9.0" - resolved "https://registry.npmjs.org/@types/node/-/node-20.9.0.tgz" - integrity sha512-nekiGu2NDb1BcVofVcEKMIwzlx4NjHlcjhoxxKBNLtz15Y1z7MYf549DFvkHSId02Ax6kGwWntIBPC3l/JZcmw== - dependencies: - undici-types "~5.26.4" - -acorn-walk@^8.1.1: - version "8.3.0" - resolved "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.0.tgz" - integrity sha512-FS7hV565M5l1R08MXqo8odwMTB02C2UqzB17RVgu9EyuYFBqJZ3/ZY97sQD5FewVu1UyDFc1yztUDrAwT0EypA== - -acorn@^8.4.1: - version "8.11.2" - resolved "https://registry.npmjs.org/acorn/-/acorn-8.11.2.tgz" - integrity sha512-nc0Axzp/0FILLEVsm4fNwLCwMttvhEI263QtVPQcbpfZZ3ts0hLsZGOpE6czNlid7CJ9MlyH8reXkpsf3YUY4w== - -arg@^4.1.0: - version "4.1.3" - resolved "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz" - integrity sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA== - -create-require@^1.1.0: - version "1.1.1" - resolved "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz" - integrity sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ== - -diff@^4.0.1: - version "4.0.2" - resolved "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz" - integrity sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A== - -husky@^9.0.11: - version "9.0.11" - resolved "https://registry.npmjs.org/husky/-/husky-9.0.11.tgz" - integrity sha512-AB6lFlbwwyIqMdHYhwPe+kjOC3Oc5P3nThEoW/AaO2BX3vJDjWPFxYLxokUZOo6RNX20He3AaT8sESs9NJcmEw== - -make-error@^1.1.1: - version "1.3.6" - resolved "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz" - integrity sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw== - -picocolors@^1.0.0: - version "1.0.0" - resolved "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz" - integrity sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ== - -ts-node@^10.9.1: - version "10.9.1" - resolved "https://registry.npmjs.org/ts-node/-/ts-node-10.9.1.tgz" - integrity sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw== - dependencies: - "@cspotcode/source-map-support" "^0.8.0" - "@tsconfig/node10" "^1.0.7" - "@tsconfig/node12" "^1.0.7" - "@tsconfig/node14" "^1.0.0" - "@tsconfig/node16" "^1.0.2" - acorn "^8.4.1" - acorn-walk "^8.1.1" - arg "^4.1.0" - create-require "^1.1.0" - diff "^4.0.1" - make-error "^1.1.1" - v8-compile-cache-lib "^3.0.1" - yn "3.1.1" - -typescript@^5.2.2, typescript@>=2.7: - version "5.2.2" - resolved "https://registry.npmjs.org/typescript/-/typescript-5.2.2.tgz" - integrity sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w== - -undici-types@~5.26.4: - version "5.26.5" - resolved "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz" - integrity sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA== - -v8-compile-cache-lib@^3.0.1: - version "3.0.1" - resolved "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz" - integrity sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg== - -yn@3.1.1: - version "3.1.1" - resolved "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz" - integrity sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q== From b72e4a5ad340698405fbec26c2a82152ce58f3d1 Mon Sep 17 00:00:00 2001 From: Mike MacCana Date: Wed, 1 Apr 2026 13:45:45 -0400 Subject: [PATCH 3/6] Fix: 'biome check' now passes. Fix all lint errors. - Biome is the existing TS formatter / linter, however it was failing. - Upgrade to Biome V2, run biome on GitHub Actions (it's already used in a precommit hook) - Add a biome config file to match what most of the existing code uses, plus Anchor defaults - Add missing Tailwind options to check CSS files with Tailwind directives - Skip some of the 'any' tests in Anchor TS files - these will be moved to LiteSVM --- .github/workflows/anchor.yml | 1 + .github/workflows/rust.yml | 1 + .github/workflows/solana-native.yml | 1 + .github/workflows/solana-pinocchio.yml | 1 + .github/workflows/typescript.yml | 30 ++ .vscode/settings.json | 4 +- basics/account-data/anchor/package.json | 30 +- .../account-data/anchor/tests/litesvm.test.ts | 172 +++---- basics/account-data/anchor/tests/test.ts | 72 ++- basics/account-data/native/tests/test.ts | 118 ++--- .../pinocchio/tests/index.test.ts | 237 +++++---- basics/checking-accounts/anchor/package.json | 32 +- .../anchor/tests/bankrun.test.ts | 95 ++-- basics/checking-accounts/anchor/tests/test.ts | 71 ++- basics/checking-accounts/native/tests/test.ts | 14 +- .../checking-accounts/pinocchio/tests/test.ts | 13 +- .../close-account/anchor/migrations/deploy.ts | 2 +- basics/close-account/anchor/package.json | 42 +- .../anchor/tests/litesvm.test.ts | 156 +++--- basics/close-account/anchor/tests/test.ts | 91 ++-- basics/close-account/anchor/tsconfig.json | 16 +- .../native/tests/close-account.test.ts | 23 +- basics/close-account/native/ts/index.ts | 4 +- .../native/ts/instructions/close.ts | 18 +- .../native/ts/instructions/create.ts | 21 +- basics/close-account/native/ts/state/index.ts | 8 +- .../pinocchio/tests/close-account.test.ts | 4 +- basics/counter/anchor/migrations/deploy.ts | 2 +- basics/counter/anchor/package.json | 40 +- basics/counter/anchor/tests/litesvm.test.ts | 178 +++---- basics/counter/anchor/tests/test.ts | 95 ++-- basics/counter/anchor/tsconfig.json | 16 +- basics/counter/mpl-stack/.solitarc.js | 14 +- basics/counter/mpl-stack/jest.config.js | 6 +- .../counter/mpl-stack/tests/counter.test.ts | 42 +- .../ts/generated/accounts/Counter.ts | 23 +- .../mpl-stack/ts/generated/accounts/index.ts | 4 +- .../counter/mpl-stack/ts/generated/index.ts | 8 +- .../ts/generated/instructions/Increment.ts | 8 +- .../ts/generated/instructions/index.ts | 2 +- basics/counter/mpl-stack/ts/index.ts | 2 +- basics/counter/native/tests/counter.test.ts | 30 +- basics/counter/native/ts/accounts/counter.ts | 6 +- basics/counter/native/ts/accounts/index.ts | 2 +- basics/counter/native/ts/index.ts | 8 +- .../createIncrementInstruction.ts | 4 +- .../counter/native/ts/instructions/index.ts | 2 +- .../counter/pinocchio/tests/counter.test.ts | 10 +- basics/create-account/anchor/package.json | 30 +- .../anchor/tests/litesvm.test.ts | 95 ++-- basics/create-account/anchor/tests/test.ts | 45 +- basics/create-account/anchor/tsconfig.json | 16 +- basics/create-account/native/tests/test.ts | 21 +- basics/create-account/pinocchio/tests/test.ts | 9 +- .../anchor/migrations/deploy.ts | 2 +- .../anchor/package.json | 40 +- .../anchor/tests/litesvm.test.ts | 271 +++++----- .../anchor/tests/test.ts | 117 ++--- .../anchor/tsconfig.json | 16 +- .../native/tests/test.ts | 39 +- basics/favorites/anchor/migrations/deploy.ts | 2 +- basics/favorites/anchor/package.json | 42 +- basics/favorites/anchor/tests/litesvm.test.ts | 257 +++++----- basics/favorites/anchor/tests/test.ts | 134 +++-- basics/favorites/anchor/tsconfig.json | 16 +- basics/favorites/native/tests/test.ts | 10 +- basics/favorites/pinocchio/tests/test.ts | 14 +- basics/hello-solana/anchor/package.json | 30 +- .../hello-solana/anchor/tests/litesvm.test.ts | 80 ++- basics/hello-solana/anchor/tests/test.ts | 22 +- basics/hello-solana/anchor/tsconfig.json | 16 +- .../hello-solana/native/tests/index.test.ts | 16 +- .../pinocchio/tests/index.test.ts | 16 +- basics/pda-rent-payer/anchor/package.json | 30 +- .../anchor/tests/litesvm.test.ts | 138 +++-- basics/pda-rent-payer/anchor/tests/test.ts | 92 ++-- basics/pda-rent-payer/anchor/tsconfig.json | 16 +- basics/pda-rent-payer/native/tests/test.ts | 18 +- basics/pda-rent-payer/pinocchio/tests/test.ts | 12 +- .../anchor/package.json | 30 +- .../anchor/tests/litesvm.test.ts | 130 +++-- .../anchor/tests/test.ts | 12 +- .../anchor/tsconfig.json | 16 +- .../native/tests/test.ts | 30 +- .../pinocchio/tests/test.ts | 10 +- .../anchor/package.json | 30 +- .../anchor/tests/litesvm.test.ts | 206 ++++---- .../anchor/tests/test.ts | 93 ++-- .../anchor/tsconfig.json | 16 +- .../native/tests/test.ts | 48 +- .../pinocchio/tests/test.ts | 12 +- basics/realloc/anchor/migrations/deploy.ts | 2 +- basics/realloc/anchor/package.json | 40 +- basics/realloc/anchor/tests/litesvm.test.ts | 192 ++++--- basics/realloc/anchor/tests/test.ts | 102 ++-- basics/realloc/anchor/tsconfig.json | 16 +- basics/realloc/native/tests/realloc.test.ts | 52 +- basics/realloc/native/ts/index.ts | 14 +- .../realloc/native/ts/instructions/create.ts | 20 +- .../realloc/native/ts/instructions/index.ts | 6 +- .../native/ts/instructions/reallocate.ts | 28 +- .../realloc/native/ts/state/address-info.ts | 14 +- .../native/ts/state/enhanced-address-info.ts | 18 +- basics/realloc/native/ts/state/index.ts | 6 +- basics/realloc/native/ts/state/work-info.ts | 14 +- basics/realloc/native/ts/util/index.ts | 2 +- basics/realloc/native/ts/util/util.ts | 4 +- .../realloc/pinocchio/tests/realloc.test.ts | 4 +- basics/rent/anchor/package.json | 30 +- basics/rent/anchor/tests/litesvm.test.ts | 106 ++-- basics/rent/anchor/tests/test.ts | 54 +- basics/rent/anchor/tsconfig.json | 16 +- basics/rent/native/tests/test.ts | 24 +- basics/rent/pinocchio/tests/test.ts | 3 +- basics/repository-layout/anchor/package.json | 30 +- .../anchor/tests/litesvm.test.ts | 218 ++++---- basics/repository-layout/anchor/tests/test.ts | 82 ++- basics/repository-layout/anchor/tsconfig.json | 16 +- basics/repository-layout/native/tests/test.ts | 126 ++++- basics/transfer-sol/anchor/package.json | 30 +- .../transfer-sol/anchor/tests/litesvm.test.ts | 157 +++--- basics/transfer-sol/anchor/tests/test.ts | 108 ++-- basics/transfer-sol/anchor/tsconfig.json | 16 +- .../transfer-sol/native/tests/instruction.ts | 10 +- basics/transfer-sol/native/tests/test.ts | 38 +- basics/transfer-sol/pinocchio/tests/test.ts | 10 +- biome.jsonc | 27 + .../cnft-burn/anchor/migrations/deploy.ts | 2 +- compression/cnft-burn/anchor/package.json | 50 +- .../anchor/tests/ReadApi/WrapperConnection.ts | 89 ++-- .../cnft-burn/anchor/tests/ReadApi/types.ts | 36 +- .../cnft-burn/anchor/tests/cnft-burn.ts | 39 +- .../cnft-burn/anchor/tests/createAndMint.ts | 36 +- .../anchor/tests/fetchNFTsByCollection.ts | 28 +- compression/cnft-burn/anchor/tests/readApi.ts | 18 +- compression/cnft-burn/anchor/tests/utils.ts | 8 +- .../anchor/tests/utils/compression.ts | 95 ++-- .../cnft-burn/anchor/tests/utils/helpers.ts | 86 ++-- compression/cnft-vault/anchor/package.json | 42 +- .../cnft-vault/anchor/tests/readAPI.ts | 18 +- .../anchor/tests/scripts/constants.ts | 8 +- .../anchor/tests/scripts/withdraw.ts | 23 +- .../anchor/tests/scripts/withdrawTwo.ts | 42 +- .../tests/scripts/withdrawWithLookup.ts | 52 +- compression/cnft-vault/anchor/tests/tests.ts | 63 ++- compression/cnft-vault/anchor/tests/utils.ts | 8 +- compression/cutils/anchor/package.json | 50 +- compression/cutils/anchor/tests/setup.ts | 28 +- compression/cutils/anchor/tests/tests.ts | 20 +- .../cutils/anchor/tests/utils/compression.ts | 97 ++-- .../cutils/anchor/tests/utils/helpers.ts | 84 ++-- .../cutils/anchor/tests/utils/readAPI.ts | 18 +- .../cutils/anchor/tests/utils/utils.ts | 23 +- package.json | 71 +-- pnpm-lock.yaml | 82 ++- scripts/lib/change-package-version.ts | 4 +- scripts/lib/command-check.ts | 16 +- scripts/lib/command-help.ts | 46 +- scripts/lib/command-list.ts | 6 +- scripts/lib/command-set.ts | 26 +- scripts/lib/command-update.ts | 22 +- scripts/lib/get-deps-count.ts | 4 +- scripts/lib/get-recursive-file-list.ts | 6 +- scripts/lib/index.ts | 10 +- scripts/sync-package-json.ts | 10 +- tokens/create-token/anchor/package.json | 38 +- tokens/create-token/anchor/prepare.mjs | 12 +- .../create-token/anchor/tests/bankrun.test.ts | 4 +- tokens/create-token/anchor/tests/test.ts | 22 +- tokens/create-token/native/package.json | 48 +- tokens/create-token/native/tests/test.ts | 54 +- tokens/escrow/anchor/migrations/deploy.ts | 2 +- tokens/escrow/anchor/package.json | 50 +- tokens/escrow/anchor/register.js | 6 +- tokens/escrow/anchor/tests/bankrun.test.ts | 151 ++---- tokens/escrow/anchor/tests/escrow.test.ts | 99 ++-- tokens/escrow/native/tests/account.ts | 14 +- tokens/escrow/native/tests/instruction.ts | 30 +- tokens/escrow/native/tests/test.ts | 50 +- tokens/escrow/native/tests/utils.ts | 29 +- .../anchor/package.json | 66 +-- .../external-delegate-token-master.test.ts | 35 +- .../anchor/tests/types.ts | 3 +- tokens/nft-minter/anchor/package.json | 36 +- tokens/nft-minter/anchor/prepare.mjs | 12 +- .../nft-minter/anchor/tests/bankrun.test.ts | 9 +- tokens/nft-minter/anchor/tests/test.ts | 20 +- .../nft-minter/native/tests/instructions.ts | 12 +- tokens/nft-minter/native/tests/test.ts | 46 +- tokens/nft-operations/anchor/package.json | 54 +- tokens/nft-operations/anchor/prepare.mjs | 12 +- .../anchor/tests/bankrun.test.ts | 300 +++++------ .../nft-operations/anchor/tests/mint-nft.ts | 60 +-- tokens/pda-mint-authority/anchor/package.json | 40 +- tokens/pda-mint-authority/anchor/prepare.mjs | 12 +- .../anchor/tests/bankrun.test.ts | 108 ++-- .../pda-mint-authority/anchor/tests/test.ts | 102 ++-- .../native/tests/instructions.ts | 14 +- .../pda-mint-authority/native/tests/test.ts | 65 ++- tokens/spl-token-minter/anchor/package.json | 40 +- tokens/spl-token-minter/anchor/prepare.mjs | 12 +- .../anchor/tests/bankrun.test.ts | 113 ++--- tokens/spl-token-minter/anchor/tests/test.ts | 108 ++-- .../native/tests/instructions.ts | 14 +- tokens/spl-token-minter/native/tests/test.ts | 39 +- .../basics/anchor/migrations/deploy.ts | 2 +- tokens/token-2022/basics/anchor/package.json | 42 +- .../token-2022/basics/anchor/tests/anchor.ts | 244 ++++----- .../basics/anchor/tests/bankrun.test.ts | 246 +++++---- .../cpi-guard/anchor/migrations/deploy.ts | 2 +- .../token-2022/cpi-guard/anchor/package.json | 42 +- .../cpi-guard/anchor/tests/cpi-guard.ts | 60 ++- .../anchor/migrations/deploy.ts | 2 +- .../default-account-state/anchor/package.json | 38 +- .../anchor/tests/default-account-state.ts | 24 +- .../native/tests/test.ts | 32 +- .../group/anchor/migrations/deploy.ts | 2 +- tokens/token-2022/group/anchor/package.json | 36 +- tokens/token-2022/group/anchor/tests/group.ts | 12 +- .../anchor/migrations/deploy.ts | 2 +- .../immutable-owner/anchor/package.json | 38 +- .../anchor/tests/immutable-owner.ts | 18 +- .../anchor/migrations/deploy.ts | 2 +- .../interest-bearing/anchor/package.json | 38 +- .../anchor/tests/interest-bearing.ts | 27 +- .../memo-transfer/anchor/migrations/deploy.ts | 2 +- .../memo-transfer/anchor/package.json | 40 +- .../anchor/tests/memo-transfer.ts | 74 ++- .../metadata/anchor/migrations/deploy.ts | 2 +- .../token-2022/metadata/anchor/package.json | 38 +- .../metadata/anchor/tests/metadata.ts | 70 +-- .../anchor/migrations/deploy.ts | 2 +- .../mint-close-authority/anchor/package.json | 38 +- .../anchor/tests/mint-close-authority.ts | 31 +- .../mint-close-authority/native/tests/test.ts | 32 +- .../multiple-extensions/native/tests/test.ts | 34 +- .../anchor/migrations/deploy.ts | 2 +- .../anchor-example/anchor/package.json | 44 +- .../anchor-example/anchor/tests/lumberjack.ts | 22 +- .../app/components/ChopTreeButton.tsx | 119 ++--- .../app/components/DisplayGameState.tsx | 20 +- .../app/components/DisplayNfts.tsx | 32 +- .../app/components/InitPlayerButton.tsx | 42 +- .../app/components/MintNftButton.tsx | 65 ++- .../app/components/RequestAirdrop.tsx | 52 +- .../app/components/SessionKeyButton.tsx | 68 ++- .../app/components/WalletMultiButton.tsx | 15 +- .../app/contexts/GameStateProvider.tsx | 134 +++-- .../app/contexts/NftProvider.tsx | 70 +-- .../app/contexts/SessionProvider.tsx | 28 +- .../app/contexts/WalletContextProvider.tsx | 39 +- .../anchor-example/app/idl/extension_nft.ts | 236 ++++----- .../anchor-example/app/next.config.js | 4 +- .../anchor-example/app/pages/_app.tsx | 22 +- .../anchor-example/app/pages/_document.tsx | 4 +- .../anchor-example/app/pages/api/hello.ts | 4 +- .../anchor-example/app/pages/index.tsx | 24 +- .../anchor-example/app/styles/Home.module.css | 18 +- .../anchor-example/app/styles/globals.css | 46 +- .../anchor-example/app/utils/anchor.ts | 33 +- .../app/utils/wrappedConnection.ts | 98 ++-- .../Assets/TextMesh Pro/Sprites/EmojiOne.json | 310 ++++++------ .../anchor/migrations/deploy.ts | 2 +- .../non-transferable/anchor/package.json | 38 +- .../anchor/tests/non-transferable.ts | 24 +- .../non-transferable/native/tests/test.ts | 34 +- .../anchor/migrations/deploy.ts | 2 +- .../permanent-delegate/anchor/package.json | 38 +- .../anchor/tests/permanent-delegate.ts | 20 +- .../transfer-fee/anchor/migrations/deploy.ts | 2 +- .../transfer-fee/anchor/package.json | 38 +- .../transfer-fee/anchor/tests/transfer-fee.ts | 69 ++- .../transfer-fee/native/tests/test.ts | 34 +- .../anchor/migrations/deploy.ts | 2 +- .../account-data-as-seed/anchor/package.json | 44 +- .../anchor/tests/transfer-hook.ts | 57 ++- .../anchor/src/abl-token-exports.ts | 22 +- .../anchor/src/index.ts | 2 +- .../anchor/tests/basic.test.ts | 10 +- .../allow-block-list-token/eslint.config.mjs | 8 +- .../allow-block-list-token/next.config.ts | 2 +- .../allow-block-list-token/package.json | 112 ++--- .../allow-block-list-token/postcss.config.mjs | 2 +- .../src/app/account/[address]/page.tsx | 4 +- .../src/app/account/page.tsx | 4 +- .../src/app/config/page.tsx | 5 +- .../src/app/create-token/page.tsx | 4 +- .../src/app/globals.css | 6 +- .../allow-block-list-token/src/app/layout.tsx | 36 +- .../src/app/manage-token/[address]/page.tsx | 4 +- .../src/app/manage-token/page.tsx | 4 +- .../allow-block-list-token/src/app/page.tsx | 4 +- .../components/abl-token/abl-token-config.tsx | 255 +++++----- .../abl-token/abl-token-data-access.tsx | 450 +++++++++-------- .../abl-token/abl-token-feature.tsx | 22 +- .../abl-token-manage-token-detail.tsx | 149 +++--- .../abl-token-manage-token-input.tsx | 33 +- .../abl-token/abl-token-manage-token.tsx | 14 +- .../abl-token/abl-token-new-token.tsx | 22 +- .../src/components/abl-token/abl-token-ui.tsx | 147 +++--- .../account/account-data-access.tsx | 194 ++++---- .../account/account-detail-feature.tsx | 30 +- .../account/account-list-feature.tsx | 15 +- .../src/components/account/account-ui.tsx | 169 ++++--- .../src/components/app-alert.tsx | 8 +- .../src/components/app-footer.tsx | 6 +- .../src/components/app-header.tsx | 30 +- .../src/components/app-hero.tsx | 14 +- .../src/components/app-layout.tsx | 22 +- .../src/components/app-modal.tsx | 20 +- .../src/components/app-providers.tsx | 14 +- .../cluster/cluster-data-access.tsx | 112 ++--- .../src/components/cluster/cluster-ui.tsx | 45 +- .../dashboard/dashboard-feature.tsx | 23 +- .../src/components/react-query-provider.tsx | 18 +- .../src/components/solana/solana-provider.tsx | 42 +- .../src/components/theme-provider.tsx | 8 +- .../src/components/theme-select.tsx | 26 +- .../src/components/ui/alert.tsx | 36 +- .../src/components/ui/button.tsx | 44 +- .../src/components/ui/card.tsx | 42 +- .../src/components/ui/dialog.tsx | 48 +- .../src/components/ui/dropdown-menu.tsx | 76 +-- .../src/components/ui/input.tsx | 16 +- .../src/components/ui/label.tsx | 14 +- .../src/components/ui/sonner.tsx | 22 +- .../src/components/ui/table.tsx | 52 +- .../src/components/use-transaction-toast.tsx | 28 +- .../allow-block-list-token/src/lib/utils.ts | 6 +- .../counter/anchor/migrations/deploy.ts | 2 +- .../transfer-hook/counter/anchor/package.json | 44 +- .../counter/anchor/tests/transfer-hook.ts | 54 +- .../hello-world/anchor/migrations/deploy.ts | 2 +- .../hello-world/anchor/package.json | 44 +- .../hello-world/anchor/tests/transfer-hook.ts | 41 +- .../transfer-hook/pblock-list/codama.ts | 193 +++---- .../transfer-hook/pblock-list/pino/codama.ts | 193 +++---- .../pino/sdk/ts/src/accounts/config.ts | 24 +- .../pino/sdk/ts/src/accounts/extraMetas.ts | 14 +- .../pino/sdk/ts/src/accounts/index.ts | 6 +- .../pino/sdk/ts/src/accounts/walletBlock.ts | 12 +- .../pblock-list/pino/sdk/ts/src/index.ts | 8 +- .../sdk/ts/src/instructions/blockWallet.ts | 94 +++- .../pino/sdk/ts/src/instructions/index.ts | 8 +- .../pino/sdk/ts/src/instructions/init.ts | 47 +- .../ts/src/instructions/setupExtraMetas.ts | 97 +++- .../sdk/ts/src/instructions/unblockWallet.ts | 74 ++- .../pino/sdk/ts/src/pdas/config.ts | 12 +- .../pino/sdk/ts/src/pdas/extraMetas.ts | 14 +- .../pblock-list/pino/sdk/ts/src/pdas/index.ts | 6 +- .../pino/sdk/ts/src/pdas/walletBlock.ts | 14 +- .../pino/sdk/ts/src/programs/blockList.ts | 31 +- .../pino/sdk/ts/src/programs/index.ts | 2 +- .../pino/sdk/ts/src/shared/index.ts | 24 +- .../pblock-list/sdk/ts/src/accounts/config.ts | 24 +- .../sdk/ts/src/accounts/extraMetas.ts | 14 +- .../pblock-list/sdk/ts/src/accounts/index.ts | 6 +- .../sdk/ts/src/accounts/walletBlock.ts | 12 +- .../pblock-list/sdk/ts/src/index.ts | 8 +- .../sdk/ts/src/instructions/blockWallet.ts | 94 +++- .../sdk/ts/src/instructions/index.ts | 8 +- .../sdk/ts/src/instructions/init.ts | 47 +- .../ts/src/instructions/setupExtraMetas.ts | 97 +++- .../sdk/ts/src/instructions/unblockWallet.ts | 74 ++- .../pblock-list/sdk/ts/src/pdas/config.ts | 12 +- .../pblock-list/sdk/ts/src/pdas/extraMetas.ts | 14 +- .../pblock-list/sdk/ts/src/pdas/index.ts | 6 +- .../sdk/ts/src/pdas/walletBlock.ts | 14 +- .../sdk/ts/src/programs/blockList.ts | 31 +- .../pblock-list/sdk/ts/src/programs/index.ts | 2 +- .../pblock-list/sdk/ts/src/shared/index.ts | 24 +- .../transfer-cost/anchor/migrations/deploy.ts | 2 +- .../transfer-cost/anchor/package.json | 38 +- .../anchor/tests/transfer-hook.ts | 57 ++- .../transfer-switch/anchor/package.json | 34 +- .../anchor/tests/transfer-switch.ts | 145 ++---- .../whitelist/anchor/migrations/deploy.ts | 2 +- .../whitelist/anchor/package.json | 42 +- .../whitelist/anchor/tests/transfer-hook.ts | 35 +- tokens/token-fundraiser/anchor/package.json | 42 +- .../anchor/tests/bankrun.test.ts | 84 +--- .../anchor/tests/fundraiser.ts | 471 ++++++++---------- tokens/token-swap/anchor/package.json | 38 +- tokens/token-swap/anchor/tests/create-amm.ts | 28 +- tokens/token-swap/anchor/tests/create-pool.ts | 28 +- .../anchor/tests/deposit-liquidity.ts | 23 +- tokens/token-swap/anchor/tests/swap.ts | 33 +- tokens/token-swap/anchor/tests/utils.ts | 20 +- .../anchor/tests/withdraw-liquidity.ts | 29 +- tokens/transfer-tokens/anchor/package.json | 42 +- tokens/transfer-tokens/anchor/prepare.mjs | 12 +- .../anchor/tests/bankrun.test.ts | 14 +- tokens/transfer-tokens/anchor/tests/test.ts | 133 +++-- .../native/tests/instructions.ts | 22 +- tokens/transfer-tokens/native/tests/test.ts | 96 ++-- tools/shank-and-solita/native/.solitarc.js | 14 +- .../native/tests/generated/accounts/Car.ts | 22 +- .../tests/generated/accounts/RentalOrder.ts | 32 +- .../native/tests/generated/accounts/index.ts | 8 +- .../native/tests/generated/index.ts | 10 +- .../tests/generated/instructions/AddCar.ts | 14 +- .../generated/instructions/BookRental.ts | 14 +- .../tests/generated/instructions/PickUpCar.ts | 8 +- .../tests/generated/instructions/ReturnCar.ts | 8 +- .../tests/generated/instructions/index.ts | 8 +- .../tests/generated/types/AddCarArgs.ts | 10 +- .../tests/generated/types/BookRentalArgs.ts | 12 +- .../generated/types/RentalOrderStatus.ts | 7 +- .../native/tests/generated/types/index.ts | 6 +- tools/shank-and-solita/native/tests/test.ts | 60 +-- 410 files changed, 9139 insertions(+), 8855 deletions(-) create mode 100644 .github/workflows/typescript.yml create mode 100644 biome.jsonc diff --git a/.github/workflows/anchor.yml b/.github/workflows/anchor.yml index 926a95b98..9b606c95d 100644 --- a/.github/workflows/anchor.yml +++ b/.github/workflows/anchor.yml @@ -7,6 +7,7 @@ on: branches: - main - anchor-1.0 + - fix-biome-errors pull_request: types: [opened, synchronize, reopened] branches: diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 64c46c494..479939a96 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -10,6 +10,7 @@ on: branches: - main - anchor-1.0 + - fix-biome-errors pull_request: types: [opened, synchronize, reopened] branches: diff --git a/.github/workflows/solana-native.yml b/.github/workflows/solana-native.yml index 9d6331e05..f1f030f8e 100644 --- a/.github/workflows/solana-native.yml +++ b/.github/workflows/solana-native.yml @@ -6,6 +6,7 @@ on: push: branches: - main + - fix-biome-errors pull_request: types: [opened, synchronize, reopened] branches: diff --git a/.github/workflows/solana-pinocchio.yml b/.github/workflows/solana-pinocchio.yml index 3215934cd..d534656c2 100644 --- a/.github/workflows/solana-pinocchio.yml +++ b/.github/workflows/solana-pinocchio.yml @@ -6,6 +6,7 @@ on: push: branches: - main + - fix-biome-errors pull_request: types: [opened, synchronize, reopened] branches: diff --git a/.github/workflows/typescript.yml b/.github/workflows/typescript.yml new file mode 100644 index 000000000..b87e3d482 --- /dev/null +++ b/.github/workflows/typescript.yml @@ -0,0 +1,30 @@ +name: TypeScript + +on: + push: + branches: + - main + - fix-biome-errors + pull_request: + types: [opened, synchronize, reopened] + branches: + - main + +env: + FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true + +jobs: + biome: + name: Biome check + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: pnpm + # --frozen-lockfile: fail if pnpm-lock.yaml is out of date + # --ignore-workspace: only install root deps, not all 94 subprojects + - run: pnpm install --frozen-lockfile --ignore-workspace + - run: pnpm run check diff --git a/.vscode/settings.json b/.vscode/settings.json index 71c603b27..88ca7c2bd 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,4 +1,4 @@ { - "editor.defaultFormatter": "biomejs.biome", - "editor.formatOnSave": true + "editor.defaultFormatter": "biomejs.biome", + "editor.formatOnSave": true } diff --git a/basics/account-data/anchor/package.json b/basics/account-data/anchor/package.json index fcb292b38..495f5d0cc 100644 --- a/basics/account-data/anchor/package.json +++ b/basics/account-data/anchor/package.json @@ -1,17 +1,17 @@ { - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/web3.js": "^1.98.4" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "litesvm": "^0.3.3", - "mocha": "^9.0.3", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - }, - "type": "module" + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/web3.js": "^1.98.4" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "litesvm": "^0.3.3", + "mocha": "^9.0.3", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + }, + "type": "module" } diff --git a/basics/account-data/anchor/tests/litesvm.test.ts b/basics/account-data/anchor/tests/litesvm.test.ts index 2136f1caa..dcf90cafd 100644 --- a/basics/account-data/anchor/tests/litesvm.test.ts +++ b/basics/account-data/anchor/tests/litesvm.test.ts @@ -1,110 +1,96 @@ import { BorshCoder } from "@anchor-lang/core"; -import { - Keypair, - PublicKey, - SystemProgram, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; +import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction } from "@solana/web3.js"; import { LiteSVM } from "litesvm"; -import IDL from "../target/idl/account_data_anchor_program.json" with { - type: "json", -}; +import IDL from "../target/idl/account_data_anchor_program.json" with { type: "json" }; describe("Account Data!", () => { - let litesvm: LiteSVM; - let programId: PublicKey; - let payer: Keypair; - let addressInfoAccount: Keypair; - const coder = new BorshCoder(IDL); + let litesvm: LiteSVM; + let programId: PublicKey; + let payer: Keypair; + let addressInfoAccount: Keypair; + const coder = new BorshCoder(IDL); - before(() => { - litesvm = new LiteSVM(); - programId = new PublicKey(IDL.address); - payer = Keypair.generate(); - addressInfoAccount = Keypair.generate(); + before(() => { + litesvm = new LiteSVM(); + programId = new PublicKey(IDL.address); + payer = Keypair.generate(); + addressInfoAccount = Keypair.generate(); - const programPath = new URL( - "../target/deploy/account_data_anchor_program.so", - // @ts-ignore - import.meta.url, - ).pathname; - litesvm.addProgramFromFile(programId, programPath); + const programPath = new URL( + "../target/deploy/account_data_anchor_program.so", + // @ts-expect-error + import.meta.url, + ).pathname; + litesvm.addProgramFromFile(programId, programPath); - litesvm.airdrop(payer.publicKey, BigInt(100000000000)); - }); + litesvm.airdrop(payer.publicKey, BigInt(100000000000)); + }); - it("Create the address info account", () => { - console.log(`Payer Address : ${payer.publicKey}`); - console.log(`Address Info Acct : ${addressInfoAccount.publicKey}`); + it("Create the address info account", () => { + console.log(`Payer Address : ${payer.publicKey}`); + console.log(`Address Info Acct : ${addressInfoAccount.publicKey}`); - // Instruction Ix data - const addressInfoIns = { - name: "Joe C", - house_number: 136, - street: "Mile High Dr.", - city: "Solana Beach", - }; + // Instruction Ix data + const addressInfoIns = { + name: "Joe C", + house_number: 136, + street: "Mile High Dr.", + city: "Solana Beach", + }; - /** - * Convert into buffer and encode of instruction and arguments - */ - const data = coder.instruction.encode( - "create_address_info", - addressInfoIns, - ); + /** + * Convert into buffer and encode of instruction and arguments + */ + const data = coder.instruction.encode("create_address_info", addressInfoIns); - /** - * Create Transactions - */ + /** + * Create Transactions + */ - const ix = new TransactionInstruction({ - keys: [ - { - pubkey: payer.publicKey, - isSigner: true, - isWritable: true, - }, - { - pubkey: addressInfoAccount.publicKey, - isSigner: true, - isWritable: true, - }, - { - pubkey: SystemProgram.programId, - isSigner: false, - isWritable: false, - }, - ], - programId, - data, - }); + const ix = new TransactionInstruction({ + keys: [ + { + pubkey: payer.publicKey, + isSigner: true, + isWritable: true, + }, + { + pubkey: addressInfoAccount.publicKey, + isSigner: true, + isWritable: true, + }, + { + pubkey: SystemProgram.programId, + isSigner: false, + isWritable: false, + }, + ], + programId, + data, + }); - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = litesvm.latestBlockhash(); - tx.sign(payer, addressInfoAccount); - const res = litesvm.sendTransaction(tx); - // console.log(res.toString()); - }); - it("Read the new account's data", () => { - const accountInfoAcc = litesvm.getAccount(addressInfoAccount.publicKey); - if (!accountInfoAcc) { - throw new Error("Failed to fetch account info"); - } + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = litesvm.latestBlockhash(); + tx.sign(payer, addressInfoAccount); + const _res = litesvm.sendTransaction(tx); + // console.log(res.toString()); + }); + it("Read the new account's data", () => { + const accountInfoAcc = litesvm.getAccount(addressInfoAccount.publicKey); + if (!accountInfoAcc) { + throw new Error("Failed to fetch account info"); + } - /** - * Decode the accounts' data - */ - const addressInfo = coder.accounts.decode( - "AddressInfo", - Buffer.from(accountInfoAcc.data), - ); + /** + * Decode the accounts' data + */ + const addressInfo = coder.accounts.decode("AddressInfo", Buffer.from(accountInfoAcc.data)); - console.log(`Name : ${addressInfo.name}`); - console.log(`House Num: ${addressInfo.house_number}`); - console.log(`Street : ${addressInfo.street}`); - console.log(`City : ${addressInfo.city}`); - }); + console.log(`Name : ${addressInfo.name}`); + console.log(`House Num: ${addressInfo.house_number}`); + console.log(`Street : ${addressInfo.street}`); + console.log(`City : ${addressInfo.city}`); + }); }); diff --git a/basics/account-data/anchor/tests/test.ts b/basics/account-data/anchor/tests/test.ts index b8822eabd..5c2302595 100644 --- a/basics/account-data/anchor/tests/test.ts +++ b/basics/account-data/anchor/tests/test.ts @@ -3,49 +3,41 @@ import { Keypair } from "@solana/web3.js"; import type { AccountDataAnchorProgram } from "../target/types/account_data_anchor_program"; describe("Account Data!", () => { - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); - const payer = provider.wallet as anchor.Wallet; - const program = anchor.workspace - .AccountDataAnchorProgram as anchor.Program; + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); + const payer = provider.wallet as anchor.Wallet; + const program = anchor.workspace.AccountDataAnchorProgram as anchor.Program; - // Generate a new keypair for the addressInfo account - const addressInfoAccount = new Keypair(); + // Generate a new keypair for the addressInfo account + const addressInfoAccount = new Keypair(); - it("Create the address info account", async () => { - console.log(`Payer Address : ${payer.publicKey}`); - console.log(`Address Info Acct : ${addressInfoAccount.publicKey}`); + it("Create the address info account", async () => { + console.log(`Payer Address : ${payer.publicKey}`); + console.log(`Address Info Acct : ${addressInfoAccount.publicKey}`); - // Instruction Ix data - const addressInfo = { - name: "Joe C", - houseNumber: 136, - street: "Mile High Dr.", - city: "Solana Beach", - }; + // Instruction Ix data + const addressInfo = { + name: "Joe C", + houseNumber: 136, + street: "Mile High Dr.", + city: "Solana Beach", + }; - await program.methods - .createAddressInfo( - addressInfo.name, - addressInfo.houseNumber, - addressInfo.street, - addressInfo.city, - ) - .accounts({ - addressInfo: addressInfoAccount.publicKey, - payer: payer.publicKey, - }) - .signers([addressInfoAccount]) - .rpc(); - }); + await program.methods + .createAddressInfo(addressInfo.name, addressInfo.houseNumber, addressInfo.street, addressInfo.city) + .accounts({ + addressInfo: addressInfoAccount.publicKey, + payer: payer.publicKey, + }) + .signers([addressInfoAccount]) + .rpc(); + }); - it("Read the new account's data", async () => { - const addressInfo = await program.account.addressInfo.fetch( - addressInfoAccount.publicKey, - ); - console.log(`Name : ${addressInfo.name}`); - console.log(`House Num: ${addressInfo.houseNumber}`); - console.log(`Street : ${addressInfo.street}`); - console.log(`City : ${addressInfo.city}`); - }); + it("Read the new account's data", async () => { + const addressInfo = await program.account.addressInfo.fetch(addressInfoAccount.publicKey); + console.log(`Name : ${addressInfo.name}`); + console.log(`House Num: ${addressInfo.houseNumber}`); + console.log(`Street : ${addressInfo.street}`); + console.log(`City : ${addressInfo.city}`); + }); }); diff --git a/basics/account-data/native/tests/test.ts b/basics/account-data/native/tests/test.ts index 3965804f5..5af298222 100644 --- a/basics/account-data/native/tests/test.ts +++ b/basics/account-data/native/tests/test.ts @@ -1,88 +1,76 @@ import { Buffer } from "node:buffer"; import { describe, test } from "node:test"; -import { - Keypair, - PublicKey, - SystemProgram, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; +import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction } from "@solana/web3.js"; import * as borsh from "borsh"; import { start } from "solana-bankrun"; const AddressInfoSchema = { - struct: { - name: "string", - house_number: "u8", - street: "string", - city: "string", - }, + struct: { + name: "string", + house_number: "u8", + street: "string", + city: "string", + }, }; type AddressInfo = { - name: string; - house_number: number; - street: string; - city: string; + name: string; + house_number: number; + street: string; + city: string; }; function borshSerialize(schema: borsh.Schema, data: object): Buffer { - return Buffer.from(borsh.serialize(schema, data)); + return Buffer.from(borsh.serialize(schema, data)); } describe("Account Data!", async () => { - const addressInfoAccount = Keypair.generate(); - const PROGRAM_ID = PublicKey.unique(); - const context = await start( - [{ name: "account_data_native_program", programId: PROGRAM_ID }], - [], - ); - const client = context.banksClient; + const addressInfoAccount = Keypair.generate(); + const PROGRAM_ID = PublicKey.unique(); + const context = await start([{ name: "account_data_native_program", programId: PROGRAM_ID }], []); + const client = context.banksClient; - test("Create the address info account", async () => { - const payer = context.payer; + test("Create the address info account", async () => { + const payer = context.payer; - console.log(`Program Address : ${PROGRAM_ID}`); - console.log(`Payer Address : ${payer.publicKey}`); - console.log(`Address Info Acct : ${addressInfoAccount.publicKey}`); + console.log(`Program Address : ${PROGRAM_ID}`); + console.log(`Payer Address : ${payer.publicKey}`); + console.log(`Address Info Acct : ${addressInfoAccount.publicKey}`); - const ix = new TransactionInstruction({ - keys: [ - { - pubkey: addressInfoAccount.publicKey, - isSigner: true, - isWritable: true, - }, - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId: PROGRAM_ID, - data: borshSerialize(AddressInfoSchema, { - name: "Joe C", - house_number: 136, - street: "Mile High Dr.", - city: "Solana Beach", - }), - }); + const ix = new TransactionInstruction({ + keys: [ + { + pubkey: addressInfoAccount.publicKey, + isSigner: true, + isWritable: true, + }, + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId: PROGRAM_ID, + data: borshSerialize(AddressInfoSchema, { + name: "Joe C", + house_number: 136, + street: "Mile High Dr.", + city: "Solana Beach", + }), + }); - const blockhash = context.lastBlockhash; + const blockhash = context.lastBlockhash; - const tx = new Transaction(); - tx.recentBlockhash = blockhash; - tx.add(ix).sign(payer, addressInfoAccount); - await client.processTransaction(tx); - }); + const tx = new Transaction(); + tx.recentBlockhash = blockhash; + tx.add(ix).sign(payer, addressInfoAccount); + await client.processTransaction(tx); + }); - test("Read the new account's data", async () => { - const accountInfo = await client.getAccount(addressInfoAccount.publicKey); + test("Read the new account's data", async () => { + const accountInfo = await client.getAccount(addressInfoAccount.publicKey); - const readAddressInfo = borsh.deserialize( - AddressInfoSchema, - Buffer.from(accountInfo.data), - ) as AddressInfo; - console.log(`Name : ${readAddressInfo.name}`); - console.log(`House Num: ${readAddressInfo.house_number}`); - console.log(`Street : ${readAddressInfo.street}`); - console.log(`City : ${readAddressInfo.city}`); - }); + const readAddressInfo = borsh.deserialize(AddressInfoSchema, Buffer.from(accountInfo.data)) as AddressInfo; + console.log(`Name : ${readAddressInfo.name}`); + console.log(`House Num: ${readAddressInfo.house_number}`); + console.log(`Street : ${readAddressInfo.street}`); + console.log(`City : ${readAddressInfo.city}`); + }); }); diff --git a/basics/account-data/pinocchio/tests/index.test.ts b/basics/account-data/pinocchio/tests/index.test.ts index 1fac4271e..825ab4e67 100644 --- a/basics/account-data/pinocchio/tests/index.test.ts +++ b/basics/account-data/pinocchio/tests/index.test.ts @@ -1,149 +1,142 @@ import { readFileSync } from "node:fs"; import { describe, test } from "node:test"; -import { - Keypair, - LAMPORTS_PER_SOL, - SystemProgram, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; +import { Keypair, LAMPORTS_PER_SOL, SystemProgram, Transaction, TransactionInstruction } from "@solana/web3.js"; import { LiteSVM } from "litesvm"; interface AddressInfo { - name: string; - house_number: number; - street: string; - city: string; + name: string; + house_number: number; + street: string; + city: string; } function toBytes(addressInfo: AddressInfo): Buffer { - const data: number[] = []; + const data: number[] = []; - // Add instruction discriminator - data.push(0); + // Add instruction discriminator + data.push(0); - // Pad name to 16 bytes (data[1..17]) - const nameBytes = Buffer.from(addressInfo.name, "utf-8"); - const namePadded = Buffer.alloc(16); - nameBytes.copy(namePadded, 0, 0, Math.min(nameBytes.length, 16)); - data.push(...namePadded); + // Pad name to 16 bytes (data[1..17]) + const nameBytes = Buffer.from(addressInfo.name, "utf-8"); + const namePadded = Buffer.alloc(16); + nameBytes.copy(namePadded, 0, 0, Math.min(nameBytes.length, 16)); + data.push(...namePadded); - // Add 1 byte padding at index 17 - data.push(0); + // Add 1 byte padding at index 17 + data.push(0); - // Add house_number at index 18 - data.push(addressInfo.house_number); + // Add house_number at index 18 + data.push(addressInfo.house_number); - // Pad street to 16 bytes (data[19..35]) - const streetBytes = Buffer.from(addressInfo.street, "utf-8"); - const streetPadded = Buffer.alloc(16); - streetBytes.copy(streetPadded, 0, 0, Math.min(streetBytes.length, 16)); - data.push(...streetPadded); + // Pad street to 16 bytes (data[19..35]) + const streetBytes = Buffer.from(addressInfo.street, "utf-8"); + const streetPadded = Buffer.alloc(16); + streetBytes.copy(streetPadded, 0, 0, Math.min(streetBytes.length, 16)); + data.push(...streetPadded); - // Add 1 byte padding at index 35 - data.push(0); + // Add 1 byte padding at index 35 + data.push(0); - // Pad city to 16 bytes (data[36..52]) - const cityBytes = Buffer.from(addressInfo.city, "utf-8"); - const cityPadded = Buffer.alloc(16); - cityBytes.copy(cityPadded, 0, 0, Math.min(cityBytes.length, 16)); - data.push(...cityPadded); + // Pad city to 16 bytes (data[36..52]) + const cityBytes = Buffer.from(addressInfo.city, "utf-8"); + const cityPadded = Buffer.alloc(16); + cityBytes.copy(cityPadded, 0, 0, Math.min(cityBytes.length, 16)); + data.push(...cityPadded); - return Buffer.from(data); + return Buffer.from(data); } function fromBytes(buffer: Buffer): AddressInfo { - // name: bytes 0..16 - const nameBytes = buffer.subarray(0, 16); - const name = nameBytes.toString("utf-8").replace(/\0/g, ""); + // name: bytes 0..16 + const nameBytes = buffer.subarray(0, 16); + const name = nameBytes.toString("utf-8").replace(/\0/g, ""); - // house_number: byte 17 - const house_number = buffer[17]; + // house_number: byte 17 + const house_number = buffer[17]; - // street: bytes 18..34 - const streetBytes = buffer.subarray(18, 34); - const street = streetBytes.toString("utf-8").replace(/\0/g, ""); + // street: bytes 18..34 + const streetBytes = buffer.subarray(18, 34); + const street = streetBytes.toString("utf-8").replace(/\0/g, ""); - // city: bytes 35..51 - const cityBytes = buffer.subarray(35, 51); - const city = cityBytes.toString("utf-8").replace(/\0/g, ""); + // city: bytes 35..51 + const cityBytes = buffer.subarray(35, 51); + const city = cityBytes.toString("utf-8").replace(/\0/g, ""); - return { name, house_number, street, city }; + return { name, house_number, street, city }; } describe("Account Data!", () => { - // Load the program keypair - const programKeypairPath = new URL( - "./fixtures/account_data_pinocchio_program-keypair.json", - // @ts-ignore - import.meta.url, - ).pathname; - const programKeypairData = JSON.parse(readFileSync(programKeypairPath, "utf-8")); - const programKeypair = Keypair.fromSecretKey(new Uint8Array(programKeypairData)); - const PROGRAM_ID = programKeypair.publicKey; - - // Load the program - const programPath = new URL( - "./fixtures/account_data_pinocchio_program.so", - // @ts-ignore - import.meta.url, - ).pathname; - - const litesvm = new LiteSVM(); - litesvm.addProgramFromFile(PROGRAM_ID, programPath); - - const payer = Keypair.generate(); - litesvm.airdrop(payer.publicKey, BigInt(100 * LAMPORTS_PER_SOL)); - - const addressInfoAccount = Keypair.generate(); - - test("Create the address info account", () => { - console.log(`Program Address : ${PROGRAM_ID}`); - console.log(`Payer Address : ${payer.publicKey}`); - console.log(`Address Info Acct : ${addressInfoAccount.publicKey}`); - - const addressInfo: AddressInfo = { - name: "Joe C", - house_number: 136, - street: "Mile High Dr.", - city: "Solana Beach", - }; - - const ix = new TransactionInstruction({ - keys: [ - { - pubkey: addressInfoAccount.publicKey, - isSigner: true, - isWritable: true, - }, - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId: PROGRAM_ID, - data: toBytes(addressInfo), - }); - - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = litesvm.latestBlockhash(); - tx.sign(payer, addressInfoAccount); - - litesvm.sendTransaction(tx); - }); - - test("Read the new account's data", () => { - const accountInfo = litesvm.getAccount(addressInfoAccount.publicKey); - - if (!accountInfo) { - throw new Error("Account not found"); - } - - const readAddressInfo = fromBytes(Buffer.from(accountInfo.data)); - - console.log(`Name : ${readAddressInfo.name}`); - console.log(`House Num: ${readAddressInfo.house_number}`); - console.log(`Street : ${readAddressInfo.street}`); - console.log(`City : ${readAddressInfo.city}`); - }); + // Load the program keypair + const programKeypairPath = new URL( + "./fixtures/account_data_pinocchio_program-keypair.json", + // @ts-expect-error + import.meta.url, + ).pathname; + const programKeypairData = JSON.parse(readFileSync(programKeypairPath, "utf-8")); + const programKeypair = Keypair.fromSecretKey(new Uint8Array(programKeypairData)); + const PROGRAM_ID = programKeypair.publicKey; + + // Load the program + const programPath = new URL( + "./fixtures/account_data_pinocchio_program.so", + // @ts-expect-error + import.meta.url, + ).pathname; + + const litesvm = new LiteSVM(); + litesvm.addProgramFromFile(PROGRAM_ID, programPath); + + const payer = Keypair.generate(); + litesvm.airdrop(payer.publicKey, BigInt(100 * LAMPORTS_PER_SOL)); + + const addressInfoAccount = Keypair.generate(); + + test("Create the address info account", () => { + console.log(`Program Address : ${PROGRAM_ID}`); + console.log(`Payer Address : ${payer.publicKey}`); + console.log(`Address Info Acct : ${addressInfoAccount.publicKey}`); + + const addressInfo: AddressInfo = { + name: "Joe C", + house_number: 136, + street: "Mile High Dr.", + city: "Solana Beach", + }; + + const ix = new TransactionInstruction({ + keys: [ + { + pubkey: addressInfoAccount.publicKey, + isSigner: true, + isWritable: true, + }, + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId: PROGRAM_ID, + data: toBytes(addressInfo), + }); + + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = litesvm.latestBlockhash(); + tx.sign(payer, addressInfoAccount); + + litesvm.sendTransaction(tx); + }); + + test("Read the new account's data", () => { + const accountInfo = litesvm.getAccount(addressInfoAccount.publicKey); + + if (!accountInfo) { + throw new Error("Account not found"); + } + + const readAddressInfo = fromBytes(Buffer.from(accountInfo.data)); + + console.log(`Name : ${readAddressInfo.name}`); + console.log(`House Num: ${readAddressInfo.house_number}`); + console.log(`Street : ${readAddressInfo.street}`); + console.log(`City : ${readAddressInfo.city}`); + }); }); - diff --git a/basics/checking-accounts/anchor/package.json b/basics/checking-accounts/anchor/package.json index 31ba94982..748d2adf5 100644 --- a/basics/checking-accounts/anchor/package.json +++ b/basics/checking-accounts/anchor/package.json @@ -1,18 +1,18 @@ { - "type": "module", - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/web3.js": "^1.98.4" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "anchor-bankrun": "^0.4.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "solana-bankrun": "^0.3.0", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/web3.js": "^1.98.4" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "anchor-bankrun": "^0.4.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "solana-bankrun": "^0.3.0", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/basics/checking-accounts/anchor/tests/bankrun.test.ts b/basics/checking-accounts/anchor/tests/bankrun.test.ts index d47712601..cb9839edf 100644 --- a/basics/checking-accounts/anchor/tests/bankrun.test.ts +++ b/basics/checking-accounts/anchor/tests/bankrun.test.ts @@ -1,63 +1,52 @@ import { describe, it } from "node:test"; import * as anchor from "@anchor-lang/core"; -import { - Keypair, - PublicKey, - SystemProgram, - Transaction, -} from "@solana/web3.js"; +import { Keypair, PublicKey, SystemProgram, Transaction } from "@solana/web3.js"; import { BankrunProvider } from "anchor-bankrun"; import { startAnchor } from "solana-bankrun"; +import IDL from "../target/idl/checking_account_program.json" with { type: "json" }; import type { CheckingAccountProgram } from "../target/types/checking_account_program"; -import IDL from "../target/idl/checking_account_program.json" with { - type: "json", -}; const PROGRAM_ID = new PublicKey(IDL.address); describe("Bankrun example", async () => { - const context = await startAnchor( - "", - [{ name: "checking_account_program", programId: PROGRAM_ID }], - [], - ); - const provider = new BankrunProvider(context); - - const wallet = provider.wallet as anchor.Wallet; - const program = new anchor.Program(IDL, provider); - const client = context.banksClient; - - // We'll create this ahead of time. - // Our program will try to modify it. - const accountToChange = new Keypair(); - // Our program will create this. - const accountToCreate = new Keypair(); - - it("Create an account owned by our program", async () => { - const instruction = SystemProgram.createAccount({ - fromPubkey: provider.wallet.publicKey, - newAccountPubkey: accountToChange.publicKey, - lamports: await provider.connection.getMinimumBalanceForRentExemption(0), - space: 0, - programId: program.programId, // Our program - }); - - const transaction = new Transaction(); - const blockhash = context.lastBlockhash; - - transaction.recentBlockhash = blockhash; - transaction.add(instruction).sign(wallet.payer, accountToChange); - await client.processTransaction(transaction); - }); - - it("Check accounts", async () => { - await program.methods - .checkAccounts() - .accounts({ - payer: wallet.publicKey, - accountToCreate: accountToCreate.publicKey, - accountToChange: accountToChange.publicKey, - }) - .rpc(); - }); + const context = await startAnchor("", [{ name: "checking_account_program", programId: PROGRAM_ID }], []); + const provider = new BankrunProvider(context); + + const wallet = provider.wallet as anchor.Wallet; + const program = new anchor.Program(IDL, provider); + const client = context.banksClient; + + // We'll create this ahead of time. + // Our program will try to modify it. + const accountToChange = new Keypair(); + // Our program will create this. + const accountToCreate = new Keypair(); + + it("Create an account owned by our program", async () => { + const instruction = SystemProgram.createAccount({ + fromPubkey: provider.wallet.publicKey, + newAccountPubkey: accountToChange.publicKey, + lamports: await provider.connection.getMinimumBalanceForRentExemption(0), + space: 0, + programId: program.programId, // Our program + }); + + const transaction = new Transaction(); + const blockhash = context.lastBlockhash; + + transaction.recentBlockhash = blockhash; + transaction.add(instruction).sign(wallet.payer, accountToChange); + await client.processTransaction(transaction); + }); + + it("Check accounts", async () => { + await program.methods + .checkAccounts() + .accounts({ + payer: wallet.publicKey, + accountToCreate: accountToCreate.publicKey, + accountToChange: accountToChange.publicKey, + }) + .rpc(); + }); }); diff --git a/basics/checking-accounts/anchor/tests/test.ts b/basics/checking-accounts/anchor/tests/test.ts index 9b5599e18..514bca172 100644 --- a/basics/checking-accounts/anchor/tests/test.ts +++ b/basics/checking-accounts/anchor/tests/test.ts @@ -1,50 +1,41 @@ import * as anchor from "@anchor-lang/core"; -import { - Keypair, - SystemProgram, - Transaction, - sendAndConfirmTransaction, -} from "@solana/web3.js"; +import { Keypair, SystemProgram, sendAndConfirmTransaction, Transaction } from "@solana/web3.js"; import type { CheckingAccountProgram } from "../target/types/checking_account_program"; describe("Anchor example", () => { - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); - const program = anchor.workspace - .CheckingAccountProgram as anchor.Program; - const wallet = provider.wallet as anchor.Wallet; + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); + const program = anchor.workspace.CheckingAccountProgram as anchor.Program; + const wallet = provider.wallet as anchor.Wallet; - // We'll create this ahead of time. - // Our program will try to modify it. - const accountToChange = new Keypair(); - // Our program will create this. - const accountToCreate = new Keypair(); + // We'll create this ahead of time. + // Our program will try to modify it. + const accountToChange = new Keypair(); + // Our program will create this. + const accountToCreate = new Keypair(); - it("Create an account owned by our program", async () => { - const instruction = SystemProgram.createAccount({ - fromPubkey: provider.wallet.publicKey, - newAccountPubkey: accountToChange.publicKey, - lamports: await provider.connection.getMinimumBalanceForRentExemption(0), - space: 0, - programId: program.programId, // Our program - }); + it("Create an account owned by our program", async () => { + const instruction = SystemProgram.createAccount({ + fromPubkey: provider.wallet.publicKey, + newAccountPubkey: accountToChange.publicKey, + lamports: await provider.connection.getMinimumBalanceForRentExemption(0), + space: 0, + programId: program.programId, // Our program + }); - const transaction = new Transaction().add(instruction); + const transaction = new Transaction().add(instruction); - await sendAndConfirmTransaction(provider.connection, transaction, [ - wallet.payer, - accountToChange, - ]); - }); + await sendAndConfirmTransaction(provider.connection, transaction, [wallet.payer, accountToChange]); + }); - it("Check accounts", async () => { - await program.methods - .checkAccounts() - .accounts({ - payer: wallet.publicKey, - accountToCreate: accountToCreate.publicKey, - accountToChange: accountToChange.publicKey, - }) - .rpc(); - }); + it("Check accounts", async () => { + await program.methods + .checkAccounts() + .accounts({ + payer: wallet.publicKey, + accountToCreate: accountToCreate.publicKey, + accountToChange: accountToChange.publicKey, + }) + .rpc(); + }); }); diff --git a/basics/checking-accounts/native/tests/test.ts b/basics/checking-accounts/native/tests/test.ts index 8e39eea31..a64bd5e0b 100644 --- a/basics/checking-accounts/native/tests/test.ts +++ b/basics/checking-accounts/native/tests/test.ts @@ -1,10 +1,10 @@ -import { describe, test } from 'node:test'; -import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction } from '@solana/web3.js'; -import { start } from 'solana-bankrun'; +import { describe, test } from "node:test"; +import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction } from "@solana/web3.js"; +import { start } from "solana-bankrun"; -describe('Checking accounts', async () => { +describe("Checking accounts", async () => { const PROGRAM_ID = PublicKey.unique(); - const context = await start([{ name: 'checking_accounts_native_program', programId: PROGRAM_ID }], []); + const context = await start([{ name: "checking_accounts_native_program", programId: PROGRAM_ID }], []); const client = context.banksClient; const payer = context.payer; const rent = await client.getRent(); @@ -15,7 +15,7 @@ describe('Checking accounts', async () => { // Our program will create this. const accountToCreate = Keypair.generate(); - test('Create an account owned by our program', async () => { + test("Create an account owned by our program", async () => { const blockhash = context.lastBlockhash; const ix = SystemProgram.createAccount({ fromPubkey: payer.publicKey, @@ -32,7 +32,7 @@ describe('Checking accounts', async () => { await client.processTransaction(tx); }); - test('Check accounts', async () => { + test("Check accounts", async () => { const blockhash = context.lastBlockhash; const ix = new TransactionInstruction({ keys: [ diff --git a/basics/checking-accounts/pinocchio/tests/test.ts b/basics/checking-accounts/pinocchio/tests/test.ts index 7dcc9d8b5..ea6a1a548 100644 --- a/basics/checking-accounts/pinocchio/tests/test.ts +++ b/basics/checking-accounts/pinocchio/tests/test.ts @@ -1,19 +1,10 @@ import { describe, test } from "node:test"; -import { - Keypair, - PublicKey, - SystemProgram, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; +import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction } from "@solana/web3.js"; import { start } from "solana-bankrun"; describe("Checking accounts", async () => { const PROGRAM_ID = PublicKey.unique(); - const context = await start( - [{ name: "checking_accounts_pinocchio_program", programId: PROGRAM_ID }], - [], - ); + const context = await start([{ name: "checking_accounts_pinocchio_program", programId: PROGRAM_ID }], []); const client = context.banksClient; const payer = context.payer; const rent = await client.getRent(); diff --git a/basics/close-account/anchor/migrations/deploy.ts b/basics/close-account/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/basics/close-account/anchor/migrations/deploy.ts +++ b/basics/close-account/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/basics/close-account/anchor/package.json b/basics/close-account/anchor/package.json index 0955a189f..a34261367 100644 --- a/basics/close-account/anchor/package.json +++ b/basics/close-account/anchor/package.json @@ -1,23 +1,23 @@ { - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/web3.js": "^1.98.4", - "litesvm": "^0.4.0" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "anchor-bankrun": "^0.4.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "solana-bankrun": "^0.3.0", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - }, - "type": "module" + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/web3.js": "^1.98.4", + "litesvm": "^0.4.0" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "anchor-bankrun": "^0.4.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "solana-bankrun": "^0.3.0", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + }, + "type": "module" } diff --git a/basics/close-account/anchor/tests/litesvm.test.ts b/basics/close-account/anchor/tests/litesvm.test.ts index 5dead96f1..304620d54 100644 --- a/basics/close-account/anchor/tests/litesvm.test.ts +++ b/basics/close-account/anchor/tests/litesvm.test.ts @@ -1,101 +1,93 @@ import anchor from "@anchor-lang/core"; import { - Keypair, - LAMPORTS_PER_SOL, - PublicKey, - SystemProgram, - Transaction, - TransactionInstruction, + Keypair, + LAMPORTS_PER_SOL, + PublicKey, + SystemProgram, + Transaction, + TransactionInstruction, } from "@solana/web3.js"; import { assert } from "chai"; import { LiteSVM } from "litesvm"; -import IDL from "../target/idl/close_account_program.json" with { - type: "json", -}; +import IDL from "../target/idl/close_account_program.json" with { type: "json" }; describe("LiteSVM: Close an account", () => { - const litesvm = new LiteSVM(); - const programId = new PublicKey(IDL.address); - const payer = Keypair.generate(); - const coder = new anchor.BorshCoder(IDL as anchor.Idl); // For serialization and deserialization + const litesvm = new LiteSVM(); + const programId = new PublicKey(IDL.address); + const payer = Keypair.generate(); + const coder = new anchor.BorshCoder(IDL as anchor.Idl); // For serialization and deserialization - const programPath = new URL( - "../target/deploy/close_account_program.so", - import.meta.url, - ).pathname; - litesvm.addProgramFromFile(programId, programPath); + const programPath = new URL("../target/deploy/close_account_program.so", import.meta.url).pathname; + litesvm.addProgramFromFile(programId, programPath); - litesvm.airdrop(payer.publicKey, BigInt(5 * LAMPORTS_PER_SOL)); + litesvm.airdrop(payer.publicKey, BigInt(5 * LAMPORTS_PER_SOL)); - /** - * Derive the PDA for the user's account. - */ - const [userAccountAddress] = PublicKey.findProgramAddressSync( - [Buffer.from("USER"), payer.publicKey.toBuffer()], - programId, - ); + /** + * Derive the PDA for the user's account. + */ + const [userAccountAddress] = PublicKey.findProgramAddressSync( + [Buffer.from("USER"), payer.publicKey.toBuffer()], + programId, + ); - it("Create an account", () => { - /** - * Instruction data - * Convert into buffer of instruction data - */ - const dataArg = { name: "John Doe" }; - const data = coder.instruction.encode("create_user", dataArg); + it("Create an account", () => { + /** + * Instruction data + * Convert into buffer of instruction data + */ + const dataArg = { name: "John Doe" }; + const data = coder.instruction.encode("create_user", dataArg); - /** - * Create Transactions - */ - const ix = new TransactionInstruction({ - keys: [ - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: userAccountAddress, isSigner: false, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId, - data, - }); + /** + * Create Transactions + */ + const ix = new TransactionInstruction({ + keys: [ + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: userAccountAddress, isSigner: false, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId, + data, + }); - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = litesvm.latestBlockhash(); - tx.sign(payer); - litesvm.sendTransaction(tx); + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = litesvm.latestBlockhash(); + tx.sign(payer); + litesvm.sendTransaction(tx); - /** - * Fetch account - */ - const userAccount = litesvm.getAccount(userAccountAddress); - const user = coder.accounts.decode( - "UserState", - Buffer.from(userAccount.data), - ); - assert.equal(user.name, "John Doe"); - assert.equal(user.user.toBase58(), payer.publicKey.toBase58()); - }); + /** + * Fetch account + */ + const userAccount = litesvm.getAccount(userAccountAddress); + const user = coder.accounts.decode("UserState", Buffer.from(userAccount.data)); + assert.equal(user.name, "John Doe"); + assert.equal(user.user.toBase58(), payer.publicKey.toBase58()); + }); - it("Close an account", () => { - const data = coder.instruction.encode("close_user", {}); + it("Close an account", () => { + const data = coder.instruction.encode("close_user", {}); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: userAccountAddress, isSigner: false, isWritable: true }, - ], - programId, - data, - }); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: userAccountAddress, isSigner: false, isWritable: true }, + ], + programId, + data, + }); - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = litesvm.latestBlockhash(); - tx.sign(payer); - litesvm.sendTransaction(tx); + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = litesvm.latestBlockhash(); + tx.sign(payer); + litesvm.sendTransaction(tx); - /** - * Fetch account - */ - const userAccount = litesvm.getAccount(userAccountAddress); - assert.equal(userAccount, null); - }); + /** + * Fetch account + */ + const userAccount = litesvm.getAccount(userAccountAddress); + assert.equal(userAccount, null); + }); }); diff --git a/basics/close-account/anchor/tests/test.ts b/basics/close-account/anchor/tests/test.ts index 4623c0d19..988ebd5f5 100644 --- a/basics/close-account/anchor/tests/test.ts +++ b/basics/close-account/anchor/tests/test.ts @@ -5,57 +5,54 @@ import { assert } from "chai"; import type { CloseAccountProgram } from "../target/types/close_account_program.ts"; describe("Anchor: Close an account", () => { - /** - * Configure the client to use the local cluster. - */ - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); + /** + * Configure the client to use the local cluster. + */ + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); - const program = anchor.workspace - .CloseAccountProgram as Program; - const payer = provider.wallet as anchor.Wallet; + const program = anchor.workspace.CloseAccountProgram as Program; + const payer = provider.wallet as anchor.Wallet; - /** - * Derive the PDA for the user's account. - */ - const [userAccountAddress] = PublicKey.findProgramAddressSync( - [Buffer.from("USER"), payer.publicKey.toBuffer()], - program.programId, - ); + /** + * Derive the PDA for the user's account. + */ + const [userAccountAddress] = PublicKey.findProgramAddressSync( + [Buffer.from("USER"), payer.publicKey.toBuffer()], + program.programId, + ); - it("Create an account", async () => { - await program.methods - .createUser("John Doe") - .accounts({ - user: payer.publicKey, - userAccount: userAccountAddress, - system_program: SystemProgram.programId, - }) - .rpc(); + it("Create an account", async () => { + await program.methods + .createUser("John Doe") + .accounts({ + user: payer.publicKey, + userAccount: userAccountAddress, + system_program: SystemProgram.programId, + }) + .rpc(); - /** - * Fetch account - */ - const userAccount = - await program.account.userState.fetch(userAccountAddress); - assert.equal(userAccount.name, "John Doe"); - assert.equal(userAccount.user.toBase58(), payer.publicKey.toBase58()); - }); + /** + * Fetch account + */ + const userAccount = await program.account.userState.fetch(userAccountAddress); + assert.equal(userAccount.name, "John Doe"); + assert.equal(userAccount.user.toBase58(), payer.publicKey.toBase58()); + }); - it("Close an account", async () => { - await program.methods - .closeUser() - .accounts({ - user: payer.publicKey, - userAccount: userAccountAddress, - }) - .rpc(); + it("Close an account", async () => { + await program.methods + .closeUser() + .accounts({ + user: payer.publicKey, + userAccount: userAccountAddress, + }) + .rpc(); - /** - * Fetch account - */ - const userAccount = - await program.account.userState.fetchNullable(userAccountAddress); - assert.equal(userAccount, null); - }); + /** + * Fetch account + */ + const userAccount = await program.account.userState.fetchNullable(userAccountAddress); + assert.equal(userAccount, null); + }); }); diff --git a/basics/close-account/anchor/tsconfig.json b/basics/close-account/anchor/tsconfig.json index 88e8865f0..ce454c83b 100644 --- a/basics/close-account/anchor/tsconfig.json +++ b/basics/close-account/anchor/tsconfig.json @@ -1,10 +1,10 @@ { - "compilerOptions": { - "typeRoots": ["./node_modules/@types"], - "lib": ["es2020"], - "module": "nodenext", - "target": "es2020", - "esModuleInterop": true, - "resolveJsonModule": true - } + "compilerOptions": { + "typeRoots": ["./node_modules/@types"], + "lib": ["es2020"], + "module": "nodenext", + "target": "es2020", + "esModuleInterop": true, + "resolveJsonModule": true + } } diff --git a/basics/close-account/native/tests/close-account.test.ts b/basics/close-account/native/tests/close-account.test.ts index cb8640c3d..df253f1fb 100644 --- a/basics/close-account/native/tests/close-account.test.ts +++ b/basics/close-account/native/tests/close-account.test.ts @@ -1,19 +1,22 @@ -import { describe, test } from 'node:test'; -import { PublicKey, Transaction } from '@solana/web3.js'; -import { start } from 'solana-bankrun'; -import { createCloseUserInstruction, createCreateUserInstruction } from '../ts'; +import { describe, test } from "node:test"; +import { PublicKey, Transaction } from "@solana/web3.js"; +import { start } from "solana-bankrun"; +import { createCloseUserInstruction, createCreateUserInstruction } from "../ts"; -describe('Close Account!', async () => { +describe("Close Account!", async () => { const PROGRAM_ID = PublicKey.unique(); - const context = await start([{ name: 'close_account_native_program', programId: PROGRAM_ID }], []); + const context = await start([{ name: "close_account_native_program", programId: PROGRAM_ID }], []); const client = context.banksClient; const payer = context.payer; - const testAccountPublicKey = PublicKey.findProgramAddressSync([Buffer.from('USER'), payer.publicKey.toBuffer()], PROGRAM_ID)[0]; + const testAccountPublicKey = PublicKey.findProgramAddressSync( + [Buffer.from("USER"), payer.publicKey.toBuffer()], + PROGRAM_ID, + )[0]; - test('Create the account', async () => { + test("Create the account", async () => { const blockhash = context.lastBlockhash; - const ix = createCreateUserInstruction(testAccountPublicKey, payer.publicKey, PROGRAM_ID, 'Jacob'); + const ix = createCreateUserInstruction(testAccountPublicKey, payer.publicKey, PROGRAM_ID, "Jacob"); const tx = new Transaction(); tx.recentBlockhash = blockhash; @@ -22,7 +25,7 @@ describe('Close Account!', async () => { await client.processTransaction(tx); }); - test('Close the account', async () => { + test("Close the account", async () => { const blockhash = context.lastBlockhash; const ix = createCloseUserInstruction(testAccountPublicKey, payer.publicKey, PROGRAM_ID); diff --git a/basics/close-account/native/ts/index.ts b/basics/close-account/native/ts/index.ts index 898deed08..110032b71 100644 --- a/basics/close-account/native/ts/index.ts +++ b/basics/close-account/native/ts/index.ts @@ -1,2 +1,2 @@ -export * from './instructions'; -export * from './state'; +export * from "./instructions"; +export * from "./state"; diff --git a/basics/close-account/native/ts/instructions/close.ts b/basics/close-account/native/ts/instructions/close.ts index 697d347bf..3bc4afd37 100644 --- a/basics/close-account/native/ts/instructions/close.ts +++ b/basics/close-account/native/ts/instructions/close.ts @@ -1,7 +1,7 @@ -import { Buffer } from 'node:buffer'; -import { type PublicKey, SystemProgram, TransactionInstruction } from '@solana/web3.js'; -import * as borsh from 'borsh'; -import { MyInstruction } from '.'; +import { Buffer } from "node:buffer"; +import { type PublicKey, SystemProgram, TransactionInstruction } from "@solana/web3.js"; +import * as borsh from "borsh"; +import { MyInstruction } from "."; export class Close { instruction: MyInstruction; @@ -25,13 +25,17 @@ export const CloseSchema = new Map([ [ Close, { - kind: 'struct', - fields: [['instruction', 'u8']], + kind: "struct", + fields: [["instruction", "u8"]], }, ], ]); -export function createCloseUserInstruction(target: PublicKey, payer: PublicKey, programId: PublicKey): TransactionInstruction { +export function createCloseUserInstruction( + target: PublicKey, + payer: PublicKey, + programId: PublicKey, +): TransactionInstruction { const instructionObject = new Close({ instruction: MyInstruction.CloseUser, }); diff --git a/basics/close-account/native/ts/instructions/create.ts b/basics/close-account/native/ts/instructions/create.ts index 100b6cd68..7a18c43ac 100644 --- a/basics/close-account/native/ts/instructions/create.ts +++ b/basics/close-account/native/ts/instructions/create.ts @@ -1,7 +1,7 @@ -import { Buffer } from 'node:buffer'; -import { type PublicKey, SystemProgram, TransactionInstruction } from '@solana/web3.js'; -import * as borsh from 'borsh'; -import { MyInstruction } from '.'; +import { Buffer } from "node:buffer"; +import { type PublicKey, SystemProgram, TransactionInstruction } from "@solana/web3.js"; +import * as borsh from "borsh"; +import { MyInstruction } from "."; export class Create { instruction: MyInstruction; @@ -25,16 +25,21 @@ export const CreateSchema = new Map([ [ Create, { - kind: 'struct', + kind: "struct", fields: [ - ['instruction', 'u8'], - ['name', 'string'], + ["instruction", "u8"], + ["name", "string"], ], }, ], ]); -export function createCreateUserInstruction(target: PublicKey, payer: PublicKey, programId: PublicKey, name: string): TransactionInstruction { +export function createCreateUserInstruction( + target: PublicKey, + payer: PublicKey, + programId: PublicKey, + name: string, +): TransactionInstruction { const instructionObject = new Create({ instruction: MyInstruction.CreateUser, name, diff --git a/basics/close-account/native/ts/state/index.ts b/basics/close-account/native/ts/state/index.ts index 4dad1be41..440a115d4 100644 --- a/basics/close-account/native/ts/state/index.ts +++ b/basics/close-account/native/ts/state/index.ts @@ -1,5 +1,5 @@ -import { Buffer } from 'node:buffer'; -import * as borsh from 'borsh'; +import { Buffer } from "node:buffer"; +import * as borsh from "borsh"; export class User { name: string; @@ -27,8 +27,8 @@ export const UserSchema = new Map([ [ User, { - kind: 'struct', - fields: [['name', 'string']], + kind: "struct", + fields: [["name", "string"]], }, ], ]); diff --git a/basics/close-account/pinocchio/tests/close-account.test.ts b/basics/close-account/pinocchio/tests/close-account.test.ts index e073c28c7..163818817 100644 --- a/basics/close-account/pinocchio/tests/close-account.test.ts +++ b/basics/close-account/pinocchio/tests/close-account.test.ts @@ -1,6 +1,4 @@ -import { describe, test } from "node:test"; -import { PublicKey, Transaction } from "@solana/web3.js"; -import { start } from "solana-bankrun"; +import { describe } from "node:test"; describe("Close Account!", async () => { console.log("Close Account"); diff --git a/basics/counter/anchor/migrations/deploy.ts b/basics/counter/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/basics/counter/anchor/migrations/deploy.ts +++ b/basics/counter/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/basics/counter/anchor/package.json b/basics/counter/anchor/package.json index 21d106e4d..5696f5b0e 100644 --- a/basics/counter/anchor/package.json +++ b/basics/counter/anchor/package.json @@ -1,22 +1,22 @@ { - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/web3.js": "^1.98.4", - "litesvm": "^0.4.0" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - }, - "type": "module" + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/web3.js": "^1.98.4", + "litesvm": "^0.4.0" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + }, + "type": "module" } diff --git a/basics/counter/anchor/tests/litesvm.test.ts b/basics/counter/anchor/tests/litesvm.test.ts index 90e80ad85..0e69f4f8c 100644 --- a/basics/counter/anchor/tests/litesvm.test.ts +++ b/basics/counter/anchor/tests/litesvm.test.ts @@ -1,121 +1,99 @@ import anchor from "@anchor-lang/core"; -import { - Keypair, - PublicKey, - SystemProgram, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; +import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction } from "@solana/web3.js"; import { assert } from "chai"; import { LiteSVM } from "litesvm"; import IDL from "../target/idl/counter_anchor.json" with { type: "json" }; describe("LiteSVM: Counter", () => { - const svm = new LiteSVM(); - const programId = new PublicKey(IDL.address); - const payer = Keypair.generate(); - svm.airdrop(payer.publicKey, BigInt(1000000000)); + const svm = new LiteSVM(); + const programId = new PublicKey(IDL.address); + const payer = Keypair.generate(); + svm.airdrop(payer.publicKey, BigInt(1000000000)); - const coder = new anchor.BorshCoder(IDL as anchor.Idl); - const programPath = new URL( - "../target/deploy/counter_anchor.so", - import.meta.url, - ).pathname; - svm.addProgramFromFile(programId, programPath); + const coder = new anchor.BorshCoder(IDL as anchor.Idl); + const programPath = new URL("../target/deploy/counter_anchor.so", import.meta.url).pathname; + svm.addProgramFromFile(programId, programPath); - /** - * Generate a new keypair for the counter account - */ - const counterKeypair = new Keypair(); + /** + * Generate a new keypair for the counter account + */ + const counterKeypair = new Keypair(); - it("Initialize Counter", () => { - /** - * Instruction data - * Create Transaction - */ - const data = coder.instruction.encode("initialize_counter", {}); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: counterKeypair.publicKey, isSigner: true, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId, - data, - }); + it("Initialize Counter", () => { + /** + * Instruction data + * Create Transaction + */ + const data = coder.instruction.encode("initialize_counter", {}); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: counterKeypair.publicKey, isSigner: true, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId, + data, + }); - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer, counterKeypair); - svm.sendTransaction(tx); + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer, counterKeypair); + svm.sendTransaction(tx); - /** - * Fetch counter account - */ - const counterAccount = svm.getAccount(counterKeypair.publicKey); - const counter = coder.accounts.decode( - "Counter", - Buffer.from(counterAccount.data), - ); + /** + * Fetch counter account + */ + const counterAccount = svm.getAccount(counterKeypair.publicKey); + const counter = coder.accounts.decode("Counter", Buffer.from(counterAccount.data)); - assert.equal(counter.count, 0); - }); + assert.equal(counter.count, 0); + }); - it("Increment Counter", () => { - const data = coder.instruction.encode("increment", {}); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: counterKeypair.publicKey, isSigner: false, isWritable: true }, - ], - programId, - data, - }); + it("Increment Counter", () => { + const data = coder.instruction.encode("increment", {}); + const ix = new TransactionInstruction({ + keys: [{ pubkey: counterKeypair.publicKey, isSigner: false, isWritable: true }], + programId, + data, + }); - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer); - svm.sendTransaction(tx); - svm.expireBlockhash(); + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer); + svm.sendTransaction(tx); + svm.expireBlockhash(); - /** - * Fetch counter account - */ - const counterAccount = svm.getAccount(counterKeypair.publicKey); - const counter = coder.accounts.decode( - "Counter", - Buffer.from(counterAccount.data), - ); + /** + * Fetch counter account + */ + const counterAccount = svm.getAccount(counterKeypair.publicKey); + const counter = coder.accounts.decode("Counter", Buffer.from(counterAccount.data)); - assert.equal(counter.count, 1); - }); + assert.equal(counter.count, 1); + }); - it("Increment Counter Again", () => { - const data = coder.instruction.encode("increment", {}); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: counterKeypair.publicKey, isSigner: false, isWritable: true }, - ], - programId, - data, - }); + it("Increment Counter Again", () => { + const data = coder.instruction.encode("increment", {}); + const ix = new TransactionInstruction({ + keys: [{ pubkey: counterKeypair.publicKey, isSigner: false, isWritable: true }], + programId, + data, + }); - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer); - svm.sendTransaction(tx); + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer); + svm.sendTransaction(tx); - /** - * Fetch counter account - */ - const counterAccount = svm.getAccount(counterKeypair.publicKey); - const counter = coder.accounts.decode( - "Counter", - Buffer.from(counterAccount.data), - ); + /** + * Fetch counter account + */ + const counterAccount = svm.getAccount(counterKeypair.publicKey); + const counter = coder.accounts.decode("Counter", Buffer.from(counterAccount.data)); - assert.equal(counter.count, 2); - }); + assert.equal(counter.count, 2); + }); }); diff --git a/basics/counter/anchor/tests/test.ts b/basics/counter/anchor/tests/test.ts index 12f93fde9..703e04bac 100644 --- a/basics/counter/anchor/tests/test.ts +++ b/basics/counter/anchor/tests/test.ts @@ -5,59 +5,44 @@ import { assert } from "chai"; import type { CounterAnchor } from "../target/types/counter_anchor.ts"; describe("Anchor: Counter", () => { - // Configure the client to use the local cluster. - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); - const payer = provider.wallet as anchor.Wallet; - - const program = anchor.workspace.CounterAnchor as Program; - - // Generate a new keypair for the counter account - const counterKeypair = new Keypair(); - - it("Initialize Counter", async () => { - await program.methods - .initializeCounter() - .accounts({ - counter: counterKeypair.publicKey, - payer: payer.publicKey, - }) - .signers([counterKeypair]) - .rpc(); - - const currentCount = await program.account.counter.fetch( - counterKeypair.publicKey, - ); - - assert( - currentCount.count.toNumber() === 0, - "Expected initialized count to be 0", - ); - }); - - it("Increment Counter", async () => { - await program.methods - .increment() - .accounts({ counter: counterKeypair.publicKey }) - .rpc(); - - const currentCount = await program.account.counter.fetch( - counterKeypair.publicKey, - ); - - assert(currentCount.count.toNumber() === 1, "Expected count to be 1"); - }); - - it("Increment Counter Again", async () => { - await program.methods - .increment() - .accounts({ counter: counterKeypair.publicKey }) - .rpc(); - - const currentCount = await program.account.counter.fetch( - counterKeypair.publicKey, - ); - - assert(currentCount.count.toNumber() === 2, "Expected count to be 2"); - }); + // Configure the client to use the local cluster. + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); + const payer = provider.wallet as anchor.Wallet; + + const program = anchor.workspace.CounterAnchor as Program; + + // Generate a new keypair for the counter account + const counterKeypair = new Keypair(); + + it("Initialize Counter", async () => { + await program.methods + .initializeCounter() + .accounts({ + counter: counterKeypair.publicKey, + payer: payer.publicKey, + }) + .signers([counterKeypair]) + .rpc(); + + const currentCount = await program.account.counter.fetch(counterKeypair.publicKey); + + assert(currentCount.count.toNumber() === 0, "Expected initialized count to be 0"); + }); + + it("Increment Counter", async () => { + await program.methods.increment().accounts({ counter: counterKeypair.publicKey }).rpc(); + + const currentCount = await program.account.counter.fetch(counterKeypair.publicKey); + + assert(currentCount.count.toNumber() === 1, "Expected count to be 1"); + }); + + it("Increment Counter Again", async () => { + await program.methods.increment().accounts({ counter: counterKeypair.publicKey }).rpc(); + + const currentCount = await program.account.counter.fetch(counterKeypair.publicKey); + + assert(currentCount.count.toNumber() === 2, "Expected count to be 2"); + }); }); diff --git a/basics/counter/anchor/tsconfig.json b/basics/counter/anchor/tsconfig.json index fdf5c04de..395d18165 100644 --- a/basics/counter/anchor/tsconfig.json +++ b/basics/counter/anchor/tsconfig.json @@ -1,10 +1,10 @@ { - "compilerOptions": { - "types": ["mocha", "chai"], - "typeRoots": ["./node_modules/@types"], - "lib": ["es2020"], - "module": "nodenext", - "target": "es2020", - "esModuleInterop": true - } + "compilerOptions": { + "types": ["mocha", "chai"], + "typeRoots": ["./node_modules/@types"], + "lib": ["es2020"], + "module": "nodenext", + "target": "es2020", + "esModuleInterop": true + } } diff --git a/basics/counter/mpl-stack/.solitarc.js b/basics/counter/mpl-stack/.solitarc.js index 74dc762c5..8ea5faec3 100644 --- a/basics/counter/mpl-stack/.solitarc.js +++ b/basics/counter/mpl-stack/.solitarc.js @@ -1,14 +1,14 @@ // @ts-check -const path = require('node:path'); +const path = require("node:path"); const programDir = path.join(__dirname); -const idlDir = path.join(__dirname, 'idl'); -const sdkDir = path.join(__dirname, 'ts', 'generated'); -const binaryInstallDir = path.join(__dirname, 'target', 'solita'); +const idlDir = path.join(__dirname, "idl"); +const sdkDir = path.join(__dirname, "ts", "generated"); +const binaryInstallDir = path.join(__dirname, "target", "solita"); module.exports = { - idlGenerator: 'shank', - programName: 'counter_mpl_stack', - programId: 'Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS', + idlGenerator: "shank", + programName: "counter_mpl_stack", + programId: "Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS", idlDir, sdkDir, binaryInstallDir, diff --git a/basics/counter/mpl-stack/jest.config.js b/basics/counter/mpl-stack/jest.config.js index 3943c3dbb..4dd7c478d 100644 --- a/basics/counter/mpl-stack/jest.config.js +++ b/basics/counter/mpl-stack/jest.config.js @@ -1,6 +1,6 @@ module.exports = { - preset: 'ts-jest/presets/default', - testEnvironment: 'node', + preset: "ts-jest/presets/default", + testEnvironment: "node", testTimeout: 100000, - resolver: 'ts-jest-resolver', + resolver: "ts-jest-resolver", }; diff --git a/basics/counter/mpl-stack/tests/counter.test.ts b/basics/counter/mpl-stack/tests/counter.test.ts index c3c3c99f1..dc345a80b 100644 --- a/basics/counter/mpl-stack/tests/counter.test.ts +++ b/basics/counter/mpl-stack/tests/counter.test.ts @@ -1,4 +1,4 @@ -import type { bignum } from '@metaplex-foundation/beet'; +import type { bignum } from "@metaplex-foundation/beet"; import { Connection, Keypair, @@ -7,20 +7,20 @@ import { sendAndConfirmTransaction, Transaction, type TransactionInstruction, -} from '@solana/web3.js'; -import { BN } from 'bn.js'; -import { assert } from 'chai'; +} from "@solana/web3.js"; +import { BN } from "bn.js"; +import { assert } from "chai"; -import { Counter, createIncrementInstruction, PROGRAM_ID } from '../ts'; +import { Counter, createIncrementInstruction, PROGRAM_ID } from "../ts"; function convertBignumToNumber(bignum: bignum): number { return new BN(bignum).toNumber(); } -describe('Counter Solana Native', () => { - const connection = new Connection('http://localhost:8899'); +describe("Counter Solana Native", () => { + const connection = new Connection("http://localhost:8899"); - it('Test allocate counter + increment tx', async () => { + it("Test allocate counter + increment tx", async () => { // Randomly generate our wallet const payerKeypair = Keypair.generate(); const payer = payerKeypair.publicKey; @@ -50,17 +50,20 @@ describe('Counter Solana Native', () => { tx.feePayer = payer; // Fetch a "timestamp" so validators know this is a recent transaction - tx.recentBlockhash = (await connection.getLatestBlockhash('confirmed')).blockhash; + tx.recentBlockhash = (await connection.getLatestBlockhash("confirmed")).blockhash; // Send transaction to network (local network) - await sendAndConfirmTransaction(connection, tx, [payerKeypair, counterKeypair], { skipPreflight: true, commitment: 'confirmed' }); + await sendAndConfirmTransaction(connection, tx, [payerKeypair, counterKeypair], { + skipPreflight: true, + commitment: "confirmed", + }); // Get the counter account info from network const count = (await Counter.fromAccountAddress(connection, counter)).count; - assert(new BN(count).toNumber() === 1, 'Expected count to have been 1'); + assert(new BN(count).toNumber() === 1, "Expected count to have been 1"); console.log(`[alloc+increment] count is: ${count}`); }); - it('Test allocate tx and increment tx', async () => { + it("Test allocate tx and increment tx", async () => { const payerKeypair = Keypair.generate(); const payer = payerKeypair.publicKey; @@ -79,11 +82,14 @@ describe('Counter Solana Native', () => { }); let tx = new Transaction().add(allocIx); tx.feePayer = payer; - tx.recentBlockhash = (await connection.getLatestBlockhash('confirmed')).blockhash; - await sendAndConfirmTransaction(connection, tx, [payerKeypair, counterKeypair], { skipPreflight: true, commitment: 'confirmed' }); + tx.recentBlockhash = (await connection.getLatestBlockhash("confirmed")).blockhash; + await sendAndConfirmTransaction(connection, tx, [payerKeypair, counterKeypair], { + skipPreflight: true, + commitment: "confirmed", + }); let count = (await Counter.fromAccountAddress(connection, counter)).count; - assert(convertBignumToNumber(count) === 0, 'Expected count to have been 0'); + assert(convertBignumToNumber(count) === 0, "Expected count to have been 0"); console.log(`[allocate] count is: ${count}`); // Check increment tx @@ -92,14 +98,14 @@ describe('Counter Solana Native', () => { }); tx = new Transaction().add(incrementIx); tx.feePayer = payer; - tx.recentBlockhash = (await connection.getLatestBlockhash('confirmed')).blockhash; + tx.recentBlockhash = (await connection.getLatestBlockhash("confirmed")).blockhash; await sendAndConfirmTransaction(connection, tx, [payerKeypair], { skipPreflight: true, - commitment: 'confirmed', + commitment: "confirmed", }); count = (await Counter.fromAccountAddress(connection, counter)).count; - assert(convertBignumToNumber(count) === 1, 'Expected count to have been 1'); + assert(convertBignumToNumber(count) === 1, "Expected count to have been 1"); console.log(`[increment] count is: ${count}`); }); }); diff --git a/basics/counter/mpl-stack/ts/generated/accounts/Counter.ts b/basics/counter/mpl-stack/ts/generated/accounts/Counter.ts index 8595a99e1..159e2972f 100644 --- a/basics/counter/mpl-stack/ts/generated/accounts/Counter.ts +++ b/basics/counter/mpl-stack/ts/generated/accounts/Counter.ts @@ -5,9 +5,9 @@ * See: https://github.com/metaplex-foundation/solita */ -import * as beet from '@metaplex-foundation/beet'; -import * as beetSolana from '@metaplex-foundation/beet-solana'; -import * as web3 from '@solana/web3.js'; +import * as beet from "@metaplex-foundation/beet"; +import * as beetSolana from "@metaplex-foundation/beet-solana"; +import * as web3 from "@solana/web3.js"; /** * Arguments used to create {@link Counter} @@ -50,7 +50,7 @@ export class Counter implements CounterArgs { */ static async fromAccountAddress(connection: web3.Connection, address: web3.PublicKey): Promise { const accountInfo = await connection.getAccountInfo(address, { - commitment: 'confirmed', + commitment: "confirmed", }); if (accountInfo == null) { throw new Error(`Unable to find Counter account at ${address}`); @@ -64,7 +64,7 @@ export class Counter implements CounterArgs { * * @param programId - the program that owns the accounts we are filtering */ - static gpaBuilder(programId: web3.PublicKey = new web3.PublicKey('Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS')) { + static gpaBuilder(programId: web3.PublicKey = new web3.PublicKey("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS")) { return beetSolana.GpaBuilder.fromStruct(programId, counterBeet); } @@ -98,7 +98,10 @@ export class Counter implements CounterArgs { * * @param connection used to retrieve the rent exemption information */ - static async getMinimumBalanceForRentExemption(connection: web3.Connection, commitment?: web3.Commitment): Promise { + static async getMinimumBalanceForRentExemption( + connection: web3.Connection, + commitment?: web3.Commitment, + ): Promise { return connection.getMinimumBalanceForRentExemption(Counter.byteSize, commitment); } @@ -118,7 +121,7 @@ export class Counter implements CounterArgs { return { count: (() => { const x = <{ toNumber: () => number }>this.count; - if (typeof x.toNumber === 'function') { + if (typeof x.toNumber === "function") { try { return x.toNumber(); } catch (_) { @@ -135,4 +138,8 @@ export class Counter implements CounterArgs { * @category Accounts * @category generated */ -export const counterBeet = new beet.BeetStruct([['count', beet.u64]], Counter.fromArgs, 'Counter'); +export const counterBeet = new beet.BeetStruct( + [["count", beet.u64]], + Counter.fromArgs, + "Counter", +); diff --git a/basics/counter/mpl-stack/ts/generated/accounts/index.ts b/basics/counter/mpl-stack/ts/generated/accounts/index.ts index cea7bf897..4a7382443 100644 --- a/basics/counter/mpl-stack/ts/generated/accounts/index.ts +++ b/basics/counter/mpl-stack/ts/generated/accounts/index.ts @@ -1,5 +1,5 @@ -export * from './Counter'; +export * from "./Counter"; -import { Counter } from './Counter'; +import { Counter } from "./Counter"; export const accountProviders = { Counter }; diff --git a/basics/counter/mpl-stack/ts/generated/index.ts b/basics/counter/mpl-stack/ts/generated/index.ts index 1167eac99..8a3d97033 100644 --- a/basics/counter/mpl-stack/ts/generated/index.ts +++ b/basics/counter/mpl-stack/ts/generated/index.ts @@ -1,7 +1,7 @@ -import { PublicKey } from '@solana/web3.js'; +import { PublicKey } from "@solana/web3.js"; -export * from './accounts'; -export * from './instructions'; +export * from "./accounts"; +export * from "./instructions"; /** * Program address @@ -9,7 +9,7 @@ export * from './instructions'; * @category constants * @category generated */ -export const PROGRAM_ADDRESS = 'Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS'; +export const PROGRAM_ADDRESS = "Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS"; /** * Program public key diff --git a/basics/counter/mpl-stack/ts/generated/instructions/Increment.ts b/basics/counter/mpl-stack/ts/generated/instructions/Increment.ts index 9f9e542fa..afc814560 100644 --- a/basics/counter/mpl-stack/ts/generated/instructions/Increment.ts +++ b/basics/counter/mpl-stack/ts/generated/instructions/Increment.ts @@ -5,8 +5,8 @@ * See: https://github.com/metaplex-foundation/solita */ -import * as beet from '@metaplex-foundation/beet'; -import * as web3 from '@solana/web3.js'; +import * as beet from "@metaplex-foundation/beet"; +import * as web3 from "@solana/web3.js"; /** * @category Instructions @@ -15,7 +15,7 @@ import * as web3 from '@solana/web3.js'; */ export const IncrementStruct = new beet.BeetArgsStruct<{ instructionDiscriminator: number; -}>([['instructionDiscriminator', beet.u8]], 'IncrementInstructionArgs'); +}>([["instructionDiscriminator", beet.u8]], "IncrementInstructionArgs"); /** * Accounts required by the _Increment_ instruction * @@ -40,7 +40,7 @@ export const incrementInstructionDiscriminator = 0; */ export function createIncrementInstruction( accounts: IncrementInstructionAccounts, - programId = new web3.PublicKey('Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS'), + programId = new web3.PublicKey("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS"), ) { const [data] = IncrementStruct.serialize({ instructionDiscriminator: incrementInstructionDiscriminator, diff --git a/basics/counter/mpl-stack/ts/generated/instructions/index.ts b/basics/counter/mpl-stack/ts/generated/instructions/index.ts index b9941ec47..84936e742 100644 --- a/basics/counter/mpl-stack/ts/generated/instructions/index.ts +++ b/basics/counter/mpl-stack/ts/generated/instructions/index.ts @@ -1 +1 @@ -export * from './Increment'; +export * from "./Increment"; diff --git a/basics/counter/mpl-stack/ts/index.ts b/basics/counter/mpl-stack/ts/index.ts index 69e4e4eb8..e84c86c64 100644 --- a/basics/counter/mpl-stack/ts/index.ts +++ b/basics/counter/mpl-stack/ts/index.ts @@ -1 +1 @@ -export * from './generated'; +export * from "./generated"; diff --git a/basics/counter/native/tests/counter.test.ts b/basics/counter/native/tests/counter.test.ts index 44c2056bf..97784546b 100644 --- a/basics/counter/native/tests/counter.test.ts +++ b/basics/counter/native/tests/counter.test.ts @@ -1,19 +1,19 @@ -import { describe, test } from 'node:test'; -import { Keypair, SystemProgram, Transaction, type TransactionInstruction } from '@solana/web3.js'; -import { assert } from 'chai'; -import { start } from 'solana-bankrun'; -import { COUNTER_ACCOUNT_SIZE, createIncrementInstruction, deserializeCounterAccount, PROGRAM_ID } from '../ts'; +import { describe, test } from "node:test"; +import { Keypair, SystemProgram, Transaction, type TransactionInstruction } from "@solana/web3.js"; +import { assert } from "chai"; +import { start } from "solana-bankrun"; +import { COUNTER_ACCOUNT_SIZE, createIncrementInstruction, deserializeCounterAccount, PROGRAM_ID } from "../ts"; -describe('Counter Solana Native', async () => { +describe("Counter Solana Native", async () => { // Randomly generate the program keypair and load the program to solana-bankrun - const context = await start([{ name: 'counter_solana_native', programId: PROGRAM_ID }], []); + const context = await start([{ name: "counter_solana_native", programId: PROGRAM_ID }], []); const client = context.banksClient; // Get the payer keypair from the context, this will be used to sign transactions with enough lamports const payer = context.payer; // Get the rent object to calculate rent for the accounts const rent = await client.getRent(); - test('Test allocate counter + increment tx', async () => { + test("Test allocate counter + increment tx", async () => { // Randomly generate the account key // to sign for setting up the Counter state const counterKeypair = Keypair.generate(); @@ -45,15 +45,15 @@ describe('Counter Solana Native', async () => { // Get the counter account info from network const counterAccountInfo = await client.getAccount(counter); - assert(counterAccountInfo, 'Expected counter account to have been created'); + assert(counterAccountInfo, "Expected counter account to have been created"); // Deserialize the counter & check count has been incremented const counterAccount = deserializeCounterAccount(Buffer.from(counterAccountInfo.data)); - assert(counterAccount.count.toNumber() === 1, 'Expected count to have been 1'); + assert(counterAccount.count.toNumber() === 1, "Expected count to have been 1"); console.log(`[alloc+increment] count is: ${counterAccount.count.toNumber()}`); }); - test('Test allocate tx and increment tx', async () => { + test("Test allocate tx and increment tx", async () => { const counterKeypair = Keypair.generate(); const counter = counterKeypair.publicKey; @@ -74,10 +74,10 @@ describe('Counter Solana Native', async () => { await client.processTransaction(tx); let counterAccountInfo = await client.getAccount(counter); - assert(counterAccountInfo, 'Expected counter account to have been created'); + assert(counterAccountInfo, "Expected counter account to have been created"); let counterAccount = deserializeCounterAccount(Buffer.from(counterAccountInfo.data)); - assert(counterAccount.count.toNumber() === 0, 'Expected count to have been 0'); + assert(counterAccount.count.toNumber() === 0, "Expected count to have been 0"); console.log(`[allocate] count is: ${counterAccount.count.toNumber()}`); // Check increment tx @@ -90,10 +90,10 @@ describe('Counter Solana Native', async () => { await client.processTransaction(tx); counterAccountInfo = await client.getAccount(counter); - assert(counterAccountInfo, 'Expected counter account to have been created'); + assert(counterAccountInfo, "Expected counter account to have been created"); counterAccount = deserializeCounterAccount(Buffer.from(counterAccountInfo.data)); - assert(counterAccount.count.toNumber() === 1, 'Expected count to have been 1'); + assert(counterAccount.count.toNumber() === 1, "Expected count to have been 1"); console.log(`[increment] count is: ${counterAccount.count.toNumber()}`); }); }); diff --git a/basics/counter/native/ts/accounts/counter.ts b/basics/counter/native/ts/accounts/counter.ts index 04b7f4844..e89747f9d 100644 --- a/basics/counter/native/ts/accounts/counter.ts +++ b/basics/counter/native/ts/accounts/counter.ts @@ -1,4 +1,4 @@ -import BN from 'bn.js'; +import BN from "bn.js"; export type Counter = { count: BN; @@ -8,10 +8,10 @@ export const COUNTER_ACCOUNT_SIZE = 8; export function deserializeCounterAccount(data: Buffer): Counter { if (data.byteLength !== 8) { - throw Error('Need exactly 8 bytes to deserialize counter'); + throw Error("Need exactly 8 bytes to deserialize counter"); } return { - count: new BN(data, 'le'), + count: new BN(data, "le"), }; } diff --git a/basics/counter/native/ts/accounts/index.ts b/basics/counter/native/ts/accounts/index.ts index 0ab63758b..bd1575cbc 100644 --- a/basics/counter/native/ts/accounts/index.ts +++ b/basics/counter/native/ts/accounts/index.ts @@ -1 +1 @@ -export * from './counter'; +export * from "./counter"; diff --git a/basics/counter/native/ts/index.ts b/basics/counter/native/ts/index.ts index 2322a115f..b353a01ff 100644 --- a/basics/counter/native/ts/index.ts +++ b/basics/counter/native/ts/index.ts @@ -1,6 +1,6 @@ -import { PublicKey } from '@solana/web3.js'; +import { PublicKey } from "@solana/web3.js"; -export * from './accounts'; -export * from './instructions'; +export * from "./accounts"; +export * from "./instructions"; -export const PROGRAM_ID = new PublicKey('Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS'); +export const PROGRAM_ID = new PublicKey("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS"); diff --git a/basics/counter/native/ts/instructions/createIncrementInstruction.ts b/basics/counter/native/ts/instructions/createIncrementInstruction.ts index 6e0bf48c4..b7290acf7 100644 --- a/basics/counter/native/ts/instructions/createIncrementInstruction.ts +++ b/basics/counter/native/ts/instructions/createIncrementInstruction.ts @@ -1,5 +1,5 @@ -import { type PublicKey, TransactionInstruction } from '@solana/web3.js'; -import { PROGRAM_ID } from '../'; +import { type PublicKey, TransactionInstruction } from "@solana/web3.js"; +import { PROGRAM_ID } from "../"; export type IncrementInstructionAccounts = { counter: PublicKey; diff --git a/basics/counter/native/ts/instructions/index.ts b/basics/counter/native/ts/instructions/index.ts index a0249a40c..618dcd823 100644 --- a/basics/counter/native/ts/instructions/index.ts +++ b/basics/counter/native/ts/instructions/index.ts @@ -1 +1 @@ -export * from './createIncrementInstruction'; +export * from "./createIncrementInstruction"; diff --git a/basics/counter/pinocchio/tests/counter.test.ts b/basics/counter/pinocchio/tests/counter.test.ts index c8ddf656f..a8e57d960 100644 --- a/basics/counter/pinocchio/tests/counter.test.ts +++ b/basics/counter/pinocchio/tests/counter.test.ts @@ -1,12 +1,4 @@ -import { describe, test } from "node:test"; -import { - Keypair, - SystemProgram, - Transaction, - type TransactionInstruction, -} from "@solana/web3.js"; -import { assert } from "chai"; -import { start } from "solana-bankrun"; +import { describe } from "node:test"; describe("Counter Solana Pinocchio", async () => { console.log("Counter Solana Pinocchio"); diff --git a/basics/create-account/anchor/package.json b/basics/create-account/anchor/package.json index 0432a3a0d..b20a6eca1 100644 --- a/basics/create-account/anchor/package.json +++ b/basics/create-account/anchor/package.json @@ -1,17 +1,17 @@ { - "type": "module", - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/web3.js": "^1.98.4", - "litesvm": "^0.4.0" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.4.1", - "mocha": "^9.0.3", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/web3.js": "^1.98.4", + "litesvm": "^0.4.0" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.4.1", + "mocha": "^9.0.3", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/basics/create-account/anchor/tests/litesvm.test.ts b/basics/create-account/anchor/tests/litesvm.test.ts index 36053080e..5cefb6604 100644 --- a/basics/create-account/anchor/tests/litesvm.test.ts +++ b/basics/create-account/anchor/tests/litesvm.test.ts @@ -1,64 +1,53 @@ import anchor from "@anchor-lang/core"; -import { - Keypair, - PublicKey, - SystemProgram, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; +import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction } from "@solana/web3.js"; import { assert } from "chai"; import { LiteSVM } from "litesvm"; -import IDL from "../target/idl/create_system_account.json" with { - type: "json", -}; +import IDL from "../target/idl/create_system_account.json" with { type: "json" }; describe("LiteSVM: Create a system account", () => { - const svm = new LiteSVM(); - const programId = new PublicKey(IDL.address); - const payer = Keypair.generate(); - svm.airdrop(payer.publicKey, BigInt(1000000000)); + const svm = new LiteSVM(); + const programId = new PublicKey(IDL.address); + const payer = Keypair.generate(); + svm.airdrop(payer.publicKey, BigInt(1000000000)); - const coder = new anchor.BorshCoder(IDL as anchor.Idl); - const programPath = new URL( - "../target/deploy/create_system_account.so", - import.meta.url, - ).pathname; - svm.addProgramFromFile(programId, programPath); + const coder = new anchor.BorshCoder(IDL as anchor.Idl); + const programPath = new URL("../target/deploy/create_system_account.so", import.meta.url).pathname; + svm.addProgramFromFile(programId, programPath); - it("Create the account", () => { - /** - * Generate a new keypair for the new account - */ - const newKeypair = new Keypair(); - /** - * Instruction data - * Create Transaction - * Send Transaction - */ - const data = coder.instruction.encode("create_system_account", {}); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: newKeypair.publicKey, isSigner: true, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId, - data, - }); + it("Create the account", () => { + /** + * Generate a new keypair for the new account + */ + const newKeypair = new Keypair(); + /** + * Instruction data + * Create Transaction + * Send Transaction + */ + const data = coder.instruction.encode("create_system_account", {}); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: newKeypair.publicKey, isSigner: true, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId, + data, + }); - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer, newKeypair); - svm.sendTransaction(tx); + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer, newKeypair); + svm.sendTransaction(tx); - /** - * Fetch account - * Check its lamports - * */ - const lamports = svm.minimumBalanceForRentExemption(0n); - const accountInfo = svm.getAccount(newKeypair.publicKey); + /** + * Fetch account + * Check its lamports + * */ + const lamports = svm.minimumBalanceForRentExemption(0n); + const accountInfo = svm.getAccount(newKeypair.publicKey); - assert(Number(lamports) === accountInfo.lamports); - }); + assert(Number(lamports) === accountInfo.lamports); + }); }); diff --git a/basics/create-account/anchor/tests/test.ts b/basics/create-account/anchor/tests/test.ts index 57a3cc900..436b16613 100644 --- a/basics/create-account/anchor/tests/test.ts +++ b/basics/create-account/anchor/tests/test.ts @@ -4,31 +4,30 @@ import { assert } from "chai"; import type { CreateSystemAccount } from "../target/types/create_system_account.ts"; describe("Anchor: Create a system account", () => { - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); - const wallet = provider.wallet as anchor.Wallet; - const connection = provider.connection; - const program = anchor.workspace - .CreateSystemAccount as anchor.Program; + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); + const wallet = provider.wallet as anchor.Wallet; + const connection = provider.connection; + const program = anchor.workspace.CreateSystemAccount as anchor.Program; - it("Create the account", async () => { - // Generate a new keypair for the new account - const newKeypair = new Keypair(); + it("Create the account", async () => { + // Generate a new keypair for the new account + const newKeypair = new Keypair(); - await program.methods - .createSystemAccount() - .accounts({ - payer: wallet.publicKey, - newAccount: newKeypair.publicKey, - }) - .signers([newKeypair]) - .rpc(); + await program.methods + .createSystemAccount() + .accounts({ + payer: wallet.publicKey, + newAccount: newKeypair.publicKey, + }) + .signers([newKeypair]) + .rpc(); - // Minimum balance for rent exemption for new account - const lamports = await connection.getMinimumBalanceForRentExemption(0); + // Minimum balance for rent exemption for new account + const lamports = await connection.getMinimumBalanceForRentExemption(0); - // Check that the account was created - const accountInfo = await connection.getAccountInfo(newKeypair.publicKey); - assert(accountInfo.lamports === lamports); - }); + // Check that the account was created + const accountInfo = await connection.getAccountInfo(newKeypair.publicKey); + assert(accountInfo.lamports === lamports); + }); }); diff --git a/basics/create-account/anchor/tsconfig.json b/basics/create-account/anchor/tsconfig.json index fdf5c04de..395d18165 100644 --- a/basics/create-account/anchor/tsconfig.json +++ b/basics/create-account/anchor/tsconfig.json @@ -1,10 +1,10 @@ { - "compilerOptions": { - "types": ["mocha", "chai"], - "typeRoots": ["./node_modules/@types"], - "lib": ["es2020"], - "module": "nodenext", - "target": "es2020", - "esModuleInterop": true - } + "compilerOptions": { + "types": ["mocha", "chai"], + "typeRoots": ["./node_modules/@types"], + "lib": ["es2020"], + "module": "nodenext", + "target": "es2020", + "esModuleInterop": true + } } diff --git a/basics/create-account/native/tests/test.ts b/basics/create-account/native/tests/test.ts index 4c1068abb..0bc801bdd 100644 --- a/basics/create-account/native/tests/test.ts +++ b/basics/create-account/native/tests/test.ts @@ -1,4 +1,4 @@ -import { describe, test } from 'node:test'; +import { describe, test } from "node:test"; import { Keypair, LAMPORTS_PER_SOL, @@ -6,20 +6,17 @@ import { SystemProgram, Transaction, TransactionInstruction, -} from '@solana/web3.js'; -import { start } from 'solana-bankrun'; +} from "@solana/web3.js"; +import { start } from "solana-bankrun"; -describe('Create a system account', async () => { +describe("Create a system account", async () => { const PROGRAM_ID = PublicKey.unique(); - const context = await start( - [{ name: 'create_account_program', programId: PROGRAM_ID }], - [], - ); + const context = await start([{ name: "create_account_program", programId: PROGRAM_ID }], []); const client = context.banksClient; const payer = context.payer; - test('Create the account via a cross program invocation', async () => { + test("Create the account via a cross program invocation", async () => { const newKeypair = Keypair.generate(); const ix = new TransactionInstruction({ @@ -40,11 +37,11 @@ describe('Create a system account', async () => { await client.processTransaction(tx); // Verify the account was created - const accountInfo = await client.getAccount(newKeypair.publicKey); + const _accountInfo = await client.getAccount(newKeypair.publicKey); console.log(`Account with public key ${newKeypair.publicKey} successfully created via CPI`); }); - test('Create the account via direct call to system program', async () => { + test("Create the account via direct call to system program", async () => { const newKeypair = Keypair.generate(); const ix = SystemProgram.createAccount({ @@ -63,7 +60,7 @@ describe('Create a system account', async () => { await client.processTransaction(tx); // Verify the account was created - const accountInfo = await client.getAccount(newKeypair.publicKey); + const _accountInfo = await client.getAccount(newKeypair.publicKey); console.log(`Account with public key ${newKeypair.publicKey} successfully created`); }); }); diff --git a/basics/create-account/pinocchio/tests/test.ts b/basics/create-account/pinocchio/tests/test.ts index 3091b46e3..317ed75e1 100644 --- a/basics/create-account/pinocchio/tests/test.ts +++ b/basics/create-account/pinocchio/tests/test.ts @@ -11,10 +11,7 @@ import { start } from "solana-bankrun"; describe("Create a system account", async () => { const PROGRAM_ID = PublicKey.unique(); - const context = await start( - [{ name: "create_account_pinocchio_program", programId: PROGRAM_ID }], - [], - ); + const context = await start([{ name: "create_account_pinocchio_program", programId: PROGRAM_ID }], []); const client = context.banksClient; const payer = context.payer; @@ -56,8 +53,6 @@ describe("Create a system account", async () => { tx.add(ix).sign(payer, newKeypair); await client.processTransaction(tx); - console.log( - `Account with public key ${newKeypair.publicKey} successfully created`, - ); + console.log(`Account with public key ${newKeypair.publicKey} successfully created`); }); }); diff --git a/basics/cross-program-invocation/anchor/migrations/deploy.ts b/basics/cross-program-invocation/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/basics/cross-program-invocation/anchor/migrations/deploy.ts +++ b/basics/cross-program-invocation/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/basics/cross-program-invocation/anchor/package.json b/basics/cross-program-invocation/anchor/package.json index 6856081db..13909a394 100644 --- a/basics/cross-program-invocation/anchor/package.json +++ b/basics/cross-program-invocation/anchor/package.json @@ -1,22 +1,22 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/web3.js": "^1.98.4", - "litesvm": "^0.4.0" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/web3.js": "^1.98.4", + "litesvm": "^0.4.0" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/basics/cross-program-invocation/anchor/tests/litesvm.test.ts b/basics/cross-program-invocation/anchor/tests/litesvm.test.ts index dcd966ddb..eb00f5312 100644 --- a/basics/cross-program-invocation/anchor/tests/litesvm.test.ts +++ b/basics/cross-program-invocation/anchor/tests/litesvm.test.ts @@ -1,152 +1,135 @@ import anchor from "@anchor-lang/core"; -import { - Keypair, - PublicKey, - SystemProgram, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; +import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction } from "@solana/web3.js"; import { assert } from "chai"; import { LiteSVM } from "litesvm"; import HAND_IDL from "../target/idl/hand.json" with { type: "json" }; import LEVER_IDL from "../target/idl/lever.json" with { type: "json" }; describe("LiteSVM: CPI", () => { - const svm = new LiteSVM(); - const handProgramId = new PublicKey(HAND_IDL.address); - const leverProgramId = new PublicKey(LEVER_IDL.address); - - const payer = Keypair.generate(); - svm.airdrop(payer.publicKey, BigInt(1000000000)); - - /** - * For serialization and deserialization of data - */ - const handCoder = new anchor.BorshCoder(HAND_IDL as anchor.Idl); - const leverCoder = new anchor.BorshCoder(LEVER_IDL as anchor.Idl); - - const handProgramPath = new URL("../target/deploy/hand.so", import.meta.url) - .pathname; - const leverProgramPath = new URL("../target/deploy/lever.so", import.meta.url) - .pathname; - svm.addProgramFromFile(handProgramId, handProgramPath); - svm.addProgramFromFile(leverProgramId, leverProgramPath); - - /** - * Generate a new keypair for the power account - */ - const powerAccount = new Keypair(); - - it("Initialize the lever!", () => { - /** - * Instruction data - * Create Transaction - * Send Transaction - */ - const data = leverCoder.instruction.encode("initialize", {}); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: powerAccount.publicKey, isSigner: true, isWritable: true }, - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId: leverProgramId, - data, - }); - - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer, powerAccount); - svm.sendTransaction(tx); - - /** - * Fetch account - * Check its required lamports - * Check it powerstatus - * */ - const minLamports = svm.minimumBalanceForRentExemption(BigInt(8 + 8)); - const powerAccountInfo = svm.getAccount(powerAccount.publicKey); - const powerStatus = leverCoder.accounts.decode( - "PowerStatus", - Buffer.from(powerAccountInfo.data), - ); - - assert(Number(minLamports) === powerAccountInfo.lamports); - assert(powerStatus.is_on === false); - }); - - it("Pull the lever!", () => { - /** - * Instruction data - * Create Transaction - * Send Transaction - */ - const data = handCoder.instruction.encode("pull_lever", { - name: "Jacob", - }); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: powerAccount.publicKey, isSigner: false, isWritable: true }, - { pubkey: leverProgramId, isSigner: false, isWritable: false }, - ], - programId: handProgramId, - data, - }); - - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer); - svm.sendTransaction(tx); - - /** - * Fetch account - * Check its powerstatus = true - * */ - const powerAccountInfo = svm.getAccount(powerAccount.publicKey); - const powerStatus = leverCoder.accounts.decode( - "PowerStatus", - Buffer.from(powerAccountInfo.data), - ); - - assert(powerStatus.is_on === true); - }); - - it("Pull it again!", () => { - /** - * Instruction data - * Create Transaction - * Send Transaction - */ - const data = handCoder.instruction.encode("pull_lever", { - name: "sol-warrior", - }); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: powerAccount.publicKey, isSigner: false, isWritable: true }, - { pubkey: leverProgramId, isSigner: false, isWritable: false }, - ], - programId: handProgramId, - data, - }); - - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer); - svm.sendTransaction(tx); - - /** - * Fetch account - * Check its powerstatus = false - * */ - const powerAccountInfo = svm.getAccount(powerAccount.publicKey); - const powerStatus = leverCoder.accounts.decode( - "PowerStatus", - Buffer.from(powerAccountInfo.data), - ); - - assert(powerStatus.is_on === false); - }); + const svm = new LiteSVM(); + const handProgramId = new PublicKey(HAND_IDL.address); + const leverProgramId = new PublicKey(LEVER_IDL.address); + + const payer = Keypair.generate(); + svm.airdrop(payer.publicKey, BigInt(1000000000)); + + /** + * For serialization and deserialization of data + */ + const handCoder = new anchor.BorshCoder(HAND_IDL as anchor.Idl); + const leverCoder = new anchor.BorshCoder(LEVER_IDL as anchor.Idl); + + const handProgramPath = new URL("../target/deploy/hand.so", import.meta.url).pathname; + const leverProgramPath = new URL("../target/deploy/lever.so", import.meta.url).pathname; + svm.addProgramFromFile(handProgramId, handProgramPath); + svm.addProgramFromFile(leverProgramId, leverProgramPath); + + /** + * Generate a new keypair for the power account + */ + const powerAccount = new Keypair(); + + it("Initialize the lever!", () => { + /** + * Instruction data + * Create Transaction + * Send Transaction + */ + const data = leverCoder.instruction.encode("initialize", {}); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: powerAccount.publicKey, isSigner: true, isWritable: true }, + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId: leverProgramId, + data, + }); + + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer, powerAccount); + svm.sendTransaction(tx); + + /** + * Fetch account + * Check its required lamports + * Check it powerstatus + * */ + const minLamports = svm.minimumBalanceForRentExemption(BigInt(8 + 8)); + const powerAccountInfo = svm.getAccount(powerAccount.publicKey); + const powerStatus = leverCoder.accounts.decode("PowerStatus", Buffer.from(powerAccountInfo.data)); + + assert(Number(minLamports) === powerAccountInfo.lamports); + assert(powerStatus.is_on === false); + }); + + it("Pull the lever!", () => { + /** + * Instruction data + * Create Transaction + * Send Transaction + */ + const data = handCoder.instruction.encode("pull_lever", { + name: "Jacob", + }); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: powerAccount.publicKey, isSigner: false, isWritable: true }, + { pubkey: leverProgramId, isSigner: false, isWritable: false }, + ], + programId: handProgramId, + data, + }); + + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer); + svm.sendTransaction(tx); + + /** + * Fetch account + * Check its powerstatus = true + * */ + const powerAccountInfo = svm.getAccount(powerAccount.publicKey); + const powerStatus = leverCoder.accounts.decode("PowerStatus", Buffer.from(powerAccountInfo.data)); + + assert(powerStatus.is_on === true); + }); + + it("Pull it again!", () => { + /** + * Instruction data + * Create Transaction + * Send Transaction + */ + const data = handCoder.instruction.encode("pull_lever", { + name: "sol-warrior", + }); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: powerAccount.publicKey, isSigner: false, isWritable: true }, + { pubkey: leverProgramId, isSigner: false, isWritable: false }, + ], + programId: handProgramId, + data, + }); + + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer); + svm.sendTransaction(tx); + + /** + * Fetch account + * Check its powerstatus = false + * */ + const powerAccountInfo = svm.getAccount(powerAccount.publicKey); + const powerStatus = leverCoder.accounts.decode("PowerStatus", Buffer.from(powerAccountInfo.data)); + + assert(powerStatus.is_on === false); + }); }); diff --git a/basics/cross-program-invocation/anchor/tests/test.ts b/basics/cross-program-invocation/anchor/tests/test.ts index d01c1c3ec..228593f81 100644 --- a/basics/cross-program-invocation/anchor/tests/test.ts +++ b/basics/cross-program-invocation/anchor/tests/test.ts @@ -5,78 +5,69 @@ import type { Hand } from "../target/types/hand.ts"; import type { Lever } from "../target/types/lever.ts"; describe("Anchor: CPI", () => { - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); - const hand = anchor.workspace.Hand as Program; - const lever = anchor.workspace.Lever as Program; + const hand = anchor.workspace.Hand as Program; + const lever = anchor.workspace.Lever as Program; - // Generate a new keypair for the power account - const powerAccount = new anchor.web3.Keypair(); + // Generate a new keypair for the power account + const powerAccount = new anchor.web3.Keypair(); - it("Initialize the lever!", async () => { - await lever.methods - .initialize() - .accounts({ - power: powerAccount.publicKey, - user: provider.wallet.publicKey, - }) - .signers([powerAccount]) - .rpc(); + it("Initialize the lever!", async () => { + await lever.methods + .initialize() + .accounts({ + power: powerAccount.publicKey, + user: provider.wallet.publicKey, + }) + .signers([powerAccount]) + .rpc(); - /** - * Fetch account - * Check its required lamports - * Check it powerstatus - * */ - const minLamports = - await provider.connection.getMinimumBalanceForRentExemption(8 + 8); - const powerStatus = await lever.account.powerStatus.fetch( - powerAccount.publicKey, - ); - const powerAccountInfo = await provider.connection.getAccountInfo( - powerAccount.publicKey, - ); + /** + * Fetch account + * Check its required lamports + * Check it powerstatus + * */ + const minLamports = await provider.connection.getMinimumBalanceForRentExemption(8 + 8); + const powerStatus = await lever.account.powerStatus.fetch(powerAccount.publicKey); + const powerAccountInfo = await provider.connection.getAccountInfo(powerAccount.publicKey); - assert(Number(minLamports) === powerAccountInfo.lamports); - assert(powerStatus.isOn === false); - }); + assert(Number(minLamports) === powerAccountInfo.lamports); + assert(powerStatus.isOn === false); + }); - it("Pull the lever!", async () => { - await hand.methods - .pullLever("Jacob") - .accounts({ - power: powerAccount.publicKey, - }) - .rpc(); + it("Pull the lever!", async () => { + await hand.methods + .pullLever("Jacob") + .accounts({ + power: powerAccount.publicKey, + }) + .rpc(); - /** - * Fetch account - * Check its powerstatus = true - * */ - const powerStatus = await lever.account.powerStatus.fetch( - powerAccount.publicKey, - ); + /** + * Fetch account + * Check its powerstatus = true + * */ + const powerStatus = await lever.account.powerStatus.fetch(powerAccount.publicKey); - assert(powerStatus.isOn === true); - }); + assert(powerStatus.isOn === true); + }); - it("Pull it again!", async () => { - await hand.methods - .pullLever("sol-warrior") - .accounts({ - power: powerAccount.publicKey, - }) - .rpc(); + it("Pull it again!", async () => { + await hand.methods + .pullLever("sol-warrior") + .accounts({ + power: powerAccount.publicKey, + }) + .rpc(); - /** - * Fetch account - * Check its powerstatus = false - * */ - const powerStatus = await lever.account.powerStatus.fetch( - powerAccount.publicKey, - ); + /** + * Fetch account + * Check its powerstatus = false + * */ + const powerStatus = await lever.account.powerStatus.fetch(powerAccount.publicKey); - assert(powerStatus.isOn === false); - }); + assert(powerStatus.isOn === false); + }); }); diff --git a/basics/cross-program-invocation/anchor/tsconfig.json b/basics/cross-program-invocation/anchor/tsconfig.json index fdf5c04de..395d18165 100644 --- a/basics/cross-program-invocation/anchor/tsconfig.json +++ b/basics/cross-program-invocation/anchor/tsconfig.json @@ -1,10 +1,10 @@ { - "compilerOptions": { - "types": ["mocha", "chai"], - "typeRoots": ["./node_modules/@types"], - "lib": ["es2020"], - "module": "nodenext", - "target": "es2020", - "esModuleInterop": true - } + "compilerOptions": { + "types": ["mocha", "chai"], + "typeRoots": ["./node_modules/@types"], + "lib": ["es2020"], + "module": "nodenext", + "target": "es2020", + "esModuleInterop": true + } } diff --git a/basics/cross-program-invocation/native/tests/test.ts b/basics/cross-program-invocation/native/tests/test.ts index efbca8062..c9dc4249b 100644 --- a/basics/cross-program-invocation/native/tests/test.ts +++ b/basics/cross-program-invocation/native/tests/test.ts @@ -1,19 +1,26 @@ -import { Buffer } from 'node:buffer'; -import { Connection, Keypair, SystemProgram, sendAndConfirmTransaction, Transaction, TransactionInstruction } from '@solana/web3.js'; -import * as borsh from 'borsh'; +import { Buffer } from "node:buffer"; +import { + Connection, + Keypair, + SystemProgram, + sendAndConfirmTransaction, + Transaction, + TransactionInstruction, +} from "@solana/web3.js"; +import * as borsh from "borsh"; function createKeypairFromFile(path: string): Keypair { - return Keypair.fromSecretKey(Uint8Array.from(JSON.parse(require('node:fs').readFileSync(path, 'utf-8')))); + return Keypair.fromSecretKey(Uint8Array.from(JSON.parse(require("node:fs").readFileSync(path, "utf-8")))); } -describe('CPI Example', () => { - const connection = new Connection('http://localhost:8899', 'confirmed'); - const payer = createKeypairFromFile(`${require('node:os').homedir()}/.config/solana/id.json`); - const hand = createKeypairFromFile('./target/so/hand-keypair.json'); - const lever = createKeypairFromFile('./target/so/lever-keypair.json'); +describe("CPI Example", () => { + const connection = new Connection("http://localhost:8899", "confirmed"); + const payer = createKeypairFromFile(`${require("node:os").homedir()}/.config/solana/id.json`); + const hand = createKeypairFromFile("./target/so/hand-keypair.json"); + const lever = createKeypairFromFile("./target/so/lever-keypair.json"); - const PowerStatusSchema = { struct: { is_on: 'u8' } }; - const SetPowerStatusSchema = { struct: { name: 'string' } }; + const PowerStatusSchema = { struct: { is_on: "u8" } }; + const SetPowerStatusSchema = { struct: { name: "string" } }; function borshSerialize(schema: borsh.Schema, data: object): Buffer { return Buffer.from(borsh.serialize(schema, data)); @@ -21,7 +28,7 @@ describe('CPI Example', () => { const powerAccount = Keypair.generate(); - it('Initialize the lever!', async () => { + it("Initialize the lever!", async () => { const ix = new TransactionInstruction({ keys: [ { pubkey: powerAccount.publicKey, isSigner: true, isWritable: true }, @@ -35,27 +42,27 @@ describe('CPI Example', () => { await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer, powerAccount]); }); - it('Pull the lever!', async () => { + it("Pull the lever!", async () => { const ix = new TransactionInstruction({ keys: [ { pubkey: powerAccount.publicKey, isSigner: false, isWritable: true }, { pubkey: lever.publicKey, isSigner: false, isWritable: false }, ], programId: hand.publicKey, - data: borshSerialize(SetPowerStatusSchema, { name: 'Chris' }), + data: borshSerialize(SetPowerStatusSchema, { name: "Chris" }), }); await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer]); }); - it('Pull it again!', async () => { + it("Pull it again!", async () => { const ix = new TransactionInstruction({ keys: [ { pubkey: powerAccount.publicKey, isSigner: false, isWritable: true }, { pubkey: lever.publicKey, isSigner: false, isWritable: false }, ], programId: hand.publicKey, - data: borshSerialize(SetPowerStatusSchema, { name: 'Ashley' }), + data: borshSerialize(SetPowerStatusSchema, { name: "Ashley" }), }); await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer]); diff --git a/basics/favorites/anchor/migrations/deploy.ts b/basics/favorites/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/basics/favorites/anchor/migrations/deploy.ts +++ b/basics/favorites/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/basics/favorites/anchor/package.json b/basics/favorites/anchor/package.json index 7cf70d1bb..f11a93525 100644 --- a/basics/favorites/anchor/package.json +++ b/basics/favorites/anchor/package.json @@ -1,23 +1,23 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/web3.js": "^1.98.4", - "litesvm": "^0.4.0" - }, - "license": "MIT", - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/web3.js": "^1.98.4", + "litesvm": "^0.4.0" + }, + "license": "MIT", + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/basics/favorites/anchor/tests/litesvm.test.ts b/basics/favorites/anchor/tests/litesvm.test.ts index c3d7c031d..34fd39e18 100644 --- a/basics/favorites/anchor/tests/litesvm.test.ts +++ b/basics/favorites/anchor/tests/litesvm.test.ts @@ -1,143 +1,130 @@ import anchor from "@anchor-lang/core"; -import { - Keypair, - PublicKey, - SystemProgram, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; +import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction } from "@solana/web3.js"; import { assert } from "chai"; import { LiteSVM } from "litesvm"; import IDL from "../target/idl/favorites.json" with { type: "json" }; describe("LiteSVM: Favorites", () => { - const svm = new LiteSVM(); - const programId = new PublicKey(IDL.address); - const coder = new anchor.BorshCoder(IDL as anchor.Idl); //For serialization and deserialization - const payer = Keypair.generate(); - svm.airdrop(payer.publicKey, BigInt(1000000000)); - - const programPath = new URL("../target/deploy/favorites.so", import.meta.url) - .pathname; - svm.addProgramFromFile(programId, programPath); - - const [favPdaAccount] = PublicKey.findProgramAddressSync( - [Buffer.from("favorites"), payer.publicKey.toBuffer()], - programId, - ); - /** - * Here's what we want to write to the blockchain - */ - const favoriteNumber = new anchor.BN(23); - const favoriteColor = "purple"; - const favoriteHobbies = ["skiing", "skydiving", "biking"]; - - it("Writes our favorites to the blockchain", () => { - const ixArgs = { - number: favoriteNumber, - color: favoriteColor, - hobbies: favoriteHobbies, - }; - - const data = coder.instruction.encode("set_favorites", ixArgs); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: favPdaAccount, isSigner: false, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId, - data, - }); - - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer); - svm.sendTransaction(tx); - - /** - * Fetch the account and check its favorites - */ - const favAccountInfo = svm.getAccount(favPdaAccount); - const favAccount = coder.accounts.decode( - "Favorites", - Buffer.from(favAccountInfo.data), - ); - - assert.equal(favAccount.number.toNumber(), favoriteNumber.toNumber()); - assert.equal(favAccount.color, favoriteColor); - assert.deepStrictEqual(favAccount.hobbies, favoriteHobbies); - }); - - it("Updates the favorites", () => { - const newFavoriteHobbies = ["coding", "reading", "biking", "swimming"]; - const ixArgs = { - number: favoriteNumber, - color: favoriteColor, - hobbies: newFavoriteHobbies, - }; - - const data = coder.instruction.encode("set_favorites", ixArgs); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: favPdaAccount, isSigner: false, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId, - data, - }); - - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer); - svm.sendTransaction(tx); - - /** - * Fetch the account and check its favorites - */ - const favAccountInfo = svm.getAccount(favPdaAccount); - const favAccount = coder.accounts.decode( - "Favorites", - Buffer.from(favAccountInfo.data), - ); - - assert.equal(favAccount.number.toNumber(), favoriteNumber.toNumber()); - assert.equal(favAccount.color, favoriteColor); - assert.deepStrictEqual(favAccount.hobbies, newFavoriteHobbies); - }); - - it("Rejects transactions from unauthorized signers", () => { - const newFavoriteHobbies = ["coding", "reading", "biking"]; - const someRandomGuy = Keypair.generate(); - - const ixArgs = { - number: favoriteNumber, - color: favoriteColor, - hobbies: newFavoriteHobbies, - }; - - const data = coder.instruction.encode("set_favorites", ixArgs); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: favPdaAccount, isSigner: false, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId, - data, - }); - - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - - assert.Throw(() => { - tx.sign(someRandomGuy); - svm.sendTransaction(tx); - }, "unknown signer"); - }); + const svm = new LiteSVM(); + const programId = new PublicKey(IDL.address); + const coder = new anchor.BorshCoder(IDL as anchor.Idl); //For serialization and deserialization + const payer = Keypair.generate(); + svm.airdrop(payer.publicKey, BigInt(1000000000)); + + const programPath = new URL("../target/deploy/favorites.so", import.meta.url).pathname; + svm.addProgramFromFile(programId, programPath); + + const [favPdaAccount] = PublicKey.findProgramAddressSync( + [Buffer.from("favorites"), payer.publicKey.toBuffer()], + programId, + ); + /** + * Here's what we want to write to the blockchain + */ + const favoriteNumber = new anchor.BN(23); + const favoriteColor = "purple"; + const favoriteHobbies = ["skiing", "skydiving", "biking"]; + + it("Writes our favorites to the blockchain", () => { + const ixArgs = { + number: favoriteNumber, + color: favoriteColor, + hobbies: favoriteHobbies, + }; + + const data = coder.instruction.encode("set_favorites", ixArgs); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: favPdaAccount, isSigner: false, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId, + data, + }); + + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer); + svm.sendTransaction(tx); + + /** + * Fetch the account and check its favorites + */ + const favAccountInfo = svm.getAccount(favPdaAccount); + const favAccount = coder.accounts.decode("Favorites", Buffer.from(favAccountInfo.data)); + + assert.equal(favAccount.number.toNumber(), favoriteNumber.toNumber()); + assert.equal(favAccount.color, favoriteColor); + assert.deepStrictEqual(favAccount.hobbies, favoriteHobbies); + }); + + it("Updates the favorites", () => { + const newFavoriteHobbies = ["coding", "reading", "biking", "swimming"]; + const ixArgs = { + number: favoriteNumber, + color: favoriteColor, + hobbies: newFavoriteHobbies, + }; + + const data = coder.instruction.encode("set_favorites", ixArgs); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: favPdaAccount, isSigner: false, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId, + data, + }); + + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer); + svm.sendTransaction(tx); + + /** + * Fetch the account and check its favorites + */ + const favAccountInfo = svm.getAccount(favPdaAccount); + const favAccount = coder.accounts.decode("Favorites", Buffer.from(favAccountInfo.data)); + + assert.equal(favAccount.number.toNumber(), favoriteNumber.toNumber()); + assert.equal(favAccount.color, favoriteColor); + assert.deepStrictEqual(favAccount.hobbies, newFavoriteHobbies); + }); + + it("Rejects transactions from unauthorized signers", () => { + const newFavoriteHobbies = ["coding", "reading", "biking"]; + const someRandomGuy = Keypair.generate(); + + const ixArgs = { + number: favoriteNumber, + color: favoriteColor, + hobbies: newFavoriteHobbies, + }; + + const data = coder.instruction.encode("set_favorites", ixArgs); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: favPdaAccount, isSigner: false, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId, + data, + }); + + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + + assert.Throw(() => { + tx.sign(someRandomGuy); + svm.sendTransaction(tx); + }, "unknown signer"); + }); }); diff --git a/basics/favorites/anchor/tests/test.ts b/basics/favorites/anchor/tests/test.ts index c39d43a6f..c77cfa258 100644 --- a/basics/favorites/anchor/tests/test.ts +++ b/basics/favorites/anchor/tests/test.ts @@ -5,83 +5,77 @@ import { assert } from "chai"; import type { Favorites } from "../target/types/favorites.ts"; describe("Anchor: Favorites", () => { - // Use the cluster and the keypair from Anchor.toml - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); - const web3 = anchor.web3; - // See https://github.com/coral-xyz/anchor/issues/3122 - const user = (provider.wallet as anchor.Wallet).payer; - const someRandomGuy = anchor.web3.Keypair.generate(); - const program = anchor.workspace.Favorites as Program; + // Use the cluster and the keypair from Anchor.toml + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); + const web3 = anchor.web3; + // See https://github.com/coral-xyz/anchor/issues/3122 + const user = (provider.wallet as anchor.Wallet).payer; + const someRandomGuy = anchor.web3.Keypair.generate(); + const program = anchor.workspace.Favorites as Program; - // Here's what we want to write to the blockchain - const favoriteNumber = new BN(23); - const favoriteColor = "purple"; - const favoriteHobbies = ["skiing", "skydiving", "biking"]; + // Here's what we want to write to the blockchain + const favoriteNumber = new BN(23); + const favoriteColor = "purple"; + const favoriteHobbies = ["skiing", "skydiving", "biking"]; - // We don't need to airdrop if we're using the local cluster - // because the local cluster gives us 85 billion dollars worth of SOL - before(async () => { - const balance = await provider.connection.getBalance(user.publicKey); - const balanceInSOL = balance / web3.LAMPORTS_PER_SOL; - const formattedBalance = new Intl.NumberFormat().format(balanceInSOL); - console.log(`Balance: ${formattedBalance} SOL`); - }); + // We don't need to airdrop if we're using the local cluster + // because the local cluster gives us 85 billion dollars worth of SOL + before(async () => { + const balance = await provider.connection.getBalance(user.publicKey); + const balanceInSOL = balance / web3.LAMPORTS_PER_SOL; + const formattedBalance = new Intl.NumberFormat().format(balanceInSOL); + console.log(`Balance: ${formattedBalance} SOL`); + }); - it("Writes our favorites to the blockchain", async () => { - await program.methods - // set_favourites in Rust becomes setFavorites in TypeScript - .setFavorites(favoriteNumber, favoriteColor, favoriteHobbies) - // Sign the transaction - .signers([user]) - // Send the transaction to the cluster or RPC - .rpc(); + it("Writes our favorites to the blockchain", async () => { + await program.methods + // set_favourites in Rust becomes setFavorites in TypeScript + .setFavorites(favoriteNumber, favoriteColor, favoriteHobbies) + // Sign the transaction + .signers([user]) + // Send the transaction to the cluster or RPC + .rpc(); - // Find the PDA for the user's favorites - const favoritesPdaAndBump = web3.PublicKey.findProgramAddressSync( - [Buffer.from("favorites"), user.publicKey.toBuffer()], - program.programId, - ); - const favoritesPda = favoritesPdaAndBump[0]; - const dataFromPda = await program.account.favorites.fetch(favoritesPda); - // And make sure it matches! - assert.equal(dataFromPda.color, favoriteColor); - // A little extra work to make sure the BNs are equal - assert.equal(dataFromPda.number.toString(), favoriteNumber.toString()); - // And check the hobbies too - assert.deepEqual(dataFromPda.hobbies, favoriteHobbies); - }); + // Find the PDA for the user's favorites + const favoritesPdaAndBump = web3.PublicKey.findProgramAddressSync( + [Buffer.from("favorites"), user.publicKey.toBuffer()], + program.programId, + ); + const favoritesPda = favoritesPdaAndBump[0]; + const dataFromPda = await program.account.favorites.fetch(favoritesPda); + // And make sure it matches! + assert.equal(dataFromPda.color, favoriteColor); + // A little extra work to make sure the BNs are equal + assert.equal(dataFromPda.number.toString(), favoriteNumber.toString()); + // And check the hobbies too + assert.deepEqual(dataFromPda.hobbies, favoriteHobbies); + }); - it("Updates the favorites", async () => { - const newFavoriteHobbies = ["skiing", "skydiving", "biking", "swimming"]; + it("Updates the favorites", async () => { + const newFavoriteHobbies = ["skiing", "skydiving", "biking", "swimming"]; - await program.methods - .setFavorites(favoriteNumber, favoriteColor, newFavoriteHobbies) - .signers([user]) - .rpc(); + await program.methods.setFavorites(favoriteNumber, favoriteColor, newFavoriteHobbies).signers([user]).rpc(); - // Find the PDA for the user's favorites - const favoritesPdaAndBump = web3.PublicKey.findProgramAddressSync( - [Buffer.from("favorites"), user.publicKey.toBuffer()], - program.programId, - ); - const favoritesPda = favoritesPdaAndBump[0]; - const dataFromPda = await program.account.favorites.fetch(favoritesPda); + // Find the PDA for the user's favorites + const favoritesPdaAndBump = web3.PublicKey.findProgramAddressSync( + [Buffer.from("favorites"), user.publicKey.toBuffer()], + program.programId, + ); + const favoritesPda = favoritesPdaAndBump[0]; + const dataFromPda = await program.account.favorites.fetch(favoritesPda); - assert.equal(dataFromPda.color, favoriteColor); - assert.equal(dataFromPda.number.toString(), favoriteNumber.toString()); - assert.deepEqual(dataFromPda.hobbies, newFavoriteHobbies); - }); + assert.equal(dataFromPda.color, favoriteColor); + assert.equal(dataFromPda.number.toString(), favoriteNumber.toString()); + assert.deepEqual(dataFromPda.hobbies, newFavoriteHobbies); + }); - it("Rejects transactions from unauthorized signers", async () => { - try { - await program.methods - .setFavorites(favoriteNumber, favoriteColor, favoriteHobbies) - .signers([someRandomGuy]) - .rpc(); - assert.fail("Expected unauthorized signer error"); - } catch (err) { - assert.include((err as Error).message, "unknown signer"); - } - }); + it("Rejects transactions from unauthorized signers", async () => { + try { + await program.methods.setFavorites(favoriteNumber, favoriteColor, favoriteHobbies).signers([someRandomGuy]).rpc(); + assert.fail("Expected unauthorized signer error"); + } catch (err) { + assert.include((err as Error).message, "unknown signer"); + } + }); }); diff --git a/basics/favorites/anchor/tsconfig.json b/basics/favorites/anchor/tsconfig.json index fdf5c04de..395d18165 100644 --- a/basics/favorites/anchor/tsconfig.json +++ b/basics/favorites/anchor/tsconfig.json @@ -1,10 +1,10 @@ { - "compilerOptions": { - "types": ["mocha", "chai"], - "typeRoots": ["./node_modules/@types"], - "lib": ["es2020"], - "module": "nodenext", - "target": "es2020", - "esModuleInterop": true - } + "compilerOptions": { + "types": ["mocha", "chai"], + "typeRoots": ["./node_modules/@types"], + "lib": ["es2020"], + "module": "nodenext", + "target": "es2020", + "esModuleInterop": true + } } diff --git a/basics/favorites/native/tests/test.ts b/basics/favorites/native/tests/test.ts index 0027bb7bb..13e5e5b34 100644 --- a/basics/favorites/native/tests/test.ts +++ b/basics/favorites/native/tests/test.ts @@ -1,6 +1,6 @@ import { - Blockhash, - Keypair, + type Blockhash, + type Keypair, PublicKey, SystemProgram, Transaction, @@ -10,7 +10,7 @@ import { BN } from "bn.js"; import * as borsh from "borsh"; import { assert, expect } from "chai"; import { describe, test } from "mocha"; -import { BanksClient, ProgramTestContext, start } from "solana-bankrun"; +import { type BanksClient, type ProgramTestContext, start } from "solana-bankrun"; const MyInstruction = { CreateFav: 0, @@ -103,9 +103,7 @@ describe("Favorites Solana Native", () => { console.log("Deserialized data:", favoritesData); - expect(new BN(favoritesData.number as any, "le").toNumber()).to.equal( - favData.number, - ); + expect(new BN(favoritesData.number as Buffer, "le").toNumber()).to.equal(favData.number); expect(favoritesData.color).to.equal(favData.color); expect(favoritesData.hobbies).to.deep.equal(favData.hobbies); }); diff --git a/basics/favorites/pinocchio/tests/test.ts b/basics/favorites/pinocchio/tests/test.ts index e6d02ff24..f63e2f8bb 100644 --- a/basics/favorites/pinocchio/tests/test.ts +++ b/basics/favorites/pinocchio/tests/test.ts @@ -1,16 +1,4 @@ -import { - Blockhash, - Keypair, - PublicKey, - SystemProgram, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; -import { BN } from "bn.js"; -import * as borsh from "borsh"; -import { assert, expect } from "chai"; -import { describe, test } from "mocha"; -import { BanksClient, ProgramTestContext, start } from "solana-bankrun"; +import { describe } from "mocha"; describe("Favorites Solana Pinocchio", () => { console.log("Favorites Solana Pinocchio"); diff --git a/basics/hello-solana/anchor/package.json b/basics/hello-solana/anchor/package.json index 0696e9344..a77db16c0 100644 --- a/basics/hello-solana/anchor/package.json +++ b/basics/hello-solana/anchor/package.json @@ -1,17 +1,17 @@ { - "type": "module", - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/web3.js": "^1.98.4", - "litesvm": "^0.4.0" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/web3.js": "^1.98.4", + "litesvm": "^0.4.0" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/basics/hello-solana/anchor/tests/litesvm.test.ts b/basics/hello-solana/anchor/tests/litesvm.test.ts index 30f9e5b74..524df9db7 100644 --- a/basics/hello-solana/anchor/tests/litesvm.test.ts +++ b/basics/hello-solana/anchor/tests/litesvm.test.ts @@ -1,55 +1,47 @@ import anchor from "@anchor-lang/core"; -import { - Keypair, - PublicKey, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; +import { Keypair, PublicKey, Transaction, TransactionInstruction } from "@solana/web3.js"; import { LiteSVM } from "litesvm"; import IDL from "../target/idl/hello_solana.json" with { type: "json" }; describe("LiteSVM: hello-solana", () => { - const svm = new LiteSVM(); - const programId = new PublicKey(IDL.address); - /** - * Creates a coder to easily build and encode program instructions based on the IDL. - */ - const coder = new anchor.BorshCoder(IDL as anchor.Idl); + const svm = new LiteSVM(); + const programId = new PublicKey(IDL.address); + /** + * Creates a coder to easily build and encode program instructions based on the IDL. + */ + const coder = new anchor.BorshCoder(IDL as anchor.Idl); - const payer = Keypair.generate(); - svm.airdrop(payer.publicKey, BigInt(1000000000)); + const payer = Keypair.generate(); + svm.airdrop(payer.publicKey, BigInt(1000000000)); - /** - * Load the hello_solana program binary into the LiteSVM instance - * for local testing and simulation. - */ - const programPath = new URL( - "../target/deploy/hello_solana.so", - import.meta.url, - ).pathname; - svm.addProgramFromFile(programId, programPath); + /** + * Load the hello_solana program binary into the LiteSVM instance + * for local testing and simulation. + */ + const programPath = new URL("../target/deploy/hello_solana.so", import.meta.url).pathname; + svm.addProgramFromFile(programId, programPath); - it("Say hello!", () => { - /** - * Create an instruction for the 'hello' method using the Anchor coder. - * No arguments are needed for this instruction so i give `{}`. - */ - const data = coder.instruction.encode("hello", {}); + it("Say hello!", () => { + /** + * Create an instruction for the 'hello' method using the Anchor coder. + * No arguments are needed for this instruction so i give `{}`. + */ + const data = coder.instruction.encode("hello", {}); - /** - * Build and sign a transaction to call the 'hello' instruction - * on the hello_solana program with LiteSVM. - */ - const ix = new TransactionInstruction({ - keys: [], - programId, - data, - }); + /** + * Build and sign a transaction to call the 'hello' instruction + * on the hello_solana program with LiteSVM. + */ + const ix = new TransactionInstruction({ + keys: [], + programId, + data, + }); - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer); - svm.sendTransaction(tx); - }); + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer); + svm.sendTransaction(tx); + }); }); diff --git a/basics/hello-solana/anchor/tests/test.ts b/basics/hello-solana/anchor/tests/test.ts index 18f4ab831..c97df9112 100644 --- a/basics/hello-solana/anchor/tests/test.ts +++ b/basics/hello-solana/anchor/tests/test.ts @@ -2,16 +2,16 @@ import * as anchor from "@anchor-lang/core"; import type { HelloSolana } from "../target/types/hello_solana.ts"; describe("Anchor: hello-solana", () => { - // Configure the Anchor provider & load the program IDL - // The IDL gives you a typescript module - // - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); - const program = anchor.workspace.HelloSolana as anchor.Program; + // Configure the Anchor provider & load the program IDL + // The IDL gives you a typescript module + // + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); + const program = anchor.workspace.HelloSolana as anchor.Program; - it("Say hello!", async () => { - // Just run Anchor's IDL method to build a transaction! - // - await program.methods.hello().accounts({}).rpc(); - }); + it("Say hello!", async () => { + // Just run Anchor's IDL method to build a transaction! + // + await program.methods.hello().accounts({}).rpc(); + }); }); diff --git a/basics/hello-solana/anchor/tsconfig.json b/basics/hello-solana/anchor/tsconfig.json index fdf5c04de..395d18165 100644 --- a/basics/hello-solana/anchor/tsconfig.json +++ b/basics/hello-solana/anchor/tsconfig.json @@ -1,10 +1,10 @@ { - "compilerOptions": { - "types": ["mocha", "chai"], - "typeRoots": ["./node_modules/@types"], - "lib": ["es2020"], - "module": "nodenext", - "target": "es2020", - "esModuleInterop": true - } + "compilerOptions": { + "types": ["mocha", "chai"], + "typeRoots": ["./node_modules/@types"], + "lib": ["es2020"], + "module": "nodenext", + "target": "es2020", + "esModuleInterop": true + } } diff --git a/basics/hello-solana/native/tests/index.test.ts b/basics/hello-solana/native/tests/index.test.ts index ec7daa61e..1c0c85b31 100644 --- a/basics/hello-solana/native/tests/index.test.ts +++ b/basics/hello-solana/native/tests/index.test.ts @@ -1,16 +1,16 @@ -import { describe, test } from 'node:test'; -import { PublicKey, Transaction, TransactionInstruction } from '@solana/web3.js'; -import { assert } from 'chai'; -import { start } from 'solana-bankrun'; +import { describe, test } from "node:test"; +import { PublicKey, Transaction, TransactionInstruction } from "@solana/web3.js"; +import { assert } from "chai"; +import { start } from "solana-bankrun"; -describe('hello-solana', async () => { +describe("hello-solana", async () => { // load program in solana-bankrun const PROGRAM_ID = PublicKey.unique(); - const context = await start([{ name: 'hello_solana_program', programId: PROGRAM_ID }], []); + const context = await start([{ name: "hello_solana_program", programId: PROGRAM_ID }], []); const client = context.banksClient; const payer = context.payer; - test('Say hello!', async () => { + test("Say hello!", async () => { const blockhash = context.lastBlockhash; // We set up our instruction first. const ix = new TransactionInstruction({ @@ -27,7 +27,7 @@ describe('hello-solana', async () => { const transaction = await client.processTransaction(tx); assert(transaction.logMessages[0].startsWith(`Program ${PROGRAM_ID}`)); - assert(transaction.logMessages[1] === 'Program log: Hello, Solana!'); + assert(transaction.logMessages[1] === "Program log: Hello, Solana!"); assert(transaction.logMessages[2] === `Program log: Our program's Program ID: ${PROGRAM_ID}`); assert(transaction.logMessages[3].startsWith(`Program ${PROGRAM_ID} consumed`)); assert(transaction.logMessages[4] === `Program ${PROGRAM_ID} success`); diff --git a/basics/hello-solana/pinocchio/tests/index.test.ts b/basics/hello-solana/pinocchio/tests/index.test.ts index 734bad24f..985c2befa 100644 --- a/basics/hello-solana/pinocchio/tests/index.test.ts +++ b/basics/hello-solana/pinocchio/tests/index.test.ts @@ -1,17 +1,17 @@ -import { PublicKey, Transaction, TransactionInstruction } from '@solana/web3.js'; -import { assert } from 'chai'; -import { ProgramTestContext, start } from 'solana-bankrun'; +import { PublicKey, Transaction, TransactionInstruction } from "@solana/web3.js"; +import { assert } from "chai"; +import { type ProgramTestContext, start } from "solana-bankrun"; -describe('hello-solana', () => { +describe("hello-solana", () => { const PROGRAM_ID = PublicKey.unique(); // load program in solana-bankrun let context: ProgramTestContext; before(async () => { - context = await start([{ name: 'hello_solana_program_pinocchio', programId: PROGRAM_ID }], []); + context = await start([{ name: "hello_solana_program_pinocchio", programId: PROGRAM_ID }], []); }); - it('Say hello!', async () => { + it("Say hello!", async () => { const client = context.banksClient; const payer = context.payer; const blockhash = context.lastBlockhash; @@ -30,8 +30,8 @@ describe('hello-solana', () => { const transaction = await client.processTransaction(tx); assert(transaction.logMessages[0].startsWith(`Program ${PROGRAM_ID}`)); - assert(transaction.logMessages[1] === 'Program log: Hello, Solana!'); - assert(transaction.logMessages[2] === `Program log: [${Array.from(PROGRAM_ID.toBytes()).join(', ')}]`); + assert(transaction.logMessages[1] === "Program log: Hello, Solana!"); + assert(transaction.logMessages[2] === `Program log: [${Array.from(PROGRAM_ID.toBytes()).join(", ")}]`); assert(transaction.logMessages[3].startsWith(`Program ${PROGRAM_ID} consumed`)); assert(transaction.logMessages[4] === `Program ${PROGRAM_ID} success`); assert(transaction.logMessages.length === 5); diff --git a/basics/pda-rent-payer/anchor/package.json b/basics/pda-rent-payer/anchor/package.json index 0696e9344..a77db16c0 100644 --- a/basics/pda-rent-payer/anchor/package.json +++ b/basics/pda-rent-payer/anchor/package.json @@ -1,17 +1,17 @@ { - "type": "module", - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/web3.js": "^1.98.4", - "litesvm": "^0.4.0" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/web3.js": "^1.98.4", + "litesvm": "^0.4.0" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/basics/pda-rent-payer/anchor/tests/litesvm.test.ts b/basics/pda-rent-payer/anchor/tests/litesvm.test.ts index 35c9a3108..a1c0c2174 100644 --- a/basics/pda-rent-payer/anchor/tests/litesvm.test.ts +++ b/basics/pda-rent-payer/anchor/tests/litesvm.test.ts @@ -1,93 +1,87 @@ import anchor from "@anchor-lang/core"; import { - Keypair, - LAMPORTS_PER_SOL, - PublicKey, - SystemProgram, - Transaction, - TransactionInstruction, + Keypair, + LAMPORTS_PER_SOL, + PublicKey, + SystemProgram, + Transaction, + TransactionInstruction, } from "@solana/web3.js"; import { assert } from "chai"; import { LiteSVM } from "litesvm"; import IDL from "../target/idl/pda_rent_payer.json" with { type: "json" }; describe("LiteSVM: PDA Rent-Payer", () => { - const svm = new LiteSVM(); - const programId = new PublicKey(IDL.address); - const coder = new anchor.BorshCoder(IDL as anchor.Idl); - const payer = Keypair.generate(); - svm.airdrop(payer.publicKey, BigInt(10000000000)); + const svm = new LiteSVM(); + const programId = new PublicKey(IDL.address); + const coder = new anchor.BorshCoder(IDL as anchor.Idl); + const payer = Keypair.generate(); + svm.airdrop(payer.publicKey, BigInt(10000000000)); - const programPath = new URL( - "../target/deploy/pda_rent_payer.so", - import.meta.url, - ).pathname; - svm.addProgramFromFile(programId, programPath); + const programPath = new URL("../target/deploy/pda_rent_payer.so", import.meta.url).pathname; + svm.addProgramFromFile(programId, programPath); - /** - * generate PDA for the Rent Vault - */ - const [rentVaultPDA] = PublicKey.findProgramAddressSync( - [Buffer.from("rent_vault")], - programId, - ); + /** + * generate PDA for the Rent Vault + */ + const [rentVaultPDA] = PublicKey.findProgramAddressSync([Buffer.from("rent_vault")], programId); - it("Initialize the Rent Vault", () => { - const ixArgs = { - fund_lamports: new anchor.BN(LAMPORTS_PER_SOL), - }; + it("Initialize the Rent Vault", () => { + const ixArgs = { + fund_lamports: new anchor.BN(LAMPORTS_PER_SOL), + }; - const data = coder.instruction.encode("init_rent_vault", ixArgs); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: rentVaultPDA, isSigner: false, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId, - data, - }); + const data = coder.instruction.encode("init_rent_vault", ixArgs); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: rentVaultPDA, isSigner: false, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId, + data, + }); - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer); - svm.sendTransaction(tx); + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer); + svm.sendTransaction(tx); - /** - * Fetch the account and check its rent vault account info - */ - const rentVaultAccountInfo = svm.getAccount(rentVaultPDA); + /** + * Fetch the account and check its rent vault account info + */ + const rentVaultAccountInfo = svm.getAccount(rentVaultPDA); - assert.equal(rentVaultAccountInfo.lamports, LAMPORTS_PER_SOL); - }); + assert.equal(rentVaultAccountInfo.lamports, LAMPORTS_PER_SOL); + }); - it("Create a new account using the Rent Vault", () => { - const newAccount = new Keypair(); + it("Create a new account using the Rent Vault", () => { + const newAccount = new Keypair(); - const data = coder.instruction.encode("create_new_account", {}); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: newAccount.publicKey, isSigner: true, isWritable: true }, - { pubkey: rentVaultPDA, isSigner: false, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId, - data, - }); + const data = coder.instruction.encode("create_new_account", {}); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: newAccount.publicKey, isSigner: true, isWritable: true }, + { pubkey: rentVaultPDA, isSigner: false, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId, + data, + }); - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer, newAccount); - svm.sendTransaction(tx); + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer, newAccount); + svm.sendTransaction(tx); - /** - * Fetch the newAccount and check its rent - */ - const minLamports = svm.minimumBalanceForRentExemption(BigInt(0)); - const newAccountInfo = svm.getAccount(newAccount.publicKey); + /** + * Fetch the newAccount and check its rent + */ + const minLamports = svm.minimumBalanceForRentExemption(BigInt(0)); + const newAccountInfo = svm.getAccount(newAccount.publicKey); - assert.equal(newAccountInfo.lamports, Number(minLamports)); - }); + assert.equal(newAccountInfo.lamports, Number(minLamports)); + }); }); diff --git a/basics/pda-rent-payer/anchor/tests/test.ts b/basics/pda-rent-payer/anchor/tests/test.ts index 153d95d3f..1e8dc3a92 100644 --- a/basics/pda-rent-payer/anchor/tests/test.ts +++ b/basics/pda-rent-payer/anchor/tests/test.ts @@ -5,52 +5,48 @@ import { assert } from "chai"; import type { PdaRentPayer } from "../target/types/pda_rent_payer.ts"; describe("PDA Rent-Payer", () => { - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); - const wallet = provider.wallet as anchor.Wallet; - const connection = provider.connection; - const program = anchor.workspace.PdaRentPayer as anchor.Program; - - // PDA for the Rent Vault - const [rentVaultPDA] = PublicKey.findProgramAddressSync( - [Buffer.from("rent_vault")], - program.programId, - ); - - it("Initialize the Rent Vault", async () => { - // 1 SOL - const fundAmount = new BN(LAMPORTS_PER_SOL); - - await program.methods - .initRentVault(fundAmount) - .accounts({ - payer: wallet.publicKey, - }) - .rpc(); - - // Check rent vault balance - const accountInfo = - await program.provider.connection.getAccountInfo(rentVaultPDA); - assert(accountInfo.lamports === fundAmount.toNumber()); - }); - - it("Create a new account using the Rent Vault", async () => { - // Generate a new keypair for the new account - const newAccount = new Keypair(); - - await program.methods - .createNewAccount() - .accounts({ - newAccount: newAccount.publicKey, - }) - .signers([newAccount]) - .rpc(); - - // Minimum balance for rent exemption for new account - const lamports = await connection.getMinimumBalanceForRentExemption(0); - - // Check that the account was created - const accountInfo = await connection.getAccountInfo(newAccount.publicKey); - assert(accountInfo.lamports === lamports); - }); + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); + const wallet = provider.wallet as anchor.Wallet; + const connection = provider.connection; + const program = anchor.workspace.PdaRentPayer as anchor.Program; + + // PDA for the Rent Vault + const [rentVaultPDA] = PublicKey.findProgramAddressSync([Buffer.from("rent_vault")], program.programId); + + it("Initialize the Rent Vault", async () => { + // 1 SOL + const fundAmount = new BN(LAMPORTS_PER_SOL); + + await program.methods + .initRentVault(fundAmount) + .accounts({ + payer: wallet.publicKey, + }) + .rpc(); + + // Check rent vault balance + const accountInfo = await program.provider.connection.getAccountInfo(rentVaultPDA); + assert(accountInfo.lamports === fundAmount.toNumber()); + }); + + it("Create a new account using the Rent Vault", async () => { + // Generate a new keypair for the new account + const newAccount = new Keypair(); + + await program.methods + .createNewAccount() + .accounts({ + newAccount: newAccount.publicKey, + }) + .signers([newAccount]) + .rpc(); + + // Minimum balance for rent exemption for new account + const lamports = await connection.getMinimumBalanceForRentExemption(0); + + // Check that the account was created + const accountInfo = await connection.getAccountInfo(newAccount.publicKey); + assert(accountInfo.lamports === lamports); + }); }); diff --git a/basics/pda-rent-payer/anchor/tsconfig.json b/basics/pda-rent-payer/anchor/tsconfig.json index 59fe75cf0..beb254c00 100644 --- a/basics/pda-rent-payer/anchor/tsconfig.json +++ b/basics/pda-rent-payer/anchor/tsconfig.json @@ -1,10 +1,10 @@ { - "compilerOptions": { - "types": ["mocha", "chai"], - "typeRoots": ["./node_modules/@types"], - "lib": ["es2015"], - "module": "nodenext", - "target": "es6", - "esModuleInterop": true - } + "compilerOptions": { + "types": ["mocha", "chai"], + "typeRoots": ["./node_modules/@types"], + "lib": ["es2015"], + "module": "nodenext", + "target": "es6", + "esModuleInterop": true + } } diff --git a/basics/pda-rent-payer/native/tests/test.ts b/basics/pda-rent-payer/native/tests/test.ts index 03f17ca03..6c3a9c414 100644 --- a/basics/pda-rent-payer/native/tests/test.ts +++ b/basics/pda-rent-payer/native/tests/test.ts @@ -1,21 +1,12 @@ import { Buffer } from "node:buffer"; import { describe, test } from "node:test"; -import { - Keypair, - PublicKey, - SystemProgram, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; +import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction } from "@solana/web3.js"; import * as borsh from "borsh"; import { start } from "solana-bankrun"; describe("PDA Rent-Payer", async () => { const PROGRAM_ID = PublicKey.unique(); - const context = await start( - [{ name: "pda_rent_payer_program", programId: PROGRAM_ID }], - [], - ); + const context = await start([{ name: "pda_rent_payer_program", programId: PROGRAM_ID }], []); const client = context.banksClient; const payer = context.payer; @@ -42,10 +33,7 @@ describe("PDA Rent-Payer", async () => { } function deriveRentVaultPda() { - const pda = PublicKey.findProgramAddressSync( - [Buffer.from("rent_vault")], - PROGRAM_ID, - ); + const pda = PublicKey.findProgramAddressSync([Buffer.from("rent_vault")], PROGRAM_ID); console.log(`PDA: ${pda[0].toBase58()}`); return pda; } diff --git a/basics/pda-rent-payer/pinocchio/tests/test.ts b/basics/pda-rent-payer/pinocchio/tests/test.ts index b1af8db34..836c6aba3 100644 --- a/basics/pda-rent-payer/pinocchio/tests/test.ts +++ b/basics/pda-rent-payer/pinocchio/tests/test.ts @@ -1,14 +1,4 @@ -import { Buffer } from "node:buffer"; -import { describe, test } from "node:test"; -import { - Keypair, - PublicKey, - SystemProgram, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; -import * as borsh from "borsh"; -import { start } from "solana-bankrun"; +import { describe } from "node:test"; describe("PDA Rent-Payer", async () => { console.log("PDA Rent-Payer"); diff --git a/basics/processing-instructions/anchor/package.json b/basics/processing-instructions/anchor/package.json index 0696e9344..a77db16c0 100644 --- a/basics/processing-instructions/anchor/package.json +++ b/basics/processing-instructions/anchor/package.json @@ -1,17 +1,17 @@ { - "type": "module", - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/web3.js": "^1.98.4", - "litesvm": "^0.4.0" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/web3.js": "^1.98.4", + "litesvm": "^0.4.0" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/basics/processing-instructions/anchor/tests/litesvm.test.ts b/basics/processing-instructions/anchor/tests/litesvm.test.ts index 096d394ee..b943c6780 100644 --- a/basics/processing-instructions/anchor/tests/litesvm.test.ts +++ b/basics/processing-instructions/anchor/tests/litesvm.test.ts @@ -1,83 +1,73 @@ import anchor from "@anchor-lang/core"; -import { - Keypair, - PublicKey, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; +import { Keypair, PublicKey, Transaction, TransactionInstruction } from "@solana/web3.js"; import { LiteSVM } from "litesvm"; -import IDL from "../target/idl/processing_instructions.json" with { - type: "json", -}; +import IDL from "../target/idl/processing_instructions.json" with { type: "json" }; describe("LiteSVM: custom-instruction-data", () => { - const svm = new LiteSVM(); - const programId = new PublicKey(IDL.address); - /** - * Creates a coder to easily build and encode program instructions based on the IDL. - */ - const coder = new anchor.BorshCoder(IDL as anchor.Idl); + const svm = new LiteSVM(); + const programId = new PublicKey(IDL.address); + /** + * Creates a coder to easily build and encode program instructions based on the IDL. + */ + const coder = new anchor.BorshCoder(IDL as anchor.Idl); - const payer = Keypair.generate(); - svm.airdrop(payer.publicKey, BigInt(1000000000)); + const payer = Keypair.generate(); + svm.airdrop(payer.publicKey, BigInt(1000000000)); - /** - * Load the processing_instructions program binary into the LiteSVM instance - * for local testing and simulation. - */ - const programPath = new URL( - "../target/deploy/processing_instructions.so", - import.meta.url, - ).pathname; - svm.addProgramFromFile(programId, programPath); + /** + * Load the processing_instructions program binary into the LiteSVM instance + * for local testing and simulation. + */ + const programPath = new URL("../target/deploy/processing_instructions.so", import.meta.url).pathname; + svm.addProgramFromFile(programId, programPath); - it("Go to the park!", () => { - /** - * Create an instruction for the 'go_to_park' method using the Anchor coder. - * Arguments are needed for this instruction so we give inside `{}`. - */ - const ixArgs = { - name: "Jimmy", - height: 5, - }; - const data = coder.instruction.encode("go_to_park", ixArgs); + it("Go to the park!", () => { + /** + * Create an instruction for the 'go_to_park' method using the Anchor coder. + * Arguments are needed for this instruction so we give inside `{}`. + */ + const ixArgs = { + name: "Jimmy", + height: 5, + }; + const data = coder.instruction.encode("go_to_park", ixArgs); - /** - * Build and sign a transaction to call the 'go_to_park' instruction - * on the processing_instructions program with LiteSVM. - */ - const ix = new TransactionInstruction({ - keys: [], - programId, - data, - }); + /** + * Build and sign a transaction to call the 'go_to_park' instruction + * on the processing_instructions program with LiteSVM. + */ + const ix = new TransactionInstruction({ + keys: [], + programId, + data, + }); - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer); - svm.sendTransaction(tx); - svm.expireBlockhash(); + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer); + svm.sendTransaction(tx); + svm.expireBlockhash(); - /** - * For Mary , height: 10 - */ - const ixArgs2 = { - name: "Mary", - height: 10, - }; - const data2 = coder.instruction.encode("go_to_park", ixArgs2); + /** + * For Mary , height: 10 + */ + const ixArgs2 = { + name: "Mary", + height: 10, + }; + const data2 = coder.instruction.encode("go_to_park", ixArgs2); - const ix2 = new TransactionInstruction({ - keys: [], - programId, - data: data2, - }); + const ix2 = new TransactionInstruction({ + keys: [], + programId, + data: data2, + }); - const tx2 = new Transaction().add(ix2); - tx2.feePayer = payer.publicKey; - tx2.recentBlockhash = svm.latestBlockhash(); - tx2.sign(payer); - svm.sendTransaction(tx2); - }); + const tx2 = new Transaction().add(ix2); + tx2.feePayer = payer.publicKey; + tx2.recentBlockhash = svm.latestBlockhash(); + tx2.sign(payer); + svm.sendTransaction(tx2); + }); }); diff --git a/basics/processing-instructions/anchor/tests/test.ts b/basics/processing-instructions/anchor/tests/test.ts index debaf2f63..5e26f7296 100644 --- a/basics/processing-instructions/anchor/tests/test.ts +++ b/basics/processing-instructions/anchor/tests/test.ts @@ -1,15 +1,15 @@ -import * as anchor from '@anchor-lang/core'; -import type { ProcessingInstructions } from '../target/types/processing_instructions'; +import * as anchor from "@anchor-lang/core"; +import type { ProcessingInstructions } from "../target/types/processing_instructions"; -describe('custom-instruction-data', () => { +describe("custom-instruction-data", () => { const provider = anchor.AnchorProvider.env(); anchor.setProvider(provider); const program = anchor.workspace.ProcessingInstructions as anchor.Program; - it('Go to the park!', async () => { + it("Go to the park!", async () => { // Again, Anchor makes it super simple. // - await program.methods.goToPark('Jimmy', 3).accounts({}).rpc(); - await program.methods.goToPark('Mary', 10).accounts({}).rpc(); + await program.methods.goToPark("Jimmy", 3).accounts({}).rpc(); + await program.methods.goToPark("Mary", 10).accounts({}).rpc(); }); }); diff --git a/basics/processing-instructions/anchor/tsconfig.json b/basics/processing-instructions/anchor/tsconfig.json index 59fe75cf0..beb254c00 100644 --- a/basics/processing-instructions/anchor/tsconfig.json +++ b/basics/processing-instructions/anchor/tsconfig.json @@ -1,10 +1,10 @@ { - "compilerOptions": { - "types": ["mocha", "chai"], - "typeRoots": ["./node_modules/@types"], - "lib": ["es2015"], - "module": "nodenext", - "target": "es6", - "esModuleInterop": true - } + "compilerOptions": { + "types": ["mocha", "chai"], + "typeRoots": ["./node_modules/@types"], + "lib": ["es2015"], + "module": "nodenext", + "target": "es6", + "esModuleInterop": true + } } diff --git a/basics/processing-instructions/native/tests/test.ts b/basics/processing-instructions/native/tests/test.ts index 3964cc912..e77b04772 100644 --- a/basics/processing-instructions/native/tests/test.ts +++ b/basics/processing-instructions/native/tests/test.ts @@ -1,19 +1,19 @@ -import { Buffer } from 'node:buffer'; -import { describe, test } from 'node:test'; -import { PublicKey, Transaction, TransactionInstruction } from '@solana/web3.js'; -import * as borsh from 'borsh'; -import { start } from 'solana-bankrun'; +import { Buffer } from "node:buffer"; +import { describe, test } from "node:test"; +import { PublicKey, Transaction, TransactionInstruction } from "@solana/web3.js"; +import * as borsh from "borsh"; +import { start } from "solana-bankrun"; -describe('custom-instruction-data', async () => { +describe("custom-instruction-data", async () => { const PROGRAM_ID = PublicKey.unique(); - const context = await start([{ name: 'processing_instructions_program', programId: PROGRAM_ID }], []); + const context = await start([{ name: "processing_instructions_program", programId: PROGRAM_ID }], []); const client = context.banksClient; const payer = context.payer; const InstructionDataSchema = { struct: { - name: 'string', - height: 'u32', + name: "string", + height: "u32", }, }; @@ -21,11 +21,17 @@ describe('custom-instruction-data', async () => { return Buffer.from(borsh.serialize(schema, data)); } - test('Go to the park!', async () => { + test("Go to the park!", async () => { const blockhash = context.lastBlockhash; - const jimmy = borshSerialize(InstructionDataSchema, { name: 'Jimmy', height: 3 }); - const mary = borshSerialize(InstructionDataSchema, { name: 'Mary', height: 10 }); + const jimmy = borshSerialize(InstructionDataSchema, { + name: "Jimmy", + height: 3, + }); + const mary = borshSerialize(InstructionDataSchema, { + name: "Mary", + height: 10, + }); const ix1 = new TransactionInstruction({ keys: [{ pubkey: payer.publicKey, isSigner: true, isWritable: true }], diff --git a/basics/processing-instructions/pinocchio/tests/test.ts b/basics/processing-instructions/pinocchio/tests/test.ts index b5be3aecb..a4fe7c67d 100644 --- a/basics/processing-instructions/pinocchio/tests/test.ts +++ b/basics/processing-instructions/pinocchio/tests/test.ts @@ -1,12 +1,4 @@ -import { Buffer } from "node:buffer"; -import { describe, test } from "node:test"; -import { - PublicKey, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; -import * as borsh from "borsh"; -import { start } from "solana-bankrun"; +import { describe } from "node:test"; describe("custom-instruction-data", async () => { console.log("custom-instruction-data"); diff --git a/basics/program-derived-addresses/anchor/package.json b/basics/program-derived-addresses/anchor/package.json index 0696e9344..a77db16c0 100644 --- a/basics/program-derived-addresses/anchor/package.json +++ b/basics/program-derived-addresses/anchor/package.json @@ -1,17 +1,17 @@ { - "type": "module", - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/web3.js": "^1.98.4", - "litesvm": "^0.4.0" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/web3.js": "^1.98.4", + "litesvm": "^0.4.0" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/basics/program-derived-addresses/anchor/tests/litesvm.test.ts b/basics/program-derived-addresses/anchor/tests/litesvm.test.ts index 84c78cb7c..cf597e954 100644 --- a/basics/program-derived-addresses/anchor/tests/litesvm.test.ts +++ b/basics/program-derived-addresses/anchor/tests/litesvm.test.ts @@ -1,119 +1,99 @@ import anchor from "@anchor-lang/core"; -import { - Keypair, - PublicKey, - SystemProgram, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; +import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction } from "@solana/web3.js"; import { assert } from "chai"; import { LiteSVM } from "litesvm"; -import IDL from "../target/idl/program_derived_addresses_program.json" with { - type: "json", -}; +import IDL from "../target/idl/program_derived_addresses_program.json" with { type: "json" }; describe("LiteSVM: PDA", () => { - const svm = new LiteSVM(); - const programId = new PublicKey(IDL.address); - const coder = new anchor.BorshCoder(IDL as anchor.Idl); - - const payer = Keypair.generate(); - svm.airdrop(payer.publicKey, BigInt(1000000000)); - - const programPath = new URL( - "../target/deploy/program_derived_addresses_program.so", - import.meta.url, - ).pathname; - svm.addProgramFromFile(programId, programPath); - - // PDA for the page visits account - const [pageVisitPDA] = PublicKey.findProgramAddressSync( - [Buffer.from("page_visits"), payer.publicKey.toBuffer()], - programId, - ); - - it("Create the page visits tracking PDA", () => { - const data = coder.instruction.encode("create_page_visits", {}); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: pageVisitPDA, isSigner: false, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId, - data, - }); - - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer); - svm.sendTransaction(tx); - - //Fetch the pageVisitPDA account and check it page visit count - const pageVisitPDAAccInfo = svm.getAccount(pageVisitPDA); - const pageVisitAccount = coder.accounts.decode( - "PageVisits", - Buffer.from(pageVisitPDAAccInfo.data), - ); - - assert.equal(pageVisitAccount.page_visits, 0); - }); - - it("Visit the page!", () => { - const data = coder.instruction.encode("increment_page_visits", {}); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: pageVisitPDA, isSigner: false, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId, - data, - }); - - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer); - svm.sendTransaction(tx); - svm.expireBlockhash(); - - //Fetch the pageVisitPDA account and check it page visit count - const pageVisitPDAAccInfo = svm.getAccount(pageVisitPDA); - const pageVisitAccount = coder.accounts.decode( - "PageVisits", - Buffer.from(pageVisitPDAAccInfo.data), - ); - - assert.equal(pageVisitAccount.page_visits, 1); - }); - - it("Again visit the page!", () => { - const data = coder.instruction.encode("increment_page_visits", {}); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: pageVisitPDA, isSigner: false, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId, - data, - }); - - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer); - svm.sendTransaction(tx); - - //Fetch the pageVisitPDA account and check it page visit count - const pageVisitPDAAccInfo = svm.getAccount(pageVisitPDA); - const pageVisitAccount = coder.accounts.decode( - "PageVisits", - Buffer.from(pageVisitPDAAccInfo.data), - ); - - assert.equal(pageVisitAccount.page_visits, 2); - }); + const svm = new LiteSVM(); + const programId = new PublicKey(IDL.address); + const coder = new anchor.BorshCoder(IDL as anchor.Idl); + + const payer = Keypair.generate(); + svm.airdrop(payer.publicKey, BigInt(1000000000)); + + const programPath = new URL("../target/deploy/program_derived_addresses_program.so", import.meta.url).pathname; + svm.addProgramFromFile(programId, programPath); + + // PDA for the page visits account + const [pageVisitPDA] = PublicKey.findProgramAddressSync( + [Buffer.from("page_visits"), payer.publicKey.toBuffer()], + programId, + ); + + it("Create the page visits tracking PDA", () => { + const data = coder.instruction.encode("create_page_visits", {}); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: pageVisitPDA, isSigner: false, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId, + data, + }); + + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer); + svm.sendTransaction(tx); + + //Fetch the pageVisitPDA account and check it page visit count + const pageVisitPDAAccInfo = svm.getAccount(pageVisitPDA); + const pageVisitAccount = coder.accounts.decode("PageVisits", Buffer.from(pageVisitPDAAccInfo.data)); + + assert.equal(pageVisitAccount.page_visits, 0); + }); + + it("Visit the page!", () => { + const data = coder.instruction.encode("increment_page_visits", {}); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: pageVisitPDA, isSigner: false, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId, + data, + }); + + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer); + svm.sendTransaction(tx); + svm.expireBlockhash(); + + //Fetch the pageVisitPDA account and check it page visit count + const pageVisitPDAAccInfo = svm.getAccount(pageVisitPDA); + const pageVisitAccount = coder.accounts.decode("PageVisits", Buffer.from(pageVisitPDAAccInfo.data)); + + assert.equal(pageVisitAccount.page_visits, 1); + }); + + it("Again visit the page!", () => { + const data = coder.instruction.encode("increment_page_visits", {}); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: pageVisitPDA, isSigner: false, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId, + data, + }); + + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer); + svm.sendTransaction(tx); + + //Fetch the pageVisitPDA account and check it page visit count + const pageVisitPDAAccInfo = svm.getAccount(pageVisitPDA); + const pageVisitAccount = coder.accounts.decode("PageVisits", Buffer.from(pageVisitPDAAccInfo.data)); + + assert.equal(pageVisitAccount.page_visits, 2); + }); }); diff --git a/basics/program-derived-addresses/anchor/tests/test.ts b/basics/program-derived-addresses/anchor/tests/test.ts index da096db2a..9e6663f27 100644 --- a/basics/program-derived-addresses/anchor/tests/test.ts +++ b/basics/program-derived-addresses/anchor/tests/test.ts @@ -4,51 +4,50 @@ import { assert } from "chai"; import type { ProgramDerivedAddressesProgram } from "../target/types/program_derived_addresses_program.ts"; describe("Anchor: PDAs", () => { - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); - const payer = provider.wallet as anchor.Wallet; - const program = anchor.workspace - .ProgramDerivedAddressesProgram as anchor.Program; - - // PDA for the page visits account - const [pageVisitPDA] = PublicKey.findProgramAddressSync( - [Buffer.from("page_visits"), payer.publicKey.toBuffer()], - program.programId, - ); - - it("Create the page visits tracking PDA", async () => { - await program.methods - .createPageVisits() - .accounts({ - payer: payer.publicKey, - }) - .rpc(); - - const pageVisits = await program.account.pageVisits.fetch(pageVisitPDA); - assert.equal(pageVisits.pageVisits, 0); - }); - - it("Visit the page!", async () => { - await program.methods - .incrementPageVisits() - .accounts({ - user: payer.publicKey, - }) - .rpc(); - - const pageVisits = await program.account.pageVisits.fetch(pageVisitPDA); - assert.equal(pageVisits.pageVisits, 1); - }); - - it("Again visit the page!", async () => { - await program.methods - .incrementPageVisits() - .accounts({ - user: payer.publicKey, - }) - .rpc(); - - const pageVisits = await program.account.pageVisits.fetch(pageVisitPDA); - assert.equal(pageVisits.pageVisits, 2); - }); + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); + const payer = provider.wallet as anchor.Wallet; + const program = anchor.workspace.ProgramDerivedAddressesProgram as anchor.Program; + + // PDA for the page visits account + const [pageVisitPDA] = PublicKey.findProgramAddressSync( + [Buffer.from("page_visits"), payer.publicKey.toBuffer()], + program.programId, + ); + + it("Create the page visits tracking PDA", async () => { + await program.methods + .createPageVisits() + .accounts({ + payer: payer.publicKey, + }) + .rpc(); + + const pageVisits = await program.account.pageVisits.fetch(pageVisitPDA); + assert.equal(pageVisits.pageVisits, 0); + }); + + it("Visit the page!", async () => { + await program.methods + .incrementPageVisits() + .accounts({ + user: payer.publicKey, + }) + .rpc(); + + const pageVisits = await program.account.pageVisits.fetch(pageVisitPDA); + assert.equal(pageVisits.pageVisits, 1); + }); + + it("Again visit the page!", async () => { + await program.methods + .incrementPageVisits() + .accounts({ + user: payer.publicKey, + }) + .rpc(); + + const pageVisits = await program.account.pageVisits.fetch(pageVisitPDA); + assert.equal(pageVisits.pageVisits, 2); + }); }); diff --git a/basics/program-derived-addresses/anchor/tsconfig.json b/basics/program-derived-addresses/anchor/tsconfig.json index 59fe75cf0..beb254c00 100644 --- a/basics/program-derived-addresses/anchor/tsconfig.json +++ b/basics/program-derived-addresses/anchor/tsconfig.json @@ -1,10 +1,10 @@ { - "compilerOptions": { - "types": ["mocha", "chai"], - "typeRoots": ["./node_modules/@types"], - "lib": ["es2015"], - "module": "nodenext", - "target": "es6", - "esModuleInterop": true - } + "compilerOptions": { + "types": ["mocha", "chai"], + "typeRoots": ["./node_modules/@types"], + "lib": ["es2015"], + "module": "nodenext", + "target": "es6", + "esModuleInterop": true + } } diff --git a/basics/program-derived-addresses/native/tests/test.ts b/basics/program-derived-addresses/native/tests/test.ts index 805bc7083..3065e8c5f 100644 --- a/basics/program-derived-addresses/native/tests/test.ts +++ b/basics/program-derived-addresses/native/tests/test.ts @@ -1,20 +1,28 @@ -import { Buffer } from 'node:buffer'; -import { describe, test } from 'node:test'; -import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction } from '@solana/web3.js'; -import * as borsh from 'borsh'; -import { start } from 'solana-bankrun'; +import { Buffer } from "node:buffer"; +import { describe, test } from "node:test"; +import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction } from "@solana/web3.js"; +import * as borsh from "borsh"; +import { start } from "solana-bankrun"; -describe('PDAs', async () => { +describe("PDAs", async () => { const PROGRAM_ID = PublicKey.unique(); - const context = await start([{ name: 'program_derived_addresses_native_program', programId: PROGRAM_ID }], []); + const context = await start( + [ + { + name: "program_derived_addresses_native_program", + programId: PROGRAM_ID, + }, + ], + [], + ); const client = context.banksClient; const payer = context.payer; const rent = await client.getRent(); const PageVisitsSchema = { struct: { - page_visits: 'u32', - bump: 'u8', + page_visits: "u32", + bump: "u8", }, }; @@ -27,7 +35,7 @@ describe('PDAs', async () => { const testUser = Keypair.generate(); - test('Create a test user', async () => { + test("Create a test user", async () => { const ix = SystemProgram.createAccount({ fromPubkey: payer.publicKey, lamports: Number(rent.minimumBalance(BigInt(0))), @@ -47,10 +55,10 @@ describe('PDAs', async () => { }); function derivePageVisitsPda(userPubkey: PublicKey) { - return PublicKey.findProgramAddressSync([Buffer.from('page_visits'), userPubkey.toBuffer()], PROGRAM_ID); + return PublicKey.findProgramAddressSync([Buffer.from("page_visits"), userPubkey.toBuffer()], PROGRAM_ID); } - test('Create the page visits tracking PDA', async () => { + test("Create the page visits tracking PDA", async () => { const [pageVisitsPda, pageVisitsBump] = derivePageVisitsPda(testUser.publicKey); const ix = new TransactionInstruction({ keys: [ @@ -60,7 +68,10 @@ describe('PDAs', async () => { { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, ], programId: PROGRAM_ID, - data: borshSerialize(PageVisitsSchema, { page_visits: 0, bump: pageVisitsBump }), + data: borshSerialize(PageVisitsSchema, { + page_visits: 0, + bump: pageVisitsBump, + }), }); const tx = new Transaction(); const blockhash = context.lastBlockhash; @@ -70,7 +81,7 @@ describe('PDAs', async () => { await client.processTransaction(tx); }); - test('Visit the page!', async () => { + test("Visit the page!", async () => { const [pageVisitsPda, _] = derivePageVisitsPda(testUser.publicKey); const ix = new TransactionInstruction({ keys: [ @@ -88,7 +99,7 @@ describe('PDAs', async () => { await client.processTransaction(tx); }); - test('Visit the page!', async () => { + test("Visit the page!", async () => { const [pageVisitsPda, _] = derivePageVisitsPda(testUser.publicKey); const ix = new TransactionInstruction({ keys: [ @@ -106,10 +117,13 @@ describe('PDAs', async () => { await client.processTransaction(tx); }); - test('Read page visits', async () => { + test("Read page visits", async () => { const [pageVisitsPda, _] = derivePageVisitsPda(testUser.publicKey); const accountInfo = await client.getAccount(pageVisitsPda); - const readPageVisits = borsh.deserialize(PageVisitsSchema, Buffer.from(accountInfo.data)) as { page_visits: number; bump: number }; + const readPageVisits = borsh.deserialize(PageVisitsSchema, Buffer.from(accountInfo.data)) as { + page_visits: number; + bump: number; + }; console.log(`Number of page visits: ${readPageVisits.page_visits}`); }); }); diff --git a/basics/program-derived-addresses/pinocchio/tests/test.ts b/basics/program-derived-addresses/pinocchio/tests/test.ts index b197963e8..892781bf9 100644 --- a/basics/program-derived-addresses/pinocchio/tests/test.ts +++ b/basics/program-derived-addresses/pinocchio/tests/test.ts @@ -1,14 +1,4 @@ -import { Buffer } from "node:buffer"; -import { describe, test } from "node:test"; -import { - Keypair, - PublicKey, - SystemProgram, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; -import * as borsh from "borsh"; -import { start } from "solana-bankrun"; +import { describe } from "node:test"; describe("PDAs", async () => { console.log("PDAS"); diff --git a/basics/realloc/anchor/migrations/deploy.ts b/basics/realloc/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/basics/realloc/anchor/migrations/deploy.ts +++ b/basics/realloc/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/basics/realloc/anchor/package.json b/basics/realloc/anchor/package.json index 3335c7917..fd06afc13 100644 --- a/basics/realloc/anchor/package.json +++ b/basics/realloc/anchor/package.json @@ -1,22 +1,22 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/web3.js": "^1.98.4", - "litesvm": "^0.4.0" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.4.1", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/web3.js": "^1.98.4", + "litesvm": "^0.4.0" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.4.1", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/basics/realloc/anchor/tests/litesvm.test.ts b/basics/realloc/anchor/tests/litesvm.test.ts index e45976d50..e83294416 100644 --- a/basics/realloc/anchor/tests/litesvm.test.ts +++ b/basics/realloc/anchor/tests/litesvm.test.ts @@ -1,125 +1,107 @@ import anchor from "@anchor-lang/core"; -import { - Keypair, - PublicKey, - SystemProgram, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; +import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction } from "@solana/web3.js"; import { assert } from "chai"; import { LiteSVM } from "litesvm"; import IDL from "../target/idl/anchor_realloc.json" with { type: "json" }; describe("LiteSVM: realloc", () => { - const svm = new LiteSVM(); - const programId = new PublicKey(IDL.address); - const coder = new anchor.BorshCoder(IDL as anchor.Idl); + const svm = new LiteSVM(); + const programId = new PublicKey(IDL.address); + const coder = new anchor.BorshCoder(IDL as anchor.Idl); - const payer = Keypair.generate(); - svm.airdrop(payer.publicKey, BigInt(1000000000)); + const payer = Keypair.generate(); + svm.airdrop(payer.publicKey, BigInt(1000000000)); - const programPath = new URL( - "../target/deploy/anchor_realloc.so", - import.meta.url, - ).pathname; - svm.addProgramFromFile(programId, programPath); + const programPath = new URL("../target/deploy/anchor_realloc.so", import.meta.url).pathname; + svm.addProgramFromFile(programId, programPath); - // PDA for the message account - const messageAccount = new Keypair(); + // PDA for the message account + const messageAccount = new Keypair(); - it("Is initialized!", () => { - const message = "hello"; - const data = coder.instruction.encode("initialize", { - input: message, - }); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: messageAccount.publicKey, isSigner: true, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId, - data, - }); + it("Is initialized!", () => { + const message = "hello"; + const data = coder.instruction.encode("initialize", { + input: message, + }); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: messageAccount.publicKey, isSigner: true, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId, + data, + }); - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer, messageAccount); - svm.sendTransaction(tx); + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer, messageAccount); + svm.sendTransaction(tx); - //Fetch the message account and check it message - const messageAccInfo = svm.getAccount(messageAccount.publicKey); - const messageAcc = coder.accounts.decode( - "Message", - Buffer.from(messageAccInfo.data), - ); - assert.equal(messageAccInfo.data.length, 8 + 4 + message.length); - assert.equal(messageAcc.message, message); - }); + //Fetch the message account and check it message + const messageAccInfo = svm.getAccount(messageAccount.publicKey); + const messageAcc = coder.accounts.decode("Message", Buffer.from(messageAccInfo.data)); + assert.equal(messageAccInfo.data.length, 8 + 4 + message.length); + assert.equal(messageAcc.message, message); + }); - it("Update", () => { - const message = "hello world"; - const data = coder.instruction.encode("update", { - input: message, - }); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: messageAccount.publicKey, isSigner: false, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId, - data, - }); + it("Update", () => { + const message = "hello world"; + const data = coder.instruction.encode("update", { + input: message, + }); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: messageAccount.publicKey, isSigner: false, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId, + data, + }); - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer); - svm.sendTransaction(tx); - svm.expireBlockhash(); + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer); + svm.sendTransaction(tx); + svm.expireBlockhash(); - //Fetch the message account and check it message - const messageAccInfo = svm.getAccount(messageAccount.publicKey); - const messageAcc = coder.accounts.decode( - "Message", - Buffer.from(messageAccInfo.data), - ); - assert.equal(messageAccInfo.data.length, 8 + 4 + message.length); - assert.equal(messageAcc.message, message); - }); + //Fetch the message account and check it message + const messageAccInfo = svm.getAccount(messageAccount.publicKey); + const messageAcc = coder.accounts.decode("Message", Buffer.from(messageAccInfo.data)); + assert.equal(messageAccInfo.data.length, 8 + 4 + message.length); + assert.equal(messageAcc.message, message); + }); - it("Again update", () => { - const message = "hi"; - const data = coder.instruction.encode("update", { - input: message, - }); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: messageAccount.publicKey, isSigner: false, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId, - data, - }); + it("Again update", () => { + const message = "hi"; + const data = coder.instruction.encode("update", { + input: message, + }); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: messageAccount.publicKey, isSigner: false, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId, + data, + }); - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer); - svm.sendTransaction(tx); - svm.expireBlockhash(); + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer); + svm.sendTransaction(tx); + svm.expireBlockhash(); - //Fetch the message account and check it message - const messageAccInfo = svm.getAccount(messageAccount.publicKey); - const messageAcc = coder.accounts.decode( - "Message", - Buffer.from(messageAccInfo.data), - ); + //Fetch the message account and check it message + const messageAccInfo = svm.getAccount(messageAccount.publicKey); + const messageAcc = coder.accounts.decode("Message", Buffer.from(messageAccInfo.data)); - assert.equal(messageAccInfo.data.length, 8 + 4 + message.length); - assert.equal(messageAcc.message, message); - }); + assert.equal(messageAccInfo.data.length, 8 + 4 + message.length); + assert.equal(messageAcc.message, message); + }); }); diff --git a/basics/realloc/anchor/tests/test.ts b/basics/realloc/anchor/tests/test.ts index be04c637d..8ae3ab45d 100644 --- a/basics/realloc/anchor/tests/test.ts +++ b/basics/realloc/anchor/tests/test.ts @@ -5,68 +5,68 @@ import { assert } from "chai"; import type { AnchorRealloc } from "../target/types/anchor_realloc.ts"; describe("Anchor: realloc", () => { - // Configure the client to use the local cluster. - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); - const payer = provider.wallet as anchor.Wallet; - const connection = provider.connection; + // Configure the client to use the local cluster. + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); + const payer = provider.wallet as anchor.Wallet; + const connection = provider.connection; - const program = anchor.workspace.AnchorRealloc as Program; + const program = anchor.workspace.AnchorRealloc as Program; - const messageAccount = new Keypair(); + const messageAccount = new Keypair(); - // helper function to check the account data and message - async function checkAccount(publicKey, expectedMessage) { - const accountInfo = await connection.getAccountInfo(publicKey); - const accountData = await program.account.message.fetch(publicKey); + // helper function to check the account data and message + async function checkAccount(publicKey, expectedMessage) { + const accountInfo = await connection.getAccountInfo(publicKey); + const accountData = await program.account.message.fetch(publicKey); - // 8 bytes for the discriminator, - // 4 bytes for the length of the message, - // and the length of the message - assert.equal(accountInfo.data.length, 8 + 4 + expectedMessage.length); - assert.equal(accountData.message, expectedMessage); - } + // 8 bytes for the discriminator, + // 4 bytes for the length of the message, + // and the length of the message + assert.equal(accountInfo.data.length, 8 + 4 + expectedMessage.length); + assert.equal(accountData.message, expectedMessage); + } - it("Is initialized!", async () => { - const input = "hello"; + it("Is initialized!", async () => { + const input = "hello"; - await program.methods - .initialize(input) - .accounts({ - payer: payer.publicKey, - messageAccount: messageAccount.publicKey, - }) - .signers([messageAccount]) - .rpc(); + await program.methods + .initialize(input) + .accounts({ + payer: payer.publicKey, + messageAccount: messageAccount.publicKey, + }) + .signers([messageAccount]) + .rpc(); - await checkAccount(messageAccount.publicKey, input); - }); + await checkAccount(messageAccount.publicKey, input); + }); - it("Update", async () => { - const input = "hello world"; + it("Update", async () => { + const input = "hello world"; - await program.methods - .update(input) - .accounts({ - payer: payer.publicKey, - messageAccount: messageAccount.publicKey, - }) - .rpc(); + await program.methods + .update(input) + .accounts({ + payer: payer.publicKey, + messageAccount: messageAccount.publicKey, + }) + .rpc(); - await checkAccount(messageAccount.publicKey, input); - }); + await checkAccount(messageAccount.publicKey, input); + }); - it("Again update", async () => { - const input = "hi"; + it("Again update", async () => { + const input = "hi"; - await program.methods - .update(input) - .accounts({ - payer: payer.publicKey, - messageAccount: messageAccount.publicKey, - }) - .rpc(); + await program.methods + .update(input) + .accounts({ + payer: payer.publicKey, + messageAccount: messageAccount.publicKey, + }) + .rpc(); - await checkAccount(messageAccount.publicKey, input); - }); + await checkAccount(messageAccount.publicKey, input); + }); }); diff --git a/basics/realloc/anchor/tsconfig.json b/basics/realloc/anchor/tsconfig.json index 59fe75cf0..beb254c00 100644 --- a/basics/realloc/anchor/tsconfig.json +++ b/basics/realloc/anchor/tsconfig.json @@ -1,10 +1,10 @@ { - "compilerOptions": { - "types": ["mocha", "chai"], - "typeRoots": ["./node_modules/@types"], - "lib": ["es2015"], - "module": "nodenext", - "target": "es6", - "esModuleInterop": true - } + "compilerOptions": { + "types": ["mocha", "chai"], + "typeRoots": ["./node_modules/@types"], + "lib": ["es2015"], + "module": "nodenext", + "target": "es6", + "esModuleInterop": true + } } diff --git a/basics/realloc/native/tests/realloc.test.ts b/basics/realloc/native/tests/realloc.test.ts index 08c39058c..53ef0b78c 100644 --- a/basics/realloc/native/tests/realloc.test.ts +++ b/basics/realloc/native/tests/realloc.test.ts @@ -1,6 +1,6 @@ -import { describe, test } from 'node:test'; -import { Keypair, PublicKey, Transaction } from '@solana/web3.js'; -import { start } from 'solana-bankrun'; +import { describe, test } from "node:test"; +import { Keypair, PublicKey, Transaction } from "@solana/web3.js"; +import { start } from "solana-bankrun"; import { AddressInfo, createCreateInstruction, @@ -8,19 +8,27 @@ import { createReallocateZeroInitInstruction, EnhancedAddressInfo, WorkInfo, -} from '../ts'; +} from "../ts"; -describe('Realloc!', async () => { +describe("Realloc!", async () => { const PROGRAM_ID = PublicKey.unique(); - const context = await start([{ name: 'realloc_program', programId: PROGRAM_ID }], []); + const context = await start([{ name: "realloc_program", programId: PROGRAM_ID }], []); const client = context.banksClient; const payer = context.payer; const testAccount = Keypair.generate(); - test('Create the account with data', async () => { + test("Create the account with data", async () => { console.log(`${testAccount.publicKey}`); - const ix = createCreateInstruction(testAccount.publicKey, payer.publicKey, PROGRAM_ID, 'Jacob', 123, 'Main St.', 'Chicago'); + const ix = createCreateInstruction( + testAccount.publicKey, + payer.publicKey, + PROGRAM_ID, + "Jacob", + 123, + "Main St.", + "Chicago", + ); const tx = new Transaction(); tx.recentBlockhash = context.lastBlockhash; @@ -30,8 +38,14 @@ describe('Realloc!', async () => { await printAddressInfo(testAccount.publicKey); }); - test('Reallocate WITHOUT zero init', async () => { - const ix = createReallocateWithoutZeroInitInstruction(testAccount.publicKey, payer.publicKey, PROGRAM_ID, 'Illinois', 12345); + test("Reallocate WITHOUT zero init", async () => { + const ix = createReallocateWithoutZeroInitInstruction( + testAccount.publicKey, + payer.publicKey, + PROGRAM_ID, + "Illinois", + 12345, + ); const tx = new Transaction(); const [blockHash, _blockHeight] = await client.getLatestBlockhash(); tx.recentBlockhash = blockHash; @@ -41,8 +55,16 @@ describe('Realloc!', async () => { await printEnhancedAddressInfo(testAccount.publicKey); }); - test('Reallocate WITH zero init', async () => { - const ix = createReallocateZeroInitInstruction(testAccount.publicKey, payer.publicKey, PROGRAM_ID, 'Pete', 'Engineer', 'Solana Labs', 2); + test("Reallocate WITH zero init", async () => { + const ix = createReallocateZeroInitInstruction( + testAccount.publicKey, + payer.publicKey, + PROGRAM_ID, + "Pete", + "Engineer", + "Solana Labs", + 2, + ); const tx = new Transaction(); const [blockHash, _blockHeight] = await client.getLatestBlockhash(); tx.recentBlockhash = blockHash; @@ -58,7 +80,7 @@ describe('Realloc!', async () => { const data = (await client.getAccount(pubkey))?.data; if (data) { const addressInfo = AddressInfo.fromBuffer(Buffer.from(data)); - console.log('Address info:'); + console.log("Address info:"); console.log(` Name: ${addressInfo.name}`); console.log(` House Num: ${addressInfo.house_number}`); console.log(` Street: ${addressInfo.street}`); @@ -71,7 +93,7 @@ describe('Realloc!', async () => { const data = (await client.getAccount(pubkey))?.data; if (data) { const enhancedAddressInfo = EnhancedAddressInfo.fromBuffer(Buffer.from(data)); - console.log('Enhanced Address info:'); + console.log("Enhanced Address info:"); console.log(` Name: ${enhancedAddressInfo.name}`); console.log(` House Num: ${enhancedAddressInfo.house_number}`); console.log(` Street: ${enhancedAddressInfo.street}`); @@ -86,7 +108,7 @@ describe('Realloc!', async () => { const data = (await client.getAccount(pubkey))?.data; if (data) { const workInfo = WorkInfo.fromBuffer(Buffer.from(data)); - console.log('Work info:'); + console.log("Work info:"); console.log(` Name: ${workInfo.name}`); console.log(` Position: ${workInfo.position}`); console.log(` Company: ${workInfo.company}`); diff --git a/basics/realloc/native/ts/index.ts b/basics/realloc/native/ts/index.ts index 70c7f3510..9cfd68485 100644 --- a/basics/realloc/native/ts/index.ts +++ b/basics/realloc/native/ts/index.ts @@ -1,7 +1,7 @@ -export * from './instructions/create'; -export * from './instructions/instruction'; -export * from './instructions/reallocate'; -export * from './state/address-info'; -export * from './state/enhanced-address-info'; -export * from './state/work-info'; -export * from './util/util'; +export * from "./instructions/create"; +export * from "./instructions/instruction"; +export * from "./instructions/reallocate"; +export * from "./state/address-info"; +export * from "./state/enhanced-address-info"; +export * from "./state/work-info"; +export * from "./util/util"; diff --git a/basics/realloc/native/ts/instructions/create.ts b/basics/realloc/native/ts/instructions/create.ts index d60a9c800..3fbc6a84e 100644 --- a/basics/realloc/native/ts/instructions/create.ts +++ b/basics/realloc/native/ts/instructions/create.ts @@ -1,7 +1,7 @@ -import { Buffer } from 'node:buffer'; -import { type PublicKey, SystemProgram, TransactionInstruction } from '@solana/web3.js'; -import * as borsh from 'borsh'; -import { ReallocInstruction } from './instruction'; +import { Buffer } from "node:buffer"; +import { type PublicKey, SystemProgram, TransactionInstruction } from "@solana/web3.js"; +import * as borsh from "borsh"; +import { ReallocInstruction } from "./instruction"; export class Create { instruction: ReallocInstruction; @@ -37,13 +37,13 @@ export const CreateSchema = new Map([ [ Create, { - kind: 'struct', + kind: "struct", fields: [ - ['instruction', 'u8'], - ['name', 'string'], - ['house_number', 'u8'], - ['street', 'string'], - ['city', 'string'], + ["instruction", "u8"], + ["name", "string"], + ["house_number", "u8"], + ["street", "string"], + ["city", "string"], ], }, ], diff --git a/basics/realloc/native/ts/instructions/index.ts b/basics/realloc/native/ts/instructions/index.ts index a0876a284..dba00c454 100644 --- a/basics/realloc/native/ts/instructions/index.ts +++ b/basics/realloc/native/ts/instructions/index.ts @@ -1,3 +1,3 @@ -export * from './create'; -export * from './instruction'; -export * from './reallocate'; +export * from "./create"; +export * from "./instruction"; +export * from "./reallocate"; diff --git a/basics/realloc/native/ts/instructions/reallocate.ts b/basics/realloc/native/ts/instructions/reallocate.ts index 884872d26..197e711d6 100644 --- a/basics/realloc/native/ts/instructions/reallocate.ts +++ b/basics/realloc/native/ts/instructions/reallocate.ts @@ -1,7 +1,7 @@ -import { Buffer } from 'node:buffer'; -import { type PublicKey, SystemProgram, TransactionInstruction } from '@solana/web3.js'; -import * as borsh from 'borsh'; -import { ReallocInstruction } from './instruction'; +import { Buffer } from "node:buffer"; +import { type PublicKey, SystemProgram, TransactionInstruction } from "@solana/web3.js"; +import * as borsh from "borsh"; +import { ReallocInstruction } from "./instruction"; export class ReallocateWithoutZeroInit { instruction: ReallocInstruction; @@ -31,11 +31,11 @@ export const ReallocateWithoutZeroInitSchema = new Map([ [ ReallocateWithoutZeroInit, { - kind: 'struct', + kind: "struct", fields: [ - ['instruction', 'u8'], - ['state', 'string'], - ['zip', 'u32'], + ["instruction", "u8"], + ["state", "string"], + ["zip", "u32"], ], }, ], @@ -101,13 +101,13 @@ export const ReallocateZeroInitSchema = new Map([ [ ReallocateZeroInit, { - kind: 'struct', + kind: "struct", fields: [ - ['instruction', 'u8'], - ['name', 'string'], - ['position', 'string'], - ['company', 'string'], - ['years_employed', 'u8'], + ["instruction", "u8"], + ["name", "string"], + ["position", "string"], + ["company", "string"], + ["years_employed", "u8"], ], }, ], diff --git a/basics/realloc/native/ts/state/address-info.ts b/basics/realloc/native/ts/state/address-info.ts index d3a3e466f..6acf96c8a 100644 --- a/basics/realloc/native/ts/state/address-info.ts +++ b/basics/realloc/native/ts/state/address-info.ts @@ -1,5 +1,5 @@ -import { Buffer } from 'node:buffer'; -import * as borsh from 'borsh'; +import { Buffer } from "node:buffer"; +import * as borsh from "borsh"; export class AddressInfo { name: string; @@ -36,12 +36,12 @@ export const AddressInfoSchema = new Map([ [ AddressInfo, { - kind: 'struct', + kind: "struct", fields: [ - ['name', 'string'], - ['house_number', 'u8'], - ['street', 'string'], - ['city', 'string'], + ["name", "string"], + ["house_number", "u8"], + ["street", "string"], + ["city", "string"], ], }, ], diff --git a/basics/realloc/native/ts/state/enhanced-address-info.ts b/basics/realloc/native/ts/state/enhanced-address-info.ts index ba7f38b57..edbda7781 100644 --- a/basics/realloc/native/ts/state/enhanced-address-info.ts +++ b/basics/realloc/native/ts/state/enhanced-address-info.ts @@ -1,5 +1,5 @@ -import { Buffer } from 'node:buffer'; -import * as borsh from 'borsh'; +import { Buffer } from "node:buffer"; +import * as borsh from "borsh"; export class EnhancedAddressInfo { name: string; @@ -42,14 +42,14 @@ export const EnhancedAddressInfoSchema = new Map([ [ EnhancedAddressInfo, { - kind: 'struct', + kind: "struct", fields: [ - ['name', 'string'], - ['house_number', 'u8'], - ['street', 'string'], - ['city', 'string'], - ['state', 'string'], - ['zip', 'u32'], + ["name", "string"], + ["house_number", "u8"], + ["street", "string"], + ["city", "string"], + ["state", "string"], + ["zip", "u32"], ], }, ], diff --git a/basics/realloc/native/ts/state/index.ts b/basics/realloc/native/ts/state/index.ts index 5b4330eb5..2cc8c6587 100644 --- a/basics/realloc/native/ts/state/index.ts +++ b/basics/realloc/native/ts/state/index.ts @@ -1,3 +1,3 @@ -export * from './address-info'; -export * from './enhanced-address-info'; -export * from './work-info'; +export * from "./address-info"; +export * from "./enhanced-address-info"; +export * from "./work-info"; diff --git a/basics/realloc/native/ts/state/work-info.ts b/basics/realloc/native/ts/state/work-info.ts index 8275ba017..26a89ebec 100644 --- a/basics/realloc/native/ts/state/work-info.ts +++ b/basics/realloc/native/ts/state/work-info.ts @@ -1,5 +1,5 @@ -import { Buffer } from 'node:buffer'; -import * as borsh from 'borsh'; +import { Buffer } from "node:buffer"; +import * as borsh from "borsh"; export class WorkInfo { name: string; @@ -36,12 +36,12 @@ export const WorkInfoSchema = new Map([ [ WorkInfo, { - kind: 'struct', + kind: "struct", fields: [ - ['name', 'string'], - ['position', 'string'], - ['company', 'string'], - ['years_employed', 'u8'], + ["name", "string"], + ["position", "string"], + ["company", "string"], + ["years_employed", "u8"], ], }, ], diff --git a/basics/realloc/native/ts/util/index.ts b/basics/realloc/native/ts/util/index.ts index bbebd88eb..181e76f24 100644 --- a/basics/realloc/native/ts/util/index.ts +++ b/basics/realloc/native/ts/util/index.ts @@ -1 +1 @@ -export * from './util'; +export * from "./util"; diff --git a/basics/realloc/native/ts/util/util.ts b/basics/realloc/native/ts/util/util.ts index 0e63c77df..7e72414f8 100644 --- a/basics/realloc/native/ts/util/util.ts +++ b/basics/realloc/native/ts/util/util.ts @@ -1,5 +1,5 @@ -import { Keypair } from '@solana/web3.js'; +import { Keypair } from "@solana/web3.js"; export function createKeypairFromFile(path: string): Keypair { - return Keypair.fromSecretKey(Buffer.from(JSON.parse(require('node:fs').readFileSync(path, 'utf-8')))); + return Keypair.fromSecretKey(Buffer.from(JSON.parse(require("node:fs").readFileSync(path, "utf-8")))); } diff --git a/basics/realloc/pinocchio/tests/realloc.test.ts b/basics/realloc/pinocchio/tests/realloc.test.ts index 58b2b4fb5..4d32049cf 100644 --- a/basics/realloc/pinocchio/tests/realloc.test.ts +++ b/basics/realloc/pinocchio/tests/realloc.test.ts @@ -1,6 +1,4 @@ -import { describe, test } from "node:test"; -import { Keypair, PublicKey, Transaction } from "@solana/web3.js"; -import { start } from "solana-bankrun"; +import { describe } from "node:test"; describe("Realloc!", async () => { console.log("Realloc!"); diff --git a/basics/rent/anchor/package.json b/basics/rent/anchor/package.json index 0696e9344..a77db16c0 100644 --- a/basics/rent/anchor/package.json +++ b/basics/rent/anchor/package.json @@ -1,17 +1,17 @@ { - "type": "module", - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/web3.js": "^1.98.4", - "litesvm": "^0.4.0" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/web3.js": "^1.98.4", + "litesvm": "^0.4.0" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/basics/rent/anchor/tests/litesvm.test.ts b/basics/rent/anchor/tests/litesvm.test.ts index b102af9f0..c289d1e8a 100644 --- a/basics/rent/anchor/tests/litesvm.test.ts +++ b/basics/rent/anchor/tests/litesvm.test.ts @@ -1,74 +1,68 @@ import anchor from "@anchor-lang/core"; import { - Keypair, - LAMPORTS_PER_SOL, - PublicKey, - SystemProgram, - Transaction, - TransactionInstruction, + Keypair, + LAMPORTS_PER_SOL, + PublicKey, + SystemProgram, + Transaction, + TransactionInstruction, } from "@solana/web3.js"; import { assert } from "chai"; import { LiteSVM } from "litesvm"; import Idl from "../target/idl/rent_example.json" with { type: "json" }; describe("LiteSVM: Create a system account", () => { - const svm = new LiteSVM(); - const programId = new PublicKey(Idl.address); - const coder = new anchor.BorshCoder(Idl as anchor.Idl); + const svm = new LiteSVM(); + const programId = new PublicKey(Idl.address); + const coder = new anchor.BorshCoder(Idl as anchor.Idl); - const payer = Keypair.generate(); - svm.airdrop(payer.publicKey, BigInt(2 * LAMPORTS_PER_SOL)); + const payer = Keypair.generate(); + svm.airdrop(payer.publicKey, BigInt(2 * LAMPORTS_PER_SOL)); - const programPath = new URL( - "../target/deploy/rent_example.so", - import.meta.url, - ).pathname; - svm.addProgramFromFile(programId, programPath); + const programPath = new URL("../target/deploy/rent_example.so", import.meta.url).pathname; + svm.addProgramFromFile(programId, programPath); - it("Create the account", () => { - const newKeypair = Keypair.generate(); + it("Create the account", () => { + const newKeypair = Keypair.generate(); - const ixArgs = { - address_data: { - name: "Marcus", - address: "123 Main St. San Francisco, CA", - }, - }; + const ixArgs = { + address_data: { + name: "Marcus", + address: "123 Main St. San Francisco, CA", + }, + }; - /** - * Create Instructions - * Create Transactions - * Send Transactions - */ - const data = coder.instruction.encode("create_system_account", ixArgs); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: newKeypair.publicKey, isSigner: true, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId, - data, - }); + /** + * Create Instructions + * Create Transactions + * Send Transactions + */ + const data = coder.instruction.encode("create_system_account", ixArgs); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: newKeypair.publicKey, isSigner: true, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId, + data, + }); - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer, newKeypair); - svm.sendTransaction(tx); + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer, newKeypair); + svm.sendTransaction(tx); - /** - * We're just going to serialize our object here so we can check - * the size on the client side against the program logs - */ - const addressDataBuffer = coder.types.encode( - "AddressData", - ixArgs.address_data, - ); + /** + * We're just going to serialize our object here so we can check + * the size on the client side against the program logs + */ + const addressDataBuffer = coder.types.encode("AddressData", ixArgs.address_data); - //Fetch newKeypair account and check its rent for space - const newKeypairInfo = svm.getAccount(newKeypair.publicKey); + //Fetch newKeypair account and check its rent for space + const newKeypairInfo = svm.getAccount(newKeypair.publicKey); - assert.equal(newKeypairInfo.data.length, addressDataBuffer.length); - }); + assert.equal(newKeypairInfo.data.length, addressDataBuffer.length); + }); }); diff --git a/basics/rent/anchor/tests/test.ts b/basics/rent/anchor/tests/test.ts index 7755d3d47..fdea57a3a 100644 --- a/basics/rent/anchor/tests/test.ts +++ b/basics/rent/anchor/tests/test.ts @@ -4,39 +4,35 @@ import Idl from "../target/idl/rent_example.json" with { type: "json" }; import type { RentExample } from "../target/types/rent_example.ts"; describe("Anchor: Create a system account", () => { - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); - const wallet = provider.wallet as anchor.Wallet; - const program = anchor.workspace.RentExample as anchor.Program; + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); + const wallet = provider.wallet as anchor.Wallet; + const program = anchor.workspace.RentExample as anchor.Program; - it("Create the account", async () => { - const newKeypair = anchor.web3.Keypair.generate(); + it("Create the account", async () => { + const newKeypair = anchor.web3.Keypair.generate(); - const addressData: anchor.IdlTypes["addressData"] = { - name: "Marcus", - address: "123 Main St. San Francisco, CA", - }; + const addressData: anchor.IdlTypes["addressData"] = { + name: "Marcus", + address: "123 Main St. San Francisco, CA", + }; - // We're just going to serialize our object here so we can check - // the size on the client side against the program logs - // - const addressDataBuffer = new anchor.BorshCoder( - Idl as anchor.Idl, - ).types.encode("AddressData", addressData); + // We're just going to serialize our object here so we can check + // the size on the client side against the program logs + // + const addressDataBuffer = new anchor.BorshCoder(Idl as anchor.Idl).types.encode("AddressData", addressData); - await program.methods - .createSystemAccount(addressData) - .accounts({ - payer: wallet.publicKey, - newAccount: newKeypair.publicKey, - }) - .signers([wallet.payer, newKeypair]) - .rpc(); + await program.methods + .createSystemAccount(addressData) + .accounts({ + payer: wallet.publicKey, + newAccount: newKeypair.publicKey, + }) + .signers([wallet.payer, newKeypair]) + .rpc(); - const newKeypairInfo = await provider.connection.getAccountInfo( - newKeypair.publicKey, - ); + const newKeypairInfo = await provider.connection.getAccountInfo(newKeypair.publicKey); - assert.equal(newKeypairInfo.data.length, addressDataBuffer.length); - }); + assert.equal(newKeypairInfo.data.length, addressDataBuffer.length); + }); }); diff --git a/basics/rent/anchor/tsconfig.json b/basics/rent/anchor/tsconfig.json index 59fe75cf0..beb254c00 100644 --- a/basics/rent/anchor/tsconfig.json +++ b/basics/rent/anchor/tsconfig.json @@ -1,10 +1,10 @@ { - "compilerOptions": { - "types": ["mocha", "chai"], - "typeRoots": ["./node_modules/@types"], - "lib": ["es2015"], - "module": "nodenext", - "target": "es6", - "esModuleInterop": true - } + "compilerOptions": { + "types": ["mocha", "chai"], + "typeRoots": ["./node_modules/@types"], + "lib": ["es2015"], + "module": "nodenext", + "target": "es6", + "esModuleInterop": true + } } diff --git a/basics/rent/native/tests/test.ts b/basics/rent/native/tests/test.ts index b07f32f79..1dc1fdee9 100644 --- a/basics/rent/native/tests/test.ts +++ b/basics/rent/native/tests/test.ts @@ -1,19 +1,19 @@ -import { Buffer } from 'node:buffer'; -import { describe, test } from 'node:test'; -import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction } from '@solana/web3.js'; -import * as borsh from 'borsh'; -import { start } from 'solana-bankrun'; +import { Buffer } from "node:buffer"; +import { describe, test } from "node:test"; +import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction } from "@solana/web3.js"; +import * as borsh from "borsh"; +import { start } from "solana-bankrun"; -describe('Create a system account', async () => { +describe("Create a system account", async () => { const PROGRAM_ID = PublicKey.unique(); - const context = await start([{ name: 'program', programId: PROGRAM_ID }], []); + const context = await start([{ name: "program", programId: PROGRAM_ID }], []); const client = context.banksClient; const payer = context.payer; const AddressDataSchema = { struct: { - name: 'string', - address: 'string', + name: "string", + address: "string", }, }; @@ -21,12 +21,12 @@ describe('Create a system account', async () => { return Buffer.from(borsh.serialize(schema, data)); } - test('Create the account', async () => { + test("Create the account", async () => { const newKeypair = Keypair.generate(); const addressData = { - name: 'Marcus', - address: '123 Main St. San Francisco, CA', + name: "Marcus", + address: "123 Main St. San Francisco, CA", }; // We're just going to serialize our object here so we can check diff --git a/basics/rent/pinocchio/tests/test.ts b/basics/rent/pinocchio/tests/test.ts index ad53cf096..4c97d9a1b 100644 --- a/basics/rent/pinocchio/tests/test.ts +++ b/basics/rent/pinocchio/tests/test.ts @@ -1,5 +1,4 @@ -import { Buffer } from "node:buffer"; -import { describe, test } from "node:test"; +import { describe } from "node:test"; describe("Create a system account", async () => { console.log("Create a system account"); diff --git a/basics/repository-layout/anchor/package.json b/basics/repository-layout/anchor/package.json index 0696e9344..a77db16c0 100644 --- a/basics/repository-layout/anchor/package.json +++ b/basics/repository-layout/anchor/package.json @@ -1,17 +1,17 @@ { - "type": "module", - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/web3.js": "^1.98.4", - "litesvm": "^0.4.0" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/web3.js": "^1.98.4", + "litesvm": "^0.4.0" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/basics/repository-layout/anchor/tests/litesvm.test.ts b/basics/repository-layout/anchor/tests/litesvm.test.ts index a77a18431..96bbc11a0 100644 --- a/basics/repository-layout/anchor/tests/litesvm.test.ts +++ b/basics/repository-layout/anchor/tests/litesvm.test.ts @@ -1,129 +1,119 @@ import anchor from "@anchor-lang/core"; -import { - Keypair, - LAMPORTS_PER_SOL, - PublicKey, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; +import { Keypair, LAMPORTS_PER_SOL, PublicKey, Transaction, TransactionInstruction } from "@solana/web3.js"; import { LiteSVM } from "litesvm"; import Idl from "../target/idl/carnival.json" with { type: "json" }; describe("LiteSVM: Carnival", () => { - const svm = new LiteSVM(); - const programId = new PublicKey(Idl.address); - const coder = new anchor.BorshCoder(Idl as anchor.Idl); - const payer = Keypair.generate(); - svm.airdrop(payer.publicKey, BigInt(5 * LAMPORTS_PER_SOL)); + const svm = new LiteSVM(); + const programId = new PublicKey(Idl.address); + const coder = new anchor.BorshCoder(Idl as anchor.Idl); + const payer = Keypair.generate(); + svm.airdrop(payer.publicKey, BigInt(5 * LAMPORTS_PER_SOL)); - const programPath = new URL("../target/deploy/carnival.so", import.meta.url) - .pathname; - svm.addProgramFromFile(programId, programPath); + const programPath = new URL("../target/deploy/carnival.so", import.meta.url).pathname; + svm.addProgramFromFile(programId, programPath); - it("Go on some rides!", () => { - const jimmyIxArgs = { - name: "Jimmy", - height: 36, - ticket_count: 15, - ride_name: "Scrambler", - }; - const maryIxArgs = { - name: "Mary", - height: 52, - ticket_count: 1, - ride_name: "Ferris Wheel", - }; - const bobIxArgs = { - name: "Alice", - height: 56, - ticket_count: 15, - ride_name: "Scrambler", - }; - const aliceIxArgs = { - name: "Bob", - height: 49, - ticket_count: 6, - ride_name: "Tilt-a-Whirl", - }; + it("Go on some rides!", () => { + const jimmyIxArgs = { + name: "Jimmy", + height: 36, + ticket_count: 15, + ride_name: "Scrambler", + }; + const maryIxArgs = { + name: "Mary", + height: 52, + ticket_count: 1, + ride_name: "Ferris Wheel", + }; + const bobIxArgs = { + name: "Alice", + height: 56, + ticket_count: 15, + ride_name: "Scrambler", + }; + const aliceIxArgs = { + name: "Bob", + height: 49, + ticket_count: 6, + ride_name: "Tilt-a-Whirl", + }; - createAndSendTx(jimmyIxArgs, "go_on_ride"); - createAndSendTx(maryIxArgs, "go_on_ride"); - createAndSendTx(bobIxArgs, "go_on_ride"); - createAndSendTx(aliceIxArgs, "go_on_ride"); - }); + createAndSendTx(jimmyIxArgs, "go_on_ride"); + createAndSendTx(maryIxArgs, "go_on_ride"); + createAndSendTx(bobIxArgs, "go_on_ride"); + createAndSendTx(aliceIxArgs, "go_on_ride"); + }); - it("Play some games!", () => { - const jimmyIxArgs = { - name: "Jimmy", - ticket_count: 15, - game_name: "I Got It!", - }; - const maryIxArgs = { - name: "Mary", - ticket_count: 1, - game_name: "Ring Toss", - }; - const aliceIxArgs = { - name: "Alice", - ticket_count: 15, - game_name: "Ladder Climb", - }; - const bobIxArgs = { - name: "Bob", - ticket_count: 6, - game_name: "Ring Toss", - }; + it("Play some games!", () => { + const jimmyIxArgs = { + name: "Jimmy", + ticket_count: 15, + game_name: "I Got It!", + }; + const maryIxArgs = { + name: "Mary", + ticket_count: 1, + game_name: "Ring Toss", + }; + const aliceIxArgs = { + name: "Alice", + ticket_count: 15, + game_name: "Ladder Climb", + }; + const bobIxArgs = { + name: "Bob", + ticket_count: 6, + game_name: "Ring Toss", + }; - createAndSendTx(jimmyIxArgs, "play_game"); - createAndSendTx(maryIxArgs, "play_game"); - createAndSendTx(aliceIxArgs, "play_game"); - createAndSendTx(bobIxArgs, "play_game"); - }); + createAndSendTx(jimmyIxArgs, "play_game"); + createAndSendTx(maryIxArgs, "play_game"); + createAndSendTx(aliceIxArgs, "play_game"); + createAndSendTx(bobIxArgs, "play_game"); + }); - it("Eat some food!", () => { - const jimmyIxArgs = { - name: "Jimmy", - ticket_count: 15, - food_stand_name: "Taco Shack", - }; - const maryIxArgs = { - name: "Mary", - ticket_count: 1, - food_stand_name: "Larry's Pizza", - }; - const aliceIxArgs = { - name: "Alice", - ticket_count: 15, - food_stand_name: "Dough Boy's", - }; - const bobIxArgs = { - name: "Bob", - ticket_count: 6, - food_stand_name: "Dough Boy's", - }; + it("Eat some food!", () => { + const jimmyIxArgs = { + name: "Jimmy", + ticket_count: 15, + food_stand_name: "Taco Shack", + }; + const maryIxArgs = { + name: "Mary", + ticket_count: 1, + food_stand_name: "Larry's Pizza", + }; + const aliceIxArgs = { + name: "Alice", + ticket_count: 15, + food_stand_name: "Dough Boy's", + }; + const bobIxArgs = { + name: "Bob", + ticket_count: 6, + food_stand_name: "Dough Boy's", + }; - createAndSendTx(jimmyIxArgs, "eat_food"); - createAndSendTx(maryIxArgs, "eat_food"); - createAndSendTx(aliceIxArgs, "eat_food"); - createAndSendTx(bobIxArgs, "eat_food"); - }); + createAndSendTx(jimmyIxArgs, "eat_food"); + createAndSendTx(maryIxArgs, "eat_food"); + createAndSendTx(aliceIxArgs, "eat_food"); + createAndSendTx(bobIxArgs, "eat_food"); + }); - function createAndSendTx( - ixArgs: Record, - ixName: string, - ) { - const data = coder.instruction.encode(ixName, ixArgs); - const ix = new TransactionInstruction({ - keys: [{ pubkey: payer.publicKey, isSigner: true, isWritable: true }], - programId, - data, - }); + function createAndSendTx(ixArgs: Record, ixName: string) { + const data = coder.instruction.encode(ixName, ixArgs); + const ix = new TransactionInstruction({ + keys: [{ pubkey: payer.publicKey, isSigner: true, isWritable: true }], + programId, + data, + }); - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer); - const re = svm.sendTransaction(tx); - // console.log(re.toString()); - } + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer); + const _re = svm.sendTransaction(tx); + // console.log(re.toString()); + } }); diff --git a/basics/repository-layout/anchor/tests/test.ts b/basics/repository-layout/anchor/tests/test.ts index 497a11edd..2d978110a 100644 --- a/basics/repository-layout/anchor/tests/test.ts +++ b/basics/repository-layout/anchor/tests/test.ts @@ -2,55 +2,43 @@ import * as anchor from "@anchor-lang/core"; import type { Carnival } from "../target/types/carnival.ts"; describe("Carnival", () => { - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); - const wallet = provider.wallet as anchor.Wallet; - const program = anchor.workspace.Carnival as anchor.Program; + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); + const wallet = provider.wallet as anchor.Wallet; + const program = anchor.workspace.Carnival as anchor.Program; - async function sendCarnivalInstructions( - instructionsList: anchor.web3.TransactionInstruction[], - ) { - const tx = new anchor.web3.Transaction(); - for (const ix of instructionsList) { - tx.add(ix); - } - await anchor.web3.sendAndConfirmTransaction(provider.connection, tx, [ - wallet.payer, - ]); - } + async function sendCarnivalInstructions(instructionsList: anchor.web3.TransactionInstruction[]) { + const tx = new anchor.web3.Transaction(); + for (const ix of instructionsList) { + tx.add(ix); + } + await anchor.web3.sendAndConfirmTransaction(provider.connection, tx, [wallet.payer]); + } - it("Go on some rides!", async () => { - await sendCarnivalInstructions([ - await program.methods - .goOnRide("Jimmy", 36, 15, "Scrambler") - .instruction(), - await program.methods - .goOnRide("Mary", 52, 1, "Ferris Wheel") - .instruction(), - await program.methods - .goOnRide("Alice", 56, 15, "Scrambler") - .instruction(), - await program.methods - .goOnRide("Bob", 49, 6, "Tilt-a-Whirl") - .instruction(), - ]); - }); + it("Go on some rides!", async () => { + await sendCarnivalInstructions([ + await program.methods.goOnRide("Jimmy", 36, 15, "Scrambler").instruction(), + await program.methods.goOnRide("Mary", 52, 1, "Ferris Wheel").instruction(), + await program.methods.goOnRide("Alice", 56, 15, "Scrambler").instruction(), + await program.methods.goOnRide("Bob", 49, 6, "Tilt-a-Whirl").instruction(), + ]); + }); - it("Play some games!", async () => { - await sendCarnivalInstructions([ - await program.methods.playGame("Jimmy", 15, "I Got It!").instruction(), - await program.methods.playGame("Mary", 1, "Ring Toss").instruction(), - await program.methods.playGame("Alice", 15, "Ladder Climb").instruction(), - await program.methods.playGame("Bob", 6, "Ring Toss").instruction(), - ]); - }); + it("Play some games!", async () => { + await sendCarnivalInstructions([ + await program.methods.playGame("Jimmy", 15, "I Got It!").instruction(), + await program.methods.playGame("Mary", 1, "Ring Toss").instruction(), + await program.methods.playGame("Alice", 15, "Ladder Climb").instruction(), + await program.methods.playGame("Bob", 6, "Ring Toss").instruction(), + ]); + }); - it("Eat some food!", async () => { - await sendCarnivalInstructions([ - await program.methods.eatFood("Jimmy", 15, "Taco Shack").instruction(), - await program.methods.eatFood("Mary", 1, "Larry's Pizza").instruction(), - await program.methods.eatFood("Alice", 15, "Dough Boy's").instruction(), - await program.methods.eatFood("Bob", 6, "Dough Boy's").instruction(), - ]); - }); + it("Eat some food!", async () => { + await sendCarnivalInstructions([ + await program.methods.eatFood("Jimmy", 15, "Taco Shack").instruction(), + await program.methods.eatFood("Mary", 1, "Larry's Pizza").instruction(), + await program.methods.eatFood("Alice", 15, "Dough Boy's").instruction(), + await program.methods.eatFood("Bob", 6, "Dough Boy's").instruction(), + ]); + }); }); diff --git a/basics/repository-layout/anchor/tsconfig.json b/basics/repository-layout/anchor/tsconfig.json index 59fe75cf0..beb254c00 100644 --- a/basics/repository-layout/anchor/tsconfig.json +++ b/basics/repository-layout/anchor/tsconfig.json @@ -1,10 +1,10 @@ { - "compilerOptions": { - "types": ["mocha", "chai"], - "typeRoots": ["./node_modules/@types"], - "lib": ["es2015"], - "module": "nodenext", - "target": "es6", - "esModuleInterop": true - } + "compilerOptions": { + "types": ["mocha", "chai"], + "typeRoots": ["./node_modules/@types"], + "lib": ["es2015"], + "module": "nodenext", + "target": "es6", + "esModuleInterop": true + } } diff --git a/basics/repository-layout/native/tests/test.ts b/basics/repository-layout/native/tests/test.ts index db8b6dedd..d480899ff 100644 --- a/basics/repository-layout/native/tests/test.ts +++ b/basics/repository-layout/native/tests/test.ts @@ -1,22 +1,22 @@ -import { Buffer } from 'node:buffer'; -import { describe, test } from 'node:test'; -import { PublicKey, Transaction, TransactionInstruction } from '@solana/web3.js'; -import * as borsh from 'borsh'; -import { start } from 'solana-bankrun'; +import { Buffer } from "node:buffer"; +import { describe, test } from "node:test"; +import { PublicKey, Transaction, TransactionInstruction } from "@solana/web3.js"; +import * as borsh from "borsh"; +import { start } from "solana-bankrun"; -describe('Carnival', async () => { +describe("Carnival", async () => { const PROGRAM_ID = PublicKey.unique(); - const context = await start([{ name: 'repository_layout_program', programId: PROGRAM_ID }], []); + const context = await start([{ name: "repository_layout_program", programId: PROGRAM_ID }], []); const client = context.banksClient; const payer = context.payer; const CarnivalInstructionSchema = { struct: { - name: 'string', - height: 'u32', - ticket_count: 'u32', - attraction: 'string', - attraction_name: 'string', + name: "string", + height: "u32", + ticket_count: "u32", + attraction: "string", + attraction_name: "string", }, }; @@ -47,30 +47,102 @@ describe('Carnival', async () => { await client.processTransaction(tx); } - test('Go on some rides!', async () => { + test("Go on some rides!", async () => { await sendCarnivalInstructions([ - { name: 'Jimmy', height: 36, ticket_count: 15, attraction: 'ride', attraction_name: 'Scrambler' }, - { name: 'Mary', height: 52, ticket_count: 1, attraction: 'ride', attraction_name: 'Ferris Wheel' }, - { name: 'Alice', height: 56, ticket_count: 15, attraction: 'ride', attraction_name: 'Scrambler' }, - { name: 'Bob', height: 49, ticket_count: 6, attraction: 'ride', attraction_name: 'Tilt-a-Whirl' }, + { + name: "Jimmy", + height: 36, + ticket_count: 15, + attraction: "ride", + attraction_name: "Scrambler", + }, + { + name: "Mary", + height: 52, + ticket_count: 1, + attraction: "ride", + attraction_name: "Ferris Wheel", + }, + { + name: "Alice", + height: 56, + ticket_count: 15, + attraction: "ride", + attraction_name: "Scrambler", + }, + { + name: "Bob", + height: 49, + ticket_count: 6, + attraction: "ride", + attraction_name: "Tilt-a-Whirl", + }, ]); }); - test('Play some games!', async () => { + test("Play some games!", async () => { await sendCarnivalInstructions([ - { name: 'Jimmy', height: 36, ticket_count: 15, attraction: 'game', attraction_name: 'I Got It!' }, - { name: 'Mary', height: 52, ticket_count: 1, attraction: 'game', attraction_name: 'Ring Toss' }, - { name: 'Alice', height: 56, ticket_count: 15, attraction: 'game', attraction_name: 'Ladder Climb' }, - { name: 'Bob', height: 49, ticket_count: 6, attraction: 'game', attraction_name: 'Ring Toss' }, + { + name: "Jimmy", + height: 36, + ticket_count: 15, + attraction: "game", + attraction_name: "I Got It!", + }, + { + name: "Mary", + height: 52, + ticket_count: 1, + attraction: "game", + attraction_name: "Ring Toss", + }, + { + name: "Alice", + height: 56, + ticket_count: 15, + attraction: "game", + attraction_name: "Ladder Climb", + }, + { + name: "Bob", + height: 49, + ticket_count: 6, + attraction: "game", + attraction_name: "Ring Toss", + }, ]); }); - test('Eat some food!', async () => { + test("Eat some food!", async () => { await sendCarnivalInstructions([ - { name: 'Jimmy', height: 36, ticket_count: 15, attraction: 'food', attraction_name: 'Taco Shack' }, - { name: 'Mary', height: 52, ticket_count: 1, attraction: 'food', attraction_name: "Larry's Pizza" }, - { name: 'Alice', height: 56, ticket_count: 15, attraction: 'food', attraction_name: "Dough Boy's" }, - { name: 'Bob', height: 49, ticket_count: 6, attraction: 'food', attraction_name: "Dough Boy's" }, + { + name: "Jimmy", + height: 36, + ticket_count: 15, + attraction: "food", + attraction_name: "Taco Shack", + }, + { + name: "Mary", + height: 52, + ticket_count: 1, + attraction: "food", + attraction_name: "Larry's Pizza", + }, + { + name: "Alice", + height: 56, + ticket_count: 15, + attraction: "food", + attraction_name: "Dough Boy's", + }, + { + name: "Bob", + height: 49, + ticket_count: 6, + attraction: "food", + attraction_name: "Dough Boy's", + }, ]); }); }); diff --git a/basics/transfer-sol/anchor/package.json b/basics/transfer-sol/anchor/package.json index 0696e9344..a77db16c0 100644 --- a/basics/transfer-sol/anchor/package.json +++ b/basics/transfer-sol/anchor/package.json @@ -1,17 +1,17 @@ { - "type": "module", - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/web3.js": "^1.98.4", - "litesvm": "^0.4.0" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/web3.js": "^1.98.4", + "litesvm": "^0.4.0" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/basics/transfer-sol/anchor/tests/litesvm.test.ts b/basics/transfer-sol/anchor/tests/litesvm.test.ts index 536e796f6..21ced4b0d 100644 --- a/basics/transfer-sol/anchor/tests/litesvm.test.ts +++ b/basics/transfer-sol/anchor/tests/litesvm.test.ts @@ -1,99 +1,96 @@ import anchor from "@anchor-lang/core"; import { - Keypair, - LAMPORTS_PER_SOL, - PublicKey, - SystemProgram, - Transaction, - TransactionInstruction, + Keypair, + LAMPORTS_PER_SOL, + PublicKey, + SystemProgram, + Transaction, + TransactionInstruction, } from "@solana/web3.js"; import { assert } from "chai"; import { LiteSVM } from "litesvm"; import Idl from "../target/idl/transfer_sol.json" with { type: "json" }; describe("LiteSVM: Transfer SOL", () => { - const svm = new LiteSVM(); - const programId = new PublicKey(Idl.address); - const coder = new anchor.BorshCoder(Idl as anchor.Idl); - const payer = Keypair.generate(); - svm.airdrop(payer.publicKey, BigInt(5 * LAMPORTS_PER_SOL)); + const svm = new LiteSVM(); + const programId = new PublicKey(Idl.address); + const coder = new anchor.BorshCoder(Idl as anchor.Idl); + const payer = Keypair.generate(); + svm.airdrop(payer.publicKey, BigInt(5 * LAMPORTS_PER_SOL)); - const programFilePath = new URL( - "../target/deploy/transfer_sol.so", - import.meta.url, - ).pathname; - svm.addProgramFromFile(programId, programFilePath); + const programFilePath = new URL("../target/deploy/transfer_sol.so", import.meta.url).pathname; + svm.addProgramFromFile(programId, programFilePath); - it("Transfer SOL with CPI", () => { - const recipient = Keypair.generate(); + it("Transfer SOL with CPI", () => { + const recipient = Keypair.generate(); - const ixArgs = { - amount: new anchor.BN(LAMPORTS_PER_SOL), - }; - const data = coder.instruction.encode("transfer_sol_with_cpi", ixArgs); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: payer.publicKey, isSigner: true, isWritable: true }, - { pubkey: recipient.publicKey, isSigner: false, isWritable: true }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId, - data, - }); + const ixArgs = { + amount: new anchor.BN(LAMPORTS_PER_SOL), + }; + const data = coder.instruction.encode("transfer_sol_with_cpi", ixArgs); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: payer.publicKey, isSigner: true, isWritable: true }, + { pubkey: recipient.publicKey, isSigner: false, isWritable: true }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId, + data, + }); - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer); - svm.sendTransaction(tx); + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer); + svm.sendTransaction(tx); - const recipientAcc = svm.getAccount(recipient.publicKey); - assert.equal(recipientAcc.lamports, LAMPORTS_PER_SOL); - }); + const recipientAcc = svm.getAccount(recipient.publicKey); + assert.equal(recipientAcc.lamports, LAMPORTS_PER_SOL); + }); - it("Transfer SOL with Program", () => { - const payerAccount = Keypair.generate(); - const ixPayer = SystemProgram.createAccount({ - fromPubkey: payer.publicKey, - newAccountPubkey: payerAccount.publicKey, - lamports: LAMPORTS_PER_SOL, - space: 0, - programId, - }); - const txPayer = new Transaction().add(ixPayer); - txPayer.feePayer = payer.publicKey; - txPayer.recentBlockhash = svm.latestBlockhash(); - txPayer.sign(payer, payerAccount); - svm.sendTransaction(txPayer); - svm.expireBlockhash(); + it("Transfer SOL with Program", () => { + const payerAccount = Keypair.generate(); + const ixPayer = SystemProgram.createAccount({ + fromPubkey: payer.publicKey, + newAccountPubkey: payerAccount.publicKey, + lamports: LAMPORTS_PER_SOL, + space: 0, + programId, + }); + const txPayer = new Transaction().add(ixPayer); + txPayer.feePayer = payer.publicKey; + txPayer.recentBlockhash = svm.latestBlockhash(); + txPayer.sign(payer, payerAccount); + svm.sendTransaction(txPayer); + svm.expireBlockhash(); - const recipientAccount = Keypair.generate(); + const recipientAccount = Keypair.generate(); - const ixArgs = { - amount: new anchor.BN(LAMPORTS_PER_SOL), - }; - const data = coder.instruction.encode("transfer_sol_with_program", ixArgs); - const ix = new TransactionInstruction({ - keys: [ - { pubkey: payerAccount.publicKey, isSigner: true, isWritable: true }, - { - pubkey: recipientAccount.publicKey, - isSigner: false, - isWritable: true, - }, - { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, - ], - programId, - data, - }); + const ixArgs = { + amount: new anchor.BN(LAMPORTS_PER_SOL), + }; + const data = coder.instruction.encode("transfer_sol_with_program", ixArgs); + const ix = new TransactionInstruction({ + keys: [ + { pubkey: payerAccount.publicKey, isSigner: true, isWritable: true }, + { + pubkey: recipientAccount.publicKey, + isSigner: false, + isWritable: true, + }, + { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, + ], + programId, + data, + }); - const tx = new Transaction().add(ix); - tx.feePayer = payer.publicKey; - tx.recentBlockhash = svm.latestBlockhash(); - tx.sign(payer, payerAccount); - svm.sendTransaction(tx); + const tx = new Transaction().add(ix); + tx.feePayer = payer.publicKey; + tx.recentBlockhash = svm.latestBlockhash(); + tx.sign(payer, payerAccount); + svm.sendTransaction(tx); - const recipientAcc = svm.getAccount(recipientAccount.publicKey); - assert.equal(recipientAcc.lamports, LAMPORTS_PER_SOL); - }); + const recipientAcc = svm.getAccount(recipientAccount.publicKey); + assert.equal(recipientAcc.lamports, LAMPORTS_PER_SOL); + }); }); diff --git a/basics/transfer-sol/anchor/tests/test.ts b/basics/transfer-sol/anchor/tests/test.ts index c43f5f122..3f773a536 100644 --- a/basics/transfer-sol/anchor/tests/test.ts +++ b/basics/transfer-sol/anchor/tests/test.ts @@ -1,68 +1,54 @@ import * as anchor from "@anchor-lang/core"; -import { - Keypair, - LAMPORTS_PER_SOL, - type PublicKey, - SystemProgram, - Transaction, - sendAndConfirmTransaction, -} from "@solana/web3.js"; +import { Keypair, LAMPORTS_PER_SOL, SystemProgram, sendAndConfirmTransaction, Transaction } from "@solana/web3.js"; import { BN } from "bn.js"; import { assert } from "chai"; import type { TransferSol } from "../target/types/transfer_sol.ts"; describe("Anchor: Transfer SOL", () => { - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); - const payer = provider.wallet as anchor.Wallet; - const program = anchor.workspace.TransferSol as anchor.Program; - - it("Transfer SOL with CPI", async () => { - const recipient = Keypair.generate(); - - await program.methods - .transferSolWithCpi(new BN(LAMPORTS_PER_SOL)) - .accounts({ - payer: payer.publicKey, - recipient: recipient.publicKey, - }) - .rpc(); - - const recipientBalance = await provider.connection.getBalance( - recipient.publicKey, - ); - assert.equal(recipientBalance, LAMPORTS_PER_SOL); - }); - - it("Transfer SOL with Program", async () => { - const payerAccount = Keypair.generate(); - const ix = SystemProgram.createAccount({ - fromPubkey: payer.publicKey, - newAccountPubkey: payerAccount.publicKey, - space: 0, - lamports: LAMPORTS_PER_SOL, // 1 SOL - programId: program.programId, // Program Owner, our program's address - }); - - const transaction = new Transaction().add(ix); - - await sendAndConfirmTransaction(provider.connection, transaction, [ - payer.payer, - payerAccount, - ]); - - const recipientAccount = Keypair.generate(); - await program.methods - .transferSolWithProgram(new BN(LAMPORTS_PER_SOL)) - .accounts({ - payer: payerAccount.publicKey, - recipient: recipientAccount.publicKey, - }) - .rpc(); - - const recipientBalance = await provider.connection.getBalance( - recipientAccount.publicKey, - ); - assert.equal(recipientBalance, LAMPORTS_PER_SOL); - }); + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); + const payer = provider.wallet as anchor.Wallet; + const program = anchor.workspace.TransferSol as anchor.Program; + + it("Transfer SOL with CPI", async () => { + const recipient = Keypair.generate(); + + await program.methods + .transferSolWithCpi(new BN(LAMPORTS_PER_SOL)) + .accounts({ + payer: payer.publicKey, + recipient: recipient.publicKey, + }) + .rpc(); + + const recipientBalance = await provider.connection.getBalance(recipient.publicKey); + assert.equal(recipientBalance, LAMPORTS_PER_SOL); + }); + + it("Transfer SOL with Program", async () => { + const payerAccount = Keypair.generate(); + const ix = SystemProgram.createAccount({ + fromPubkey: payer.publicKey, + newAccountPubkey: payerAccount.publicKey, + space: 0, + lamports: LAMPORTS_PER_SOL, // 1 SOL + programId: program.programId, // Program Owner, our program's address + }); + + const transaction = new Transaction().add(ix); + + await sendAndConfirmTransaction(provider.connection, transaction, [payer.payer, payerAccount]); + + const recipientAccount = Keypair.generate(); + await program.methods + .transferSolWithProgram(new BN(LAMPORTS_PER_SOL)) + .accounts({ + payer: payerAccount.publicKey, + recipient: recipientAccount.publicKey, + }) + .rpc(); + + const recipientBalance = await provider.connection.getBalance(recipientAccount.publicKey); + assert.equal(recipientBalance, LAMPORTS_PER_SOL); + }); }); diff --git a/basics/transfer-sol/anchor/tsconfig.json b/basics/transfer-sol/anchor/tsconfig.json index 59fe75cf0..beb254c00 100644 --- a/basics/transfer-sol/anchor/tsconfig.json +++ b/basics/transfer-sol/anchor/tsconfig.json @@ -1,10 +1,10 @@ { - "compilerOptions": { - "types": ["mocha", "chai"], - "typeRoots": ["./node_modules/@types"], - "lib": ["es2015"], - "module": "nodenext", - "target": "es6", - "esModuleInterop": true - } + "compilerOptions": { + "types": ["mocha", "chai"], + "typeRoots": ["./node_modules/@types"], + "lib": ["es2015"], + "module": "nodenext", + "target": "es6", + "esModuleInterop": true + } } diff --git a/basics/transfer-sol/native/tests/instruction.ts b/basics/transfer-sol/native/tests/instruction.ts index 311a35188..72e90f9d2 100644 --- a/basics/transfer-sol/native/tests/instruction.ts +++ b/basics/transfer-sol/native/tests/instruction.ts @@ -1,6 +1,6 @@ -import { Buffer } from 'node:buffer'; -import { type PublicKey, SystemProgram, TransactionInstruction } from '@solana/web3.js'; -import * as borsh from 'borsh'; +import { Buffer } from "node:buffer"; +import { type PublicKey, SystemProgram, TransactionInstruction } from "@solana/web3.js"; +import * as borsh from "borsh"; export enum InstructionType { CpiTransfer = 0, @@ -9,8 +9,8 @@ export enum InstructionType { const TransferInstructionSchema = { struct: { - instruction: 'u8', - amount: 'u64', + instruction: "u8", + amount: "u64", }, }; diff --git a/basics/transfer-sol/native/tests/test.ts b/basics/transfer-sol/native/tests/test.ts index e5eb81b02..929fb0a3f 100644 --- a/basics/transfer-sol/native/tests/test.ts +++ b/basics/transfer-sol/native/tests/test.ts @@ -1,11 +1,11 @@ -import { describe, test } from 'node:test'; -import { Keypair, LAMPORTS_PER_SOL, PublicKey, SystemProgram, Transaction } from '@solana/web3.js'; -import { start } from 'solana-bankrun'; -import { createTransferInstruction, InstructionType } from './instruction'; +import { describe, test } from "node:test"; +import { Keypair, LAMPORTS_PER_SOL, PublicKey, SystemProgram, Transaction } from "@solana/web3.js"; +import { start } from "solana-bankrun"; +import { createTransferInstruction, InstructionType } from "./instruction"; -describe('transfer-sol', async () => { +describe("transfer-sol", async () => { const PROGRAM_ID = PublicKey.unique(); - const context = await start([{ name: 'transfer_sol_program', programId: PROGRAM_ID }], []); + const context = await start([{ name: "transfer_sol_program", programId: PROGRAM_ID }], []); const client = context.banksClient; const payer = context.payer; @@ -14,10 +14,16 @@ describe('transfer-sol', async () => { const test2Recipient1 = Keypair.generate(); const test2Recipient2 = Keypair.generate(); - test('Transfer between accounts using the system program', async () => { - await getBalances(payer.publicKey, test1Recipient.publicKey, 'Beginning'); + test("Transfer between accounts using the system program", async () => { + await getBalances(payer.publicKey, test1Recipient.publicKey, "Beginning"); - const ix = createTransferInstruction(payer.publicKey, test1Recipient.publicKey, PROGRAM_ID, InstructionType.CpiTransfer, transferAmount); + const ix = createTransferInstruction( + payer.publicKey, + test1Recipient.publicKey, + PROGRAM_ID, + InstructionType.CpiTransfer, + transferAmount, + ); const tx = new Transaction(); const [blockhash, _] = await client.getLatestBlockhash(); @@ -26,10 +32,10 @@ describe('transfer-sol', async () => { await client.processTransaction(tx); - await getBalances(payer.publicKey, test1Recipient.publicKey, 'Resulting'); + await getBalances(payer.publicKey, test1Recipient.publicKey, "Resulting"); }); - test('Create two accounts for the following test', async () => { + test("Create two accounts for the following test", async () => { const ix = (pubkey: PublicKey) => { return SystemProgram.createAccount({ fromPubkey: payer.publicKey, @@ -43,13 +49,15 @@ describe('transfer-sol', async () => { const tx = new Transaction(); const [blockhash, _] = await client.getLatestBlockhash(); tx.recentBlockhash = blockhash; - tx.add(ix(test2Recipient1.publicKey)).add(ix(test2Recipient2.publicKey)).sign(payer, test2Recipient1, test2Recipient2); + tx.add(ix(test2Recipient1.publicKey)) + .add(ix(test2Recipient2.publicKey)) + .sign(payer, test2Recipient1, test2Recipient2); await client.processTransaction(tx); }); - test('Transfer between accounts using our program', async () => { - await getBalances(test2Recipient1.publicKey, test2Recipient2.publicKey, 'Beginning'); + test("Transfer between accounts using our program", async () => { + await getBalances(test2Recipient1.publicKey, test2Recipient2.publicKey, "Beginning"); const ix = createTransferInstruction( test2Recipient1.publicKey, @@ -66,7 +74,7 @@ describe('transfer-sol', async () => { await client.processTransaction(tx); - await getBalances(test2Recipient1.publicKey, test2Recipient2.publicKey, 'Resulting'); + await getBalances(test2Recipient1.publicKey, test2Recipient2.publicKey, "Resulting"); }); async function getBalances(payerPubkey: PublicKey, recipientPubkey: PublicKey, timeframe: string) { diff --git a/basics/transfer-sol/pinocchio/tests/test.ts b/basics/transfer-sol/pinocchio/tests/test.ts index 40dda0916..561e1d988 100644 --- a/basics/transfer-sol/pinocchio/tests/test.ts +++ b/basics/transfer-sol/pinocchio/tests/test.ts @@ -1,12 +1,4 @@ -import { describe, test } from "node:test"; -import { - Keypair, - LAMPORTS_PER_SOL, - PublicKey, - SystemProgram, - Transaction, -} from "@solana/web3.js"; -import { start } from "solana-bankrun"; +import { describe } from "node:test"; describe("transfer-sol", async () => { console.log("transfer-sol"); diff --git a/biome.jsonc b/biome.jsonc new file mode 100644 index 000000000..6243cd87c --- /dev/null +++ b/biome.jsonc @@ -0,0 +1,27 @@ +{ + "$schema": "https://biomejs.dev/schemas/2.4.10/schema.json", + "files": { + "includes": ["**", "!**/Assets"] + }, + "formatter": { + // Matches more existing code, + // also 2 spaces is used by: Prettier, StandardJS, AirBnB, + // Google JavaScript Style Guide, node.js style guide, + // deno fmt, MDN, and idiomatic.js. + "indentStyle": "space", + "indentWidth": 2, + "lineWidth": 120 + }, + "javascript": { + "formatter": { + // Also to match Prettier, Google, etc. + // (though standard and AirBnB use single) + "quoteStyle": "double" + } + }, + "css": { + "parser": { + "tailwindDirectives": true + } + } +} diff --git a/compression/cnft-burn/anchor/migrations/deploy.ts b/compression/cnft-burn/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/compression/cnft-burn/anchor/migrations/deploy.ts +++ b/compression/cnft-burn/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/compression/cnft-burn/anchor/package.json b/compression/cnft-burn/anchor/package.json index bfbe65494..ae310a6b7 100644 --- a/compression/cnft-burn/anchor/package.json +++ b/compression/cnft-burn/anchor/package.json @@ -1,27 +1,27 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@metaplex-foundation/js": "^0.19.4", - "@metaplex-foundation/mpl-bubblegum": "^0.7.0", - "@metaplex-foundation/mpl-token-metadata": "^2.12.0", - "@metaplex-foundation/umi": "^0.9.0", - "@solana/spl-account-compression": "^0.2.0", - "@solana/web3.js": "^1.98.4", - "axios": "^1.6.5" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@metaplex-foundation/js": "^0.19.4", + "@metaplex-foundation/mpl-bubblegum": "^0.7.0", + "@metaplex-foundation/mpl-token-metadata": "^2.12.0", + "@metaplex-foundation/umi": "^0.9.0", + "@solana/spl-account-compression": "^0.2.0", + "@solana/web3.js": "^1.98.4", + "axios": "^1.6.5" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/compression/cnft-burn/anchor/tests/ReadApi/WrapperConnection.ts b/compression/cnft-burn/anchor/tests/ReadApi/WrapperConnection.ts index 0f20ec043..426f6ba6b 100644 --- a/compression/cnft-burn/anchor/tests/ReadApi/WrapperConnection.ts +++ b/compression/cnft-burn/anchor/tests/ReadApi/WrapperConnection.ts @@ -1,12 +1,12 @@ // local imports for the ReadApi types -import type { Metadata, Mint, NftOriginalEdition, SplTokenCurrency } from '@metaplex-foundation/js'; +import type { Metadata, Mint, NftOriginalEdition, SplTokenCurrency } from "@metaplex-foundation/js"; // import from the `@metaplex-foundation/js` -import { amount, MetaplexError, Pda, toBigNumber } from '@metaplex-foundation/js'; -import { PROGRAM_ID as BUBBLEGUM_PROGRAM_ID } from '@metaplex-foundation/mpl-bubblegum'; -import { TokenStandard } from '@metaplex-foundation/mpl-token-metadata'; -import { Connection, PublicKey } from '@solana/web3.js'; -import BN from 'bn.js'; +import { amount, MetaplexError, Pda, toBigNumber } from "@metaplex-foundation/js"; +import { PROGRAM_ID as BUBBLEGUM_PROGRAM_ID } from "@metaplex-foundation/mpl-bubblegum"; +import { TokenStandard } from "@metaplex-foundation/mpl-token-metadata"; +import { Connection, PublicKey } from "@solana/web3.js"; +import BN from "bn.js"; import type { GetAssetProofRpcInput, GetAssetProofRpcResponse, @@ -15,7 +15,7 @@ import type { GetAssetsByOwnerRpcInput, ReadApiAsset, ReadApiAssetList, -} from '@/ReadApi/types'; +} from "@/ReadApi/types"; type JsonRpcParams = { method: string; @@ -29,9 +29,9 @@ type JsonRpcOutput = { /** @group Errors */ export class ReadApiError extends MetaplexError { - readonly name: string = 'ReadApiError'; + readonly name: string = "ReadApiError"; constructor(message: string, cause?: Error) { - super(message, 'rpc', undefined, cause); + super(message, "rpc", undefined, cause); } } @@ -40,7 +40,7 @@ export class ReadApiError extends MetaplexError { */ export const toNftEditionFromReadApiAsset = (input: ReadApiAsset): NftOriginalEdition => { return { - model: 'nftEdition', + model: "nftEdition", isOriginal: true, address: new PublicKey(input.id), supply: toBigNumber(input.supply.print_current_supply), @@ -53,13 +53,13 @@ export const toNftEditionFromReadApiAsset = (input: ReadApiAsset): NftOriginalEd */ export const toMintFromReadApiAsset = (input: ReadApiAsset): Mint => { const currency: SplTokenCurrency = { - symbol: 'Token', + symbol: "Token", decimals: 0, - namespace: 'spl-token', + namespace: "spl-token", }; return { - model: 'mint', + model: "mint", address: new PublicKey(input.id), mintAuthorityAddress: new PublicKey(input.id), freezeAuthorityAddress: new PublicKey(input.id), @@ -74,26 +74,26 @@ export const toMintFromReadApiAsset = (input: ReadApiAsset): Mint => { * Convert a ReadApi asset's data into standard Metaplex `Metadata` */ export const toMetadataFromReadApiAsset = (input: ReadApiAsset): Metadata => { - const updateAuthority = input.authorities?.find((authority) => authority.scopes.includes('full')); + const updateAuthority = input.authorities?.find((authority) => authority.scopes.includes("full")); - const collection = input.grouping.find(({ group_key }) => group_key === 'collection'); + const collection = input.grouping.find(({ group_key }) => group_key === "collection"); return { - model: 'metadata', + model: "metadata", /** * We technically don't have a metadata address anymore. * So we are using the asset's id as the address */ address: Pda.find(BUBBLEGUM_PROGRAM_ID, [ - Buffer.from('asset', 'utf-8'), + Buffer.from("asset", "utf-8"), new PublicKey(input.compression.tree).toBuffer(), - Uint8Array.from(new BN(input.compression.leaf_id).toArray('le', 8)), + Uint8Array.from(new BN(input.compression.leaf_id).toArray("le", 8)), ]), mintAddress: new PublicKey(input.id), updateAuthorityAddress: new PublicKey(updateAuthority?.address), - name: input.content.metadata?.name ?? '', - symbol: input.content.metadata?.symbol ?? '', + name: input.content.metadata?.name ?? "", + symbol: input.content.metadata?.symbol ?? "", json: input.content.metadata, jsonLoaded: true, @@ -132,14 +132,14 @@ export class WrapperConnection extends Connection { jsonRpcParams: JsonRpcParams, ): Promise> => { const response = await fetch(this.rpcEndpoint, { - method: 'POST', + method: "POST", headers: { - 'Content-Type': 'application/json', + "Content-Type": "application/json", }, body: JSON.stringify({ - jsonrpc: '2.0', + jsonrpc: "2.0", method: jsonRpcParams.method, - id: jsonRpcParams.id ?? 'rpd-op-123', + id: jsonRpcParams.id ?? "rpd-op-123", params: jsonRpcParams.params, }), }); @@ -151,13 +151,13 @@ export class WrapperConnection extends Connection { // It is a PDA with the following seeds: ["asset", tree, leafIndex] async getAsset(assetId: PublicKey): Promise { const { result: asset } = await this.callReadApi({ - method: 'getAsset', + method: "getAsset", params: { id: assetId.toBase58(), }, }); - if (!asset) throw new ReadApiError('No asset returned'); + if (!asset) throw new ReadApiError("No asset returned"); return asset; } @@ -166,26 +166,35 @@ export class WrapperConnection extends Connection { // It is a PDA with the following seeds: ["asset", tree, leafIndex] async getAssetProof(assetId: PublicKey): Promise { const { result: proof } = await this.callReadApi({ - method: 'getAssetProof', + method: "getAssetProof", params: { id: assetId.toBase58(), }, }); - if (!proof) throw new ReadApiError('No asset proof returned'); + if (!proof) throw new ReadApiError("No asset proof returned"); return proof; } // - async getAssetsByGroup({ groupKey, groupValue, page, limit, sortBy, before, after }: GetAssetsByGroupRpcInput): Promise { + async getAssetsByGroup({ + groupKey, + groupValue, + page, + limit, + sortBy, + before, + after, + }: GetAssetsByGroupRpcInput): Promise { // `page` cannot be supplied with `before` or `after` - if (typeof page === 'number' && (before || after)) throw new ReadApiError('Pagination Error. Only one pagination parameter supported per query.'); + if (typeof page === "number" && (before || after)) + throw new ReadApiError("Pagination Error. Only one pagination parameter supported per query."); // a pagination method MUST be selected, but we are defaulting to using `page=0` const { result } = await this.callReadApi({ - method: 'getAssetsByGroup', + method: "getAssetsByGroup", params: { groupKey, groupValue, @@ -197,20 +206,28 @@ export class WrapperConnection extends Connection { }, }); - if (!result) throw new ReadApiError('No results returned'); + if (!result) throw new ReadApiError("No results returned"); return result; } // - async getAssetsByOwner({ ownerAddress, page, limit, sortBy, before, after }: GetAssetsByOwnerRpcInput): Promise { + async getAssetsByOwner({ + ownerAddress, + page, + limit, + sortBy, + before, + after, + }: GetAssetsByOwnerRpcInput): Promise { // `page` cannot be supplied with `before` or `after` - if (typeof page === 'number' && (before || after)) throw new ReadApiError('Pagination Error. Only one pagination parameter supported per query.'); + if (typeof page === "number" && (before || after)) + throw new ReadApiError("Pagination Error. Only one pagination parameter supported per query."); // a pagination method MUST be selected, but we are defaulting to using `page=0` const { result } = await this.callReadApi({ - method: 'getAssetsByOwner', + method: "getAssetsByOwner", params: { ownerAddress, after: after ?? null, @@ -221,7 +238,7 @@ export class WrapperConnection extends Connection { }, }); - if (!result) throw new ReadApiError('No results returned'); + if (!result) throw new ReadApiError("No results returned"); return result; } diff --git a/compression/cnft-burn/anchor/tests/ReadApi/types.ts b/compression/cnft-burn/anchor/tests/ReadApi/types.ts index a49e40fb0..b5c14b296 100644 --- a/compression/cnft-burn/anchor/tests/ReadApi/types.ts +++ b/compression/cnft-burn/anchor/tests/ReadApi/types.ts @@ -2,25 +2,25 @@ Types specific to the ReadApi */ -import type { Metadata, Option } from '@metaplex-foundation/js'; -import type { ConcurrentMerkleTreeAccount } from '@solana/spl-account-compression'; +import type { Metadata, Option } from "@metaplex-foundation/js"; +import type { ConcurrentMerkleTreeAccount } from "@solana/spl-account-compression"; export type ReadApiAssetInterface = - | 'V1_NFT' - | 'V1_PRINT' - | 'LEGACY_NFT' - | 'V2_NFT' - | 'FungibleAsset' - | 'Custom' - | 'Identity' - | 'Executable' - | 'ProgrammableNFT'; + | "V1_NFT" + | "V1_PRINT" + | "LEGACY_NFT" + | "V2_NFT" + | "FungibleAsset" + | "Custom" + | "Identity" + | "Executable" + | "ProgrammableNFT"; -export type ReadApiPropGroupKey = 'collection'; +export type ReadApiPropGroupKey = "collection"; -export type ReadApiPropSortBy = 'created' | 'updated' | 'recent_action'; +export type ReadApiPropSortBy = "created" | "updated" | "recent_action"; -export type ReadApiPropSortDirection = 'asc' | 'desc'; +export type ReadApiPropSortDirection = "asc" | "desc"; export type TransferNftCompressionParam = { ownership?: ReadApiOwnershipMetadata; @@ -36,7 +36,7 @@ export type ReadApiParamAssetSortBy = { export type ReadApiAssetContent = { json_uri: string; - metadata: Metadata['json']; + metadata: Metadata["json"]; }; export type ReadApiCompressionMetadata = { @@ -55,7 +55,7 @@ export type ReadApiOwnershipMetadata = { delegated: boolean; delegate: string | null; owner: string; - ownership_model: 'single' | 'token'; + ownership_model: "single" | "token"; }; export type ReadApiAssetSupplyMetadata = { @@ -74,7 +74,7 @@ export type ReadApiAssetGrouping = { group_value: string; }; -export type ReadApiAuthorityScope = 'full'; +export type ReadApiAuthorityScope = "full"; export type ReadApiAssetAuthority = { address: string; @@ -133,7 +133,7 @@ export type ReadApiAsset = { content: ReadApiAssetContent; royalty: ReadApiAssetRoyaltyMetadata; supply: ReadApiAssetSupplyMetadata; - creators: Metadata['creators']; + creators: Metadata["creators"]; grouping: Array; compression: ReadApiCompressionMetadata; }; diff --git a/compression/cnft-burn/anchor/tests/cnft-burn.ts b/compression/cnft-burn/anchor/tests/cnft-burn.ts index c2e9464ef..5bc3047c9 100644 --- a/compression/cnft-burn/anchor/tests/cnft-burn.ts +++ b/compression/cnft-burn/anchor/tests/cnft-burn.ts @@ -1,17 +1,17 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; -import { PROGRAM_ID as BUBBLEGUM_PROGRAM_ID } from '@metaplex-foundation/mpl-bubblegum'; -import { SPL_ACCOUNT_COMPRESSION_PROGRAM_ID, SPL_NOOP_PROGRAM_ID } from '@solana/spl-account-compression'; -import type { CnftBurn } from '../target/types/cnft_burn'; -import { createAndMint } from './createAndMint'; -import { getcNFTsFromCollection } from './fetchNFTsByCollection'; -import { getAsset, getAssetProof } from './readApi'; -import { decode, mapProof } from './utils'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; +import { PROGRAM_ID as BUBBLEGUM_PROGRAM_ID } from "@metaplex-foundation/mpl-bubblegum"; +import { SPL_ACCOUNT_COMPRESSION_PROGRAM_ID, SPL_NOOP_PROGRAM_ID } from "@solana/spl-account-compression"; +import type { CnftBurn } from "../target/types/cnft_burn"; +import { createAndMint } from "./createAndMint"; +import { getcNFTsFromCollection } from "./fetchNFTsByCollection"; +import { getAsset, getAssetProof } from "./readApi"; +import { decode, mapProof } from "./utils"; // Replace this with your custom RPC endpoint that supports cNFT indexing -const _RPC_PATH = 'https://api.devnet.solana.com'; +const _RPC_PATH = "https://api.devnet.solana.com"; -describe('cnft-burn', () => { +describe("cnft-burn", () => { // Configure the client to use the local cluster. anchor.setProvider(anchor.AnchorProvider.env()); @@ -23,20 +23,20 @@ describe('cnft-burn', () => { const MPL_BUBBLEGUM_PROGRAM_ID_KEY = new anchor.web3.PublicKey(BUBBLEGUM_PROGRAM_ID); // this is the assetId of the cNft you want to burn - let assetId = ''; + let assetId = ""; - it('Should create the tree and mint a cnft', async () => { + it("Should create the tree and mint a cnft", async () => { const { tree, collection } = await createAndMint(); if (!tree.treeAddress) { - throw new Error('Tree address not found'); + throw new Error("Tree address not found"); } treeAddress = tree.treeAddress; const fetchcNFTs = await getcNFTsFromCollection(collection.mint, payerWallet.publicKey.toString()); - console.log('fetchcNFTs', fetchcNFTs); + console.log("fetchcNFTs", fetchcNFTs); assetId = fetchcNFTs[0]; }); - it('Burn cNft!', async () => { + it("Burn cNft!", async () => { const asset = await getAsset(assetId); const proof = await getAssetProof(assetId); @@ -46,7 +46,10 @@ describe('cnft-burn', () => { const creatorHash = decode(asset.compression.creator_hash); const nonce = new anchor.BN(asset.compression.leaf_id); const index = asset.compression.leaf_id; - const [treeAuthority, _bump2] = anchor.web3.PublicKey.findProgramAddressSync([treeAddress.toBuffer()], MPL_BUBBLEGUM_PROGRAM_ID_KEY); + const [treeAuthority, _bump2] = anchor.web3.PublicKey.findProgramAddressSync( + [treeAddress.toBuffer()], + MPL_BUBBLEGUM_PROGRAM_ID_KEY, + ); const tx = await program.methods .burnCnft(root, dataHash, creatorHash, nonce, index) .accounts({ @@ -62,7 +65,7 @@ describe('cnft-burn', () => { .rpc({ skipPreflight: true, }); - console.log('Your transaction signature', tx); + console.log("Your transaction signature", tx); // here is a sample transaction signature on devnet // https://explorer.solana.com/tx/2MpeHi64pbWNY7BKBuhAp4yND5HdfQqNqkd8pu6F6meoSNUYRvxQgV5TC4w8BM8hUihB8G8TwBAaPRqS7pnN8Nu1?cluster=devnet }); diff --git a/compression/cnft-burn/anchor/tests/createAndMint.ts b/compression/cnft-burn/anchor/tests/createAndMint.ts index add25d3cd..7ef574b1d 100644 --- a/compression/cnft-burn/anchor/tests/createAndMint.ts +++ b/compression/cnft-burn/anchor/tests/createAndMint.ts @@ -12,18 +12,18 @@ less console logging and explanation of what is occurring */ -import * as anchor from '@anchor-lang/core'; -import { type MetadataArgs, TokenProgramVersion, TokenStandard } from '@metaplex-foundation/mpl-bubblegum'; -import type { CreateMetadataAccountArgsV3 } from '@metaplex-foundation/mpl-token-metadata'; -import type { ValidDepthSizePair } from '@solana/spl-account-compression'; -import { Keypair, LAMPORTS_PER_SOL } from '@solana/web3.js'; -import { RPC_PATH } from './cnft-burn'; +import * as anchor from "@anchor-lang/core"; +import { type MetadataArgs, TokenProgramVersion, TokenStandard } from "@metaplex-foundation/mpl-bubblegum"; +import type { CreateMetadataAccountArgsV3 } from "@metaplex-foundation/mpl-token-metadata"; +import type { ValidDepthSizePair } from "@solana/spl-account-compression"; +import { Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js"; +import { RPC_PATH } from "./cnft-burn"; // local import of the connection wrapper, to help with using the ReadApi -import { WrapperConnection } from './ReadApi/WrapperConnection'; +import { WrapperConnection } from "./ReadApi/WrapperConnection"; // import custom helpers to mint compressed NFTs -import { createCollection, createTree, mintCompressedNFT } from './utils/compression'; +import { createCollection, createTree, mintCompressedNFT } from "./utils/compression"; // import custom helpers for demos -import { numberFormatter } from './utils/helpers'; +import { numberFormatter } from "./utils/helpers"; // define some reusable balance values for tracking let initBalance: number; @@ -39,7 +39,7 @@ export async function createAndMint() { const payerWallet = provider.wallet as anchor.Wallet; const payer = payerWallet.payer; - console.log('Payer address:', payer.publicKey.toBase58()); + console.log("Payer address:", payer.publicKey.toBase58()); ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// @@ -48,7 +48,7 @@ export async function createAndMint() { const CLUSTER_URL = RPC_PATH; // create a new rpc connection, using the ReadApi wrapper - const connection = new WrapperConnection(CLUSTER_URL, 'confirmed'); + const connection = new WrapperConnection(CLUSTER_URL, "confirmed"); // get the payer's starting balance (only used for demonstration purposes) initBalance = await connection.getBalance(payer.publicKey); @@ -84,10 +84,10 @@ export async function createAndMint() { // define the metadata to be used for creating the NFT collection const collectionMetadataV3: CreateMetadataAccountArgsV3 = { data: { - name: 'Test Burn', - symbol: 'TB', + name: "Test Burn", + symbol: "TB", // specific json metadata for the collection - uri: 'https://supersweetcollection.notarealurl/collection.json', + uri: "https://supersweetcollection.notarealurl/collection.json", sellerFeeBasisPoints: 100, creators: [ { @@ -111,10 +111,10 @@ export async function createAndMint() { */ const compressedNFTMetadata: MetadataArgs = { - name: 'Pratik test', + name: "Pratik test", symbol: collectionMetadataV3.data.symbol, // specific json metadata for each NFT - uri: 'https://bafkreies5r7b5eszpq5dgnw2brhjtlw7xtdtmsmoniebqehf37nv5rxajy.ipfs.nftstorage.link/', + uri: "https://bafkreies5r7b5eszpq5dgnw2brhjtlw7xtdtmsmoniebqehf37nv5rxajy.ipfs.nftstorage.link/", creators: [ { address: payer.publicKey, @@ -154,8 +154,8 @@ export async function createAndMint() { // fetch the payer's final balance balance = await connection.getBalance(payer.publicKey); - console.log('==============================='); - console.log('Total cost:', numberFormatter((initBalance - balance) / LAMPORTS_PER_SOL, true), 'SOL\n'); + console.log("==============================="); + console.log("Total cost:", numberFormatter((initBalance - balance) / LAMPORTS_PER_SOL, true), "SOL\n"); return { tree, collection }; } diff --git a/compression/cnft-burn/anchor/tests/fetchNFTsByCollection.ts b/compression/cnft-burn/anchor/tests/fetchNFTsByCollection.ts index e12114ee5..11fef4d0a 100644 --- a/compression/cnft-burn/anchor/tests/fetchNFTsByCollection.ts +++ b/compression/cnft-burn/anchor/tests/fetchNFTsByCollection.ts @@ -4,13 +4,13 @@ */ // imports from other libraries -import type { PublicKey } from '@solana/web3.js'; -import { RPC_PATH } from './cnft-burn'; +import type { PublicKey } from "@solana/web3.js"; +import { RPC_PATH } from "./cnft-burn"; // local import of the connection wrapper, to help with using the ReadApi -import { WrapperConnection } from './ReadApi/WrapperConnection'; +import { WrapperConnection } from "./ReadApi/WrapperConnection"; // import custom helpers for demos -import { printConsoleSeparator } from './utils/helpers'; +import { printConsoleSeparator } from "./utils/helpers"; export async function getcNFTsFromCollection(collectionMint: PublicKey, owner: string) { // load the stored PublicKeys for ease of use @@ -23,7 +23,7 @@ export async function getcNFTsFromCollection(collectionMint: PublicKey, owner: s // convert the locally saved keys to PublicKeys // const collectionMint: PublicKey = keys.collectionMint; - console.log('Collection mint:', collectionMint.toBase58()); + console.log("Collection mint:", collectionMint.toBase58()); ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// @@ -38,31 +38,31 @@ export async function getcNFTsFromCollection(collectionMint: PublicKey, owner: s const assets = await connection .getAssetsByGroup({ - groupKey: 'collection', + groupKey: "collection", groupValue: collectionMint.toBase58(), sortBy: { - sortBy: 'recent_action', - sortDirection: 'asc', + sortBy: "recent_action", + sortDirection: "asc", }, }) .then((res) => { - console.log('Total assets returned:', res.total); + console.log("Total assets returned:", res.total); // loop over each of the asset items in the collection const assetsIds = res.items?.map((asset) => { // display a spacer between each of the assets - console.log('\n==============================================='); + console.log("\n==============================================="); // print the entire asset record to the console // console.log(asset); // print some useful info - console.log('assetId:', asset.id); - console.log('ownership:', asset.ownership); - console.log('compression:', asset.compression); + console.log("assetId:", asset.id); + console.log("ownership:", asset.ownership); + console.log("compression:", asset.compression); if (asset.ownership?.owner === owner) { - console.log('assetId:', asset.id); + console.log("assetId:", asset.id); return asset.id; } return undefined; diff --git a/compression/cnft-burn/anchor/tests/readApi.ts b/compression/cnft-burn/anchor/tests/readApi.ts index 0ee382850..87b9c4e0e 100644 --- a/compression/cnft-burn/anchor/tests/readApi.ts +++ b/compression/cnft-burn/anchor/tests/readApi.ts @@ -2,20 +2,21 @@ // as it supports more readAPI functionality // this is just a subset of functions for quick availabiity -import axios from 'axios'; -import { RPC_PATH } from './cnft-burn'; +import axios from "axios"; +import { RPC_PATH } from "./cnft-burn"; // you might want to change that to your custom RPC endpoint as this endpoint is not going to work as it does not support DAS +// biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 export async function getAsset(assetId: any, rpcUrl = RPC_PATH): Promise { try { const axiosInstance = axios.create({ baseURL: rpcUrl, }); const response = await axiosInstance.post(rpcUrl, { - jsonrpc: '2.0', - method: 'getAsset', - id: 'rpd-op-123', + jsonrpc: "2.0", + method: "getAsset", + id: "rpd-op-123", params: { id: assetId, }, @@ -26,15 +27,16 @@ export async function getAsset(assetId: any, rpcUrl = RPC_PATH): Promise { } } +// biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 export async function getAssetProof(assetId: any, rpcUrl = RPC_PATH): Promise { try { const axiosInstance = axios.create({ baseURL: rpcUrl, }); const response = await axiosInstance.post(rpcUrl, { - jsonrpc: '2.0', - method: 'getAssetProof', - id: 'rpd-op-123', + jsonrpc: "2.0", + method: "getAssetProof", + id: "rpd-op-123", params: { id: assetId, }, diff --git a/compression/cnft-burn/anchor/tests/utils.ts b/compression/cnft-burn/anchor/tests/utils.ts index 43759dd36..70aa141d9 100644 --- a/compression/cnft-burn/anchor/tests/utils.ts +++ b/compression/cnft-burn/anchor/tests/utils.ts @@ -1,9 +1,9 @@ -import { type AccountMeta, Keypair, PublicKey } from '@solana/web3.js'; +import { type AccountMeta, Keypair, PublicKey } from "@solana/web3.js"; -import * as bs58 from 'bs58'; +import * as bs58 from "bs58"; export function loadWalletKey(keypairFile: string): Keypair { - const fs = require('node:fs'); + const fs = require("node:fs"); return Keypair.fromSecretKey(new Uint8Array(JSON.parse(fs.readFileSync(keypairFile).toString()))); } @@ -19,7 +19,7 @@ function bufferToArray(buffer: Buffer): number[] { } export const mapProof = (assetProof: { proof: string[] }): AccountMeta[] => { if (!assetProof.proof || assetProof.proof.length === 0) { - throw new Error('Proof is empty'); + throw new Error("Proof is empty"); } return assetProof.proof.map((node) => ({ pubkey: new PublicKey(node), diff --git a/compression/cnft-burn/anchor/tests/utils/compression.ts b/compression/cnft-burn/anchor/tests/utils/compression.ts index 3e3e7d01a..b91ee1170 100644 --- a/compression/cnft-burn/anchor/tests/utils/compression.ts +++ b/compression/cnft-burn/anchor/tests/utils/compression.ts @@ -5,20 +5,32 @@ import { createCreateTreeInstruction, createMintToCollectionV1Instruction, type MetadataArgs, -} from '@metaplex-foundation/mpl-bubblegum'; +} from "@metaplex-foundation/mpl-bubblegum"; import { type CreateMetadataAccountArgsV3, createCreateMasterEditionV3Instruction, createCreateMetadataAccountV3Instruction, createSetCollectionSizeInstruction, PROGRAM_ID as TOKEN_METADATA_PROGRAM_ID, -} from '@metaplex-foundation/mpl-token-metadata'; -import { createAllocTreeIx, SPL_ACCOUNT_COMPRESSION_PROGRAM_ID, SPL_NOOP_PROGRAM_ID, type ValidDepthSizePair } from '@solana/spl-account-compression'; -import { createAccount, createMint, mintTo, TOKEN_PROGRAM_ID } from '@solana/spl-token'; -import { type Connection, type Keypair, PublicKey, sendAndConfirmTransaction, Transaction, type TransactionInstruction } from '@solana/web3.js'; +} from "@metaplex-foundation/mpl-token-metadata"; +import { + createAllocTreeIx, + SPL_ACCOUNT_COMPRESSION_PROGRAM_ID, + SPL_NOOP_PROGRAM_ID, + type ValidDepthSizePair, +} from "@solana/spl-account-compression"; +import { createAccount, createMint, mintTo, TOKEN_PROGRAM_ID } from "@solana/spl-token"; +import { + type Connection, + type Keypair, + PublicKey, + sendAndConfirmTransaction, + Transaction, + type TransactionInstruction, +} from "@solana/web3.js"; // import local helper functions -import { explorerURL, extractSignatureFromFailedTransaction } from './helpers'; +import { explorerURL, extractSignatureFromFailedTransaction } from "./helpers"; /* Helper function to create a merkle tree on chain, including allocating @@ -31,16 +43,25 @@ export async function createTree( maxDepthSizePair: ValidDepthSizePair, canopyDepth = 0, ) { - console.log('Creating a new Merkle tree...'); - console.log('treeAddress:', treeKeypair.publicKey.toBase58()); + console.log("Creating a new Merkle tree..."); + console.log("treeAddress:", treeKeypair.publicKey.toBase58()); // derive the tree's authority (PDA), owned by Bubblegum - const [treeAuthority, _bump] = PublicKey.findProgramAddressSync([treeKeypair.publicKey.toBuffer()], BUBBLEGUM_PROGRAM_ID); - console.log('treeAuthority:', treeAuthority.toBase58()); + const [treeAuthority, _bump] = PublicKey.findProgramAddressSync( + [treeKeypair.publicKey.toBuffer()], + BUBBLEGUM_PROGRAM_ID, + ); + console.log("treeAuthority:", treeAuthority.toBase58()); // allocate the tree's account on chain with the `space` // NOTE: this will compute the space needed to store the tree on chain (and the lamports required to store it) - const allocTreeIx = await createAllocTreeIx(connection, treeKeypair.publicKey, payer.publicKey, maxDepthSizePair, canopyDepth); + const allocTreeIx = await createAllocTreeIx( + connection, + treeKeypair.publicKey, + payer.publicKey, + maxDepthSizePair, + canopyDepth, + ); // create the instruction to actually create the tree const createTreeIx = createCreateTreeInstruction( @@ -73,18 +94,19 @@ export async function createTree( // ensuring the `treeKeypair` PDA and the `payer` are BOTH signers [treeKeypair, payer], { - commitment: 'confirmed', + commitment: "confirmed", skipPreflight: true, }, ); - console.log('\nMerkle tree created successfully!'); + console.log("\nMerkle tree created successfully!"); console.log(explorerURL({ txSignature })); // return useful info return { treeAuthority, treeAddress: treeKeypair.publicKey }; + // biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 } catch (err: any) { - console.error('\nFailed to create merkle tree:', err); + console.error("\nFailed to create merkle tree:", err); // log a block explorer link for the failed transaction await extractSignatureFromFailedTransaction(connection, err); @@ -97,7 +119,11 @@ export async function createTree( * Create an NFT collection on-chain, using the regular Metaplex standards * with the `payer` as the authority */ -export async function createCollection(connection: Connection, payer: Keypair, metadataV3: CreateMetadataAccountArgsV3) { +export async function createCollection( + connection: Connection, + payer: Keypair, + metadataV3: CreateMetadataAccountArgsV3, +) { // create and initialize the SPL token mint console.log("Creating the collection's mint..."); const mint = await createMint( @@ -110,10 +136,10 @@ export async function createCollection(connection: Connection, payer: Keypair, m // decimals - use `0` for NFTs since they are non-fungible 0, ); - console.log('Mint address:', mint.toBase58()); + console.log("Mint address:", mint.toBase58()); // create the token account - console.log('Creating a token account...'); + console.log("Creating a token account..."); const tokenAccount = await createAccount( connection, payer, @@ -121,10 +147,10 @@ export async function createCollection(connection: Connection, payer: Keypair, m payer.publicKey, // undefined, undefined, ); - console.log('Token account:', tokenAccount.toBase58()); + console.log("Token account:", tokenAccount.toBase58()); // mint 1 token () - console.log('Minting 1 token for the collection...'); + console.log("Minting 1 token for the collection..."); const _mintSig = await mintTo( connection, payer, @@ -142,10 +168,10 @@ export async function createCollection(connection: Connection, payer: Keypair, m // derive the PDA for the metadata account const [metadataAccount, _bump] = PublicKey.findProgramAddressSync( - [Buffer.from('metadata', 'utf8'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mint.toBuffer()], + [Buffer.from("metadata", "utf8"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mint.toBuffer()], TOKEN_METADATA_PROGRAM_ID, ); - console.log('Metadata account:', metadataAccount.toBase58()); + console.log("Metadata account:", metadataAccount.toBase58()); // create an instruction to create the metadata account const createMetadataIx = createCreateMetadataAccountV3Instruction( @@ -163,10 +189,15 @@ export async function createCollection(connection: Connection, payer: Keypair, m // derive the PDA for the metadata account const [masterEditionAccount, _bump2] = PublicKey.findProgramAddressSync( - [Buffer.from('metadata', 'utf8'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mint.toBuffer(), Buffer.from('edition', 'utf8')], + [ + Buffer.from("metadata", "utf8"), + TOKEN_METADATA_PROGRAM_ID.toBuffer(), + mint.toBuffer(), + Buffer.from("edition", "utf8"), + ], TOKEN_METADATA_PROGRAM_ID, ); - console.log('Master edition account:', masterEditionAccount.toBase58()); + console.log("Master edition account:", masterEditionAccount.toBase58()); // create an instruction to create the metadata account const createMasterEditionIx = createCreateMasterEditionV3Instruction( @@ -204,14 +235,14 @@ export async function createCollection(connection: Connection, payer: Keypair, m // send the transaction to the cluster const txSignature = await sendAndConfirmTransaction(connection, tx, [payer], { - commitment: 'confirmed', + commitment: "confirmed", skipPreflight: true, }); - console.log('\nCollection successfully created!'); + console.log("\nCollection successfully created!"); console.log(explorerURL({ txSignature })); } catch (err) { - console.error('\nFailed to create collection:', err); + console.error("\nFailed to create collection:", err); // log a block explorer link for the failed transaction await extractSignatureFromFailedTransaction(connection, err); @@ -242,7 +273,7 @@ export async function mintCompressedNFT( // derive a PDA (owned by Bubblegum) to act as the signer of the compressed minting const [bubblegumSigner, _bump2] = PublicKey.findProgramAddressSync( // `collection_cpi` is a custom prefix required by the Bubblegum program - [Buffer.from('collection_cpi', 'utf8')], + [Buffer.from("collection_cpi", "utf8")], BUBBLEGUM_PROGRAM_ID, ); @@ -269,8 +300,8 @@ export async function mintCompressedNFT( */ const computedDataHash = new PublicKey(computeDataHash(metadataArgs)).toBase58(); const computedCreatorHash = new PublicKey(computeCreatorHash(metadataArgs.creators)).toBase58(); - console.log('computedDataHash:', computedDataHash); - console.log('computedCreatorHash:', computedCreatorHash); + console.log("computedDataHash:", computedDataHash); + console.log("computedCreatorHash:", computedCreatorHash); /* Add a single mint to collection instruction @@ -326,16 +357,16 @@ export async function mintCompressedNFT( // send the transaction to the cluster const txSignature = await sendAndConfirmTransaction(connection, tx, [payer], { - commitment: 'confirmed', + commitment: "confirmed", skipPreflight: true, }); - console.log('\nSuccessfully minted the compressed NFT!'); + console.log("\nSuccessfully minted the compressed NFT!"); console.log(explorerURL({ txSignature })); return txSignature; } catch (err) { - console.error('\nFailed to mint compressed NFT:', err); + console.error("\nFailed to mint compressed NFT:", err); // log a block explorer link for the failed transaction await extractSignatureFromFailedTransaction(connection, err); diff --git a/compression/cnft-burn/anchor/tests/utils/helpers.ts b/compression/cnft-burn/anchor/tests/utils/helpers.ts index da6481353..14dcf3db8 100644 --- a/compression/cnft-burn/anchor/tests/utils/helpers.ts +++ b/compression/cnft-burn/anchor/tests/utils/helpers.ts @@ -1,11 +1,11 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { type Connection, Keypair, LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js'; +import fs from "node:fs"; +import path from "node:path"; +import { type Connection, Keypair, LAMPORTS_PER_SOL, PublicKey } from "@solana/web3.js"; // define some default locations -const DEFAULT_KEY_DIR_NAME = '.local_keys'; -const DEFAULT_PUBLIC_KEY_FILE = 'keys.json'; -const DEFAULT_DEMO_DATA_FILE = 'demo.json'; +const DEFAULT_KEY_DIR_NAME = ".local_keys"; +const DEFAULT_PUBLIC_KEY_FILE = "keys.json"; +const DEFAULT_DEMO_DATA_FILE = "demo.json"; /* Load locally stored PublicKey addresses @@ -13,20 +13,20 @@ const DEFAULT_DEMO_DATA_FILE = 'demo.json'; */ export function loadPublicKeysFromFile(absPath = `${DEFAULT_KEY_DIR_NAME}/${DEFAULT_PUBLIC_KEY_FILE}`) { try { - if (!absPath) throw Error('No path provided'); - if (!fs.existsSync(absPath)) throw Error('File does not exist.'); + if (!absPath) throw Error("No path provided"); + if (!fs.existsSync(absPath)) throw Error("File does not exist."); // load the public keys from the file - const data = JSON.parse(fs.readFileSync(absPath, { encoding: 'utf-8' })) || {}; + const data = JSON.parse(fs.readFileSync(absPath, { encoding: "utf-8" })) || {}; // convert all loaded keyed values into valid public keys for (const [key, value] of Object.entries(data)) { - data[key] = new PublicKey(value as string) ?? ''; + data[key] = new PublicKey(value as string) ?? ""; } return data; } catch (_err) { - console.warn('Unable to load local file'); + console.warn("Unable to load local file"); } // always return an object return {}; @@ -35,23 +35,28 @@ export function loadPublicKeysFromFile(absPath = `${DEFAULT_KEY_DIR_NAME}/${DEFA /* Locally save a demo data to the filesystem for later retrieval */ -export function saveDemoDataToFile(name: string, newData: any, absPath = `${DEFAULT_KEY_DIR_NAME}/${DEFAULT_DEMO_DATA_FILE}`) { +export function saveDemoDataToFile( + name: string, + // biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 + newData: any, + absPath = `${DEFAULT_KEY_DIR_NAME}/${DEFAULT_DEMO_DATA_FILE}`, +) { try { let data: object = {}; // fetch all the current values, when the storage file exists - if (fs.existsSync(absPath)) data = JSON.parse(fs.readFileSync(absPath, { encoding: 'utf-8' })) || {}; + if (fs.existsSync(absPath)) data = JSON.parse(fs.readFileSync(absPath, { encoding: "utf-8" })) || {}; data = { ...data, [name]: newData }; // actually save the data to the file fs.writeFileSync(absPath, JSON.stringify(data), { - encoding: 'utf-8', + encoding: "utf-8", }); return data; } catch (err) { - console.warn('Unable to save to file'); + console.warn("Unable to save to file"); console.warn(err); } @@ -62,23 +67,29 @@ export function saveDemoDataToFile(name: string, newData: any, absPath = `${DEFA /* Locally save a PublicKey addresses to the filesystem for later retrieval */ -export function savePublicKeyToFile(name: string, publicKey: PublicKey, absPath = `${DEFAULT_KEY_DIR_NAME}/${DEFAULT_PUBLIC_KEY_FILE}`) { +export function savePublicKeyToFile( + name: string, + publicKey: PublicKey, + absPath = `${DEFAULT_KEY_DIR_NAME}/${DEFAULT_PUBLIC_KEY_FILE}`, +) { try { // if (!absPath) throw Error("No path provided"); // if (!fs.existsSync(absPath)) throw Error("File does not exist."); // fetch all the current values + // biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 let data: any = loadPublicKeysFromFile(absPath); // convert all loaded keyed values from PublicKeys to strings for (const [key, value] of Object.entries(data)) { + // biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 data[key as any] = (value as PublicKey).toBase58(); } data = { ...data, [name]: publicKey.toBase58() }; // actually save the data to the file fs.writeFileSync(absPath, JSON.stringify(data), { - encoding: 'utf-8', + encoding: "utf-8", }); // reload the keys for sanity @@ -86,7 +97,7 @@ export function savePublicKeyToFile(name: string, publicKey: PublicKey, absPath return data; } catch (_err) { - console.warn('Unable to save to file'); + console.warn("Unable to save to file"); } // always return an object return {}; @@ -97,16 +108,16 @@ export function savePublicKeyToFile(name: string, publicKey: PublicKey, absPath */ export function loadKeypairFromFile(absPath: string) { try { - if (!absPath) throw Error('No path provided'); - if (!fs.existsSync(absPath)) throw Error('File does not exist.'); + if (!absPath) throw Error("No path provided"); + if (!fs.existsSync(absPath)) throw Error("File does not exist."); // load the keypair from the file - const keyfileBytes = JSON.parse(fs.readFileSync(absPath, { encoding: 'utf-8' })); + const keyfileBytes = JSON.parse(fs.readFileSync(absPath, { encoding: "utf-8" })); // parse the loaded secretKey into a valid keypair const keypair = Keypair.fromSecretKey(new Uint8Array(keyfileBytes)); return keypair; } catch (err) { - console.error('loadKeypairFromFile:', err); + console.error("loadKeypairFromFile:", err); throw err; } } @@ -126,7 +137,7 @@ export function saveKeypairToFile(keypair: Keypair, relativeFileName: string, di // write the `secretKey` value as a string fs.writeFileSync(fileName, `[${keypair.secretKey.toString()}]`, { - encoding: 'utf-8', + encoding: "utf-8", }); return fileName; @@ -148,7 +159,7 @@ export function loadOrGenerateKeypair(fileName: string, dirName: string = DEFAUL return keypair; } catch (err) { - console.error('loadOrGenerateKeypair:', err); + console.error("loadOrGenerateKeypair:", err); throw err; } } @@ -163,17 +174,17 @@ export function explorerURL({ }: { address?: string; txSignature?: string; - cluster?: 'devnet' | 'testnet' | 'mainnet' | 'mainnet-beta'; + cluster?: "devnet" | "testnet" | "mainnet" | "mainnet-beta"; }) { let baseUrl: string; // if (address) baseUrl = `https://explorer.solana.com/address/${address}`; else if (txSignature) baseUrl = `https://explorer.solana.com/tx/${txSignature}`; - else return '[unknown]'; + else return "[unknown]"; // auto append the desired search params const url = new URL(baseUrl); - url.searchParams.append('cluster', cluster || 'devnet'); + url.searchParams.append("cluster", cluster || "devnet"); return `${url.toString()}\n`; } @@ -191,7 +202,7 @@ export async function airdropOnLowBalance(connection: Connection, keypair: Keypa if (forceAirdrop === true || balance < MIN_BALANCE_TO_AIRDROP) { console.log(`Requesting airdrop of 1 SOL to ${keypair.publicKey.toBase58()}...`); await connection.requestAirdrop(keypair.publicKey, LAMPORTS_PER_SOL).then((sig) => { - console.log('Tx signature:', sig); + console.log("Tx signature:", sig); // balance = balance + LAMPORTS_PER_SOL; }); @@ -207,11 +218,14 @@ export async function airdropOnLowBalance(connection: Connection, keypair: Keypa /* Helper function to extract a transaction signature from a failed transaction's error message */ +// biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 export async function extractSignatureFromFailedTransaction(connection: Connection, err: any, fetchLogs?: boolean) { if (err?.signature) return err.signature; // extract the failed transaction's signature - const failedSig = new RegExp(/^((.*)?Error: )?(Transaction|Signature) ([A-Z0-9]{32,}) /gim).exec(err?.message?.toString())?.[4]; + const failedSig = new RegExp(/^((.*)?Error: )?(Transaction|Signature) ([A-Z0-9]{32,}) /gim).exec( + err?.message?.toString(), + )?.[4]; // ensure a signature was found if (failedSig) { @@ -223,14 +237,14 @@ export async function extractSignatureFromFailedTransaction(connection: Connecti }) .then((tx) => { console.log(`\n==== Transaction logs for ${failedSig} ====`); - console.log(explorerURL({ txSignature: failedSig }), ''); - console.log(tx?.meta?.logMessages ?? 'No log messages provided by RPC'); - console.log('==== END LOGS ====\n'); + console.log(explorerURL({ txSignature: failedSig }), ""); + console.log(tx?.meta?.logMessages ?? "No log messages provided by RPC"); + console.log("==== END LOGS ====\n"); }); else { - console.log('\n========================================'); + console.log("\n========================================"); console.log(explorerURL({ txSignature: failedSig })); - console.log('========================================\n'); + console.log("========================================\n"); } } @@ -255,7 +269,7 @@ export function numberFormatter(num: number, forceDecimals = false) { Display a separator in the console, with our without a message */ export function printConsoleSeparator(message?: string) { - console.log('\n==============================================='); - console.log('===============================================\n'); + console.log("\n==============================================="); + console.log("===============================================\n"); if (message) console.log(message); } diff --git a/compression/cnft-vault/anchor/package.json b/compression/cnft-vault/anchor/package.json index 4aeee309a..993a30e05 100644 --- a/compression/cnft-vault/anchor/package.json +++ b/compression/cnft-vault/anchor/package.json @@ -1,23 +1,23 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@metaplex-foundation/mpl-bubblegum": "^0.6.2", - "@solana/spl-account-compression": "^0.1.8", - "axios": "^1.4.0" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@metaplex-foundation/mpl-bubblegum": "^0.6.2", + "@solana/spl-account-compression": "^0.1.8", + "axios": "^1.4.0" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/compression/cnft-vault/anchor/tests/readAPI.ts b/compression/cnft-vault/anchor/tests/readAPI.ts index 070203f17..3db19e145 100644 --- a/compression/cnft-vault/anchor/tests/readAPI.ts +++ b/compression/cnft-vault/anchor/tests/readAPI.ts @@ -2,20 +2,21 @@ // as it supports more readAPI functionality // this is just a subset of functions for quick availabiity -import axios from 'axios'; +import axios from "axios"; // you might want to change that to your custom RPC -const RPC_PATH = 'https://rpc-devnet.aws.metaplex.com/'; +const RPC_PATH = "https://rpc-devnet.aws.metaplex.com/"; +// biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 export async function getAsset(assetId: any, rpcUrl = RPC_PATH): Promise { try { const axiosInstance = axios.create({ baseURL: rpcUrl, }); const response = await axiosInstance.post(rpcUrl, { - jsonrpc: '2.0', - method: 'getAsset', - id: 'rpd-op-123', + jsonrpc: "2.0", + method: "getAsset", + id: "rpd-op-123", params: { id: assetId, }, @@ -26,15 +27,16 @@ export async function getAsset(assetId: any, rpcUrl = RPC_PATH): Promise { } } +// biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 export async function getAssetProof(assetId: any, rpcUrl = RPC_PATH): Promise { try { const axiosInstance = axios.create({ baseURL: rpcUrl, }); const response = await axiosInstance.post(rpcUrl, { - jsonrpc: '2.0', - method: 'getAssetProof', - id: 'rpd-op-123', + jsonrpc: "2.0", + method: "getAssetProof", + id: "rpd-op-123", params: { id: assetId, }, diff --git a/compression/cnft-vault/anchor/tests/scripts/constants.ts b/compression/cnft-vault/anchor/tests/scripts/constants.ts index 2727afc0c..4ab604bfb 100644 --- a/compression/cnft-vault/anchor/tests/scripts/constants.ts +++ b/compression/cnft-vault/anchor/tests/scripts/constants.ts @@ -3,13 +3,9 @@ import type { CnftVault } from "../../target/types/cnft_vault"; import IDL from "../../target/types/cnft_vault"; import { loadWalletKey } from "../utils"; -export const connection = new anchor.web3.Connection( - "https://api.devnet.solana.com", -); +export const connection = new anchor.web3.Connection("https://api.devnet.solana.com"); export const keypair = loadWalletKey("~/.config/solana/id.json"); export const wallet = new anchor.Wallet(keypair); export const provider = new anchor.AnchorProvider(connection, wallet, {}); -export const programID = new anchor.web3.PublicKey( - "CNftyK7T8udPwYRzZUMWzbh79rKrz9a5GwV2wv7iEHpk", -); +export const programID = new anchor.web3.PublicKey("CNftyK7T8udPwYRzZUMWzbh79rKrz9a5GwV2wv7iEHpk"); export const program = new anchor.Program(IDL, programID, provider); diff --git a/compression/cnft-vault/anchor/tests/scripts/withdraw.ts b/compression/cnft-vault/anchor/tests/scripts/withdraw.ts index 133857d15..73144d840 100644 --- a/compression/cnft-vault/anchor/tests/scripts/withdraw.ts +++ b/compression/cnft-vault/anchor/tests/scripts/withdraw.ts @@ -1,21 +1,24 @@ -import * as anchor from '@anchor-lang/core'; -import { PROGRAM_ID as BUBBLEGUM_PROGRAM_ID } from '@metaplex-foundation/mpl-bubblegum'; -import { SPL_ACCOUNT_COMPRESSION_PROGRAM_ID, SPL_NOOP_PROGRAM_ID } from '@solana/spl-account-compression'; -import { getAsset, getAssetProof } from '../readAPI'; -import { decode, mapProof } from '../utils'; +import * as anchor from "@anchor-lang/core"; +import { PROGRAM_ID as BUBBLEGUM_PROGRAM_ID } from "@metaplex-foundation/mpl-bubblegum"; +import { SPL_ACCOUNT_COMPRESSION_PROGRAM_ID, SPL_NOOP_PROGRAM_ID } from "@solana/spl-account-compression"; +import { getAsset, getAssetProof } from "../readAPI"; +import { decode, mapProof } from "../utils"; -import { program, programID } from './constants'; +import { program, programID } from "./constants"; async function main() { - const [vaultPDA, _bump] = anchor.web3.PublicKey.findProgramAddressSync([Buffer.from('cNFT-vault', 'utf8')], programID); + const [vaultPDA, _bump] = anchor.web3.PublicKey.findProgramAddressSync( + [Buffer.from("cNFT-vault", "utf8")], + programID, + ); - const tree = new anchor.web3.PublicKey('trezdkTFPKyj4gE9LAJYPpxn8AYVCvM7Mc4JkTb9X5B'); + const tree = new anchor.web3.PublicKey("trezdkTFPKyj4gE9LAJYPpxn8AYVCvM7Mc4JkTb9X5B"); - const receiver = new anchor.web3.PublicKey('Andys9wuoMdUeRiZLgRS5aJwYNFv4Ut6qQi8PNDTAPEM'); + const receiver = new anchor.web3.PublicKey("Andys9wuoMdUeRiZLgRS5aJwYNFv4Ut6qQi8PNDTAPEM"); const [treeAuthority, _bump2] = anchor.web3.PublicKey.findProgramAddressSync([tree.toBuffer()], BUBBLEGUM_PROGRAM_ID); - const assetId = 'DGWU3mHenDerCvjkeDsKYEbsvXbWvqdo1bVoXy3dkeTd'; + const assetId = "DGWU3mHenDerCvjkeDsKYEbsvXbWvqdo1bVoXy3dkeTd"; const asset = await getAsset(assetId); // console.log(res) diff --git a/compression/cnft-vault/anchor/tests/scripts/withdrawTwo.ts b/compression/cnft-vault/anchor/tests/scripts/withdrawTwo.ts index 65785c658..e8f06cf2f 100644 --- a/compression/cnft-vault/anchor/tests/scripts/withdrawTwo.ts +++ b/compression/cnft-vault/anchor/tests/scripts/withdrawTwo.ts @@ -1,28 +1,37 @@ -import * as anchor from '@anchor-lang/core'; -import { PROGRAM_ID as BUBBLEGUM_PROGRAM_ID } from '@metaplex-foundation/mpl-bubblegum'; -import { SPL_ACCOUNT_COMPRESSION_PROGRAM_ID, SPL_NOOP_PROGRAM_ID } from '@solana/spl-account-compression'; -import type { AccountMeta } from '@solana/web3.js'; -import { getAsset, getAssetProof } from '../readAPI'; -import { decode, mapProof } from '../utils'; +import * as anchor from "@anchor-lang/core"; +import { PROGRAM_ID as BUBBLEGUM_PROGRAM_ID } from "@metaplex-foundation/mpl-bubblegum"; +import { SPL_ACCOUNT_COMPRESSION_PROGRAM_ID, SPL_NOOP_PROGRAM_ID } from "@solana/spl-account-compression"; +import type { AccountMeta } from "@solana/web3.js"; +import { getAsset, getAssetProof } from "../readAPI"; +import { decode, mapProof } from "../utils"; -import { program, programID } from './constants'; +import { program, programID } from "./constants"; async function main() { // TODO change all of these to your values - const assetId1 = 'DGWU3mHenDerCvjkeDsKYEbsvXbWvqdo1bVoXy3dkeTd'; - const assetId2 = '14JojSTdBZvP7f77rCxB3oQK78skTVD6DiXrXUL4objg'; //"D2CoMLCRfsfv1EAiNbaBHfoU1Sqf1964KXLGxEfyUwWo"; + const assetId1 = "DGWU3mHenDerCvjkeDsKYEbsvXbWvqdo1bVoXy3dkeTd"; + const assetId2 = "14JojSTdBZvP7f77rCxB3oQK78skTVD6DiXrXUL4objg"; //"D2CoMLCRfsfv1EAiNbaBHfoU1Sqf1964KXLGxEfyUwWo"; - const tree1 = new anchor.web3.PublicKey('trezdkTFPKyj4gE9LAJYPpxn8AYVCvM7Mc4JkTb9X5B'); - const tree2 = new anchor.web3.PublicKey('Feywkti8LLBLfxhSGmYgzUBqpq89qehfB1SMTYV1zCu'); + const tree1 = new anchor.web3.PublicKey("trezdkTFPKyj4gE9LAJYPpxn8AYVCvM7Mc4JkTb9X5B"); + const tree2 = new anchor.web3.PublicKey("Feywkti8LLBLfxhSGmYgzUBqpq89qehfB1SMTYV1zCu"); - const receiver1 = new anchor.web3.PublicKey('Andys9wuoMdUeRiZLgRS5aJwYNFv4Ut6qQi8PNDTAPEM'); - const receiver2 = new anchor.web3.PublicKey('Andys9wuoMdUeRiZLgRS5aJwYNFv4Ut6qQi8PNDTAPEM'); + const receiver1 = new anchor.web3.PublicKey("Andys9wuoMdUeRiZLgRS5aJwYNFv4Ut6qQi8PNDTAPEM"); + const receiver2 = new anchor.web3.PublicKey("Andys9wuoMdUeRiZLgRS5aJwYNFv4Ut6qQi8PNDTAPEM"); // --- - const [vaultPDA, _bump] = anchor.web3.PublicKey.findProgramAddressSync([Buffer.from('cNFT-vault', 'utf8')], programID); + const [vaultPDA, _bump] = anchor.web3.PublicKey.findProgramAddressSync( + [Buffer.from("cNFT-vault", "utf8")], + programID, + ); - const [treeAuthority1, _bump2] = anchor.web3.PublicKey.findProgramAddressSync([tree1.toBuffer()], BUBBLEGUM_PROGRAM_ID); - const [treeAuthority2, _bump3] = anchor.web3.PublicKey.findProgramAddressSync([tree2.toBuffer()], BUBBLEGUM_PROGRAM_ID); + const [treeAuthority1, _bump2] = anchor.web3.PublicKey.findProgramAddressSync( + [tree1.toBuffer()], + BUBBLEGUM_PROGRAM_ID, + ); + const [treeAuthority2, _bump3] = anchor.web3.PublicKey.findProgramAddressSync( + [tree2.toBuffer()], + BUBBLEGUM_PROGRAM_ID, + ); const asset1 = await getAsset(assetId1); const asset2 = await getAsset(assetId2); @@ -57,6 +66,7 @@ async function main() { console.log(tx); } +// biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 function getInstructionData(asset: any, proof: any): [number[], number[], number[], anchor.BN, number, number] { const root = decode(proof.root); const dataHash = decode(asset.compression.data_hash); diff --git a/compression/cnft-vault/anchor/tests/scripts/withdrawWithLookup.ts b/compression/cnft-vault/anchor/tests/scripts/withdrawWithLookup.ts index 20cf63fc4..f3f45097b 100644 --- a/compression/cnft-vault/anchor/tests/scripts/withdrawWithLookup.ts +++ b/compression/cnft-vault/anchor/tests/scripts/withdrawWithLookup.ts @@ -1,6 +1,6 @@ -import * as anchor from '@anchor-lang/core'; -import { PROGRAM_ID as BUBBLEGUM_PROGRAM_ID } from '@metaplex-foundation/mpl-bubblegum'; -import { SPL_ACCOUNT_COMPRESSION_PROGRAM_ID, SPL_NOOP_PROGRAM_ID } from '@solana/spl-account-compression'; +import * as anchor from "@anchor-lang/core"; +import { PROGRAM_ID as BUBBLEGUM_PROGRAM_ID } from "@metaplex-foundation/mpl-bubblegum"; +import { SPL_ACCOUNT_COMPRESSION_PROGRAM_ID, SPL_NOOP_PROGRAM_ID } from "@solana/spl-account-compression"; import { type AccountMeta, AddressLookupTableProgram, @@ -10,30 +10,39 @@ import { Transaction, TransactionMessage, VersionedTransaction, -} from '@solana/web3.js'; -import { getAsset, getAssetProof } from '../readAPI'; -import { decode, mapProof } from '../utils'; +} from "@solana/web3.js"; +import { getAsset, getAssetProof } from "../readAPI"; +import { decode, mapProof } from "../utils"; -import { connection, keypair, program, programID } from './constants'; +import { connection, keypair, program, programID } from "./constants"; async function main() { // TODO change all of these to your values - const assetId1 = 'DGWU3mHenDerCvjkeDsKYEbsvXbWvqdo1bVoXy3dkeTd'; - const assetId2 = '14JojSTdBZvP7f77rCxB3oQK78skTVD6DiXrXUL4objg'; //"D2CoMLCRfsfv1EAiNbaBHfoU1Sqf1964KXLGxEfyUwWo"; + const assetId1 = "DGWU3mHenDerCvjkeDsKYEbsvXbWvqdo1bVoXy3dkeTd"; + const assetId2 = "14JojSTdBZvP7f77rCxB3oQK78skTVD6DiXrXUL4objg"; //"D2CoMLCRfsfv1EAiNbaBHfoU1Sqf1964KXLGxEfyUwWo"; - const tree1 = new anchor.web3.PublicKey('trezdkTFPKyj4gE9LAJYPpxn8AYVCvM7Mc4JkTb9X5B'); - const tree2 = new anchor.web3.PublicKey('trezdkTFPKyj4gE9LAJYPpxn8AYVCvM7Mc4JkTb9X5B'); + const tree1 = new anchor.web3.PublicKey("trezdkTFPKyj4gE9LAJYPpxn8AYVCvM7Mc4JkTb9X5B"); + const tree2 = new anchor.web3.PublicKey("trezdkTFPKyj4gE9LAJYPpxn8AYVCvM7Mc4JkTb9X5B"); - const receiver1 = new anchor.web3.PublicKey('Andys9wuoMdUeRiZLgRS5aJwYNFv4Ut6qQi8PNDTAPEM'); - const receiver2 = new anchor.web3.PublicKey('Andys9wuoMdUeRiZLgRS5aJwYNFv4Ut6qQi8PNDTAPEM'); + const receiver1 = new anchor.web3.PublicKey("Andys9wuoMdUeRiZLgRS5aJwYNFv4Ut6qQi8PNDTAPEM"); + const receiver2 = new anchor.web3.PublicKey("Andys9wuoMdUeRiZLgRS5aJwYNFv4Ut6qQi8PNDTAPEM"); // --- const lookupTable = await createLookupTable(); - const [vaultPDA, _bump] = anchor.web3.PublicKey.findProgramAddressSync([Buffer.from('cNFT-vault', 'utf8')], programID); + const [vaultPDA, _bump] = anchor.web3.PublicKey.findProgramAddressSync( + [Buffer.from("cNFT-vault", "utf8")], + programID, + ); - const [treeAuthority1, _bump2] = anchor.web3.PublicKey.findProgramAddressSync([tree1.toBuffer()], BUBBLEGUM_PROGRAM_ID); - const [treeAuthority2, _bump3] = anchor.web3.PublicKey.findProgramAddressSync([tree2.toBuffer()], BUBBLEGUM_PROGRAM_ID); + const [treeAuthority1, _bump2] = anchor.web3.PublicKey.findProgramAddressSync( + [tree1.toBuffer()], + BUBBLEGUM_PROGRAM_ID, + ); + const [treeAuthority2, _bump3] = anchor.web3.PublicKey.findProgramAddressSync( + [tree2.toBuffer()], + BUBBLEGUM_PROGRAM_ID, + ); const asset1 = await getAsset(assetId1); const asset2 = await getAsset(assetId2); @@ -78,7 +87,7 @@ async function main() { const lookupTableAccount = await connection.getAddressLookupTable(lookupTable).then((res) => res.value); if (!lookupTableAccount) { - console.log('could not fetch ATL!'); + console.log("could not fetch ATL!"); return; } @@ -97,6 +106,7 @@ async function main() { console.log(txid); } +// biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 function getInstructionData(asset: any, proof: any): [number[], number[], number[], anchor.BN, number, number] { const root = decode(proof.root); const dataHash = decode(asset.compression.data_hash); @@ -121,10 +131,10 @@ async function extendLookupTable(lookupTableAddress: PublicKey, proofHashes: Pub tx.add(extendInstruction); const sx = await sendAndConfirmTransaction(connection, tx, [keypair], { - commitment: 'finalized', + commitment: "finalized", }); console.log(sx); - console.log('ALT extended!'); + console.log("ALT extended!"); } async function createLookupTable(): Promise { @@ -155,10 +165,10 @@ async function createLookupTable(): Promise { tx.add(lookupTableInst).add(extendInstruction); const sx = await sendAndConfirmTransaction(connection, tx, [keypair], { - commitment: 'finalized', + commitment: "finalized", }); console.log(sx); - console.log('ALT created'); + console.log("ALT created"); return lookupTableAddress; } diff --git a/compression/cnft-vault/anchor/tests/tests.ts b/compression/cnft-vault/anchor/tests/tests.ts index 28031d448..b378ecbbe 100644 --- a/compression/cnft-vault/anchor/tests/tests.ts +++ b/compression/cnft-vault/anchor/tests/tests.ts @@ -1,31 +1,37 @@ -import * as anchor from '@anchor-lang/core'; -import { PROGRAM_ID as BUBBLEGUM_PROGRAM_ID } from '@metaplex-foundation/mpl-bubblegum'; -import { SPL_ACCOUNT_COMPRESSION_PROGRAM_ID, SPL_NOOP_PROGRAM_ID } from '@solana/spl-account-compression'; -import type { AccountMeta } from '@solana/web3.js'; -import { type CnftVault } from '../target/types/cnft_vault'; -import { getAsset, getAssetProof } from './readAPI'; -import { decode, mapProof } from './utils'; - -describe('cNFT Vault', () => { +import * as anchor from "@anchor-lang/core"; +import { PROGRAM_ID as BUBBLEGUM_PROGRAM_ID } from "@metaplex-foundation/mpl-bubblegum"; +import { SPL_ACCOUNT_COMPRESSION_PROGRAM_ID, SPL_NOOP_PROGRAM_ID } from "@solana/spl-account-compression"; +import type { AccountMeta } from "@solana/web3.js"; +import type { CnftVault } from "../target/types/cnft_vault"; +import { getAsset, getAssetProof } from "./readAPI"; +import { decode, mapProof } from "./utils"; + +describe("cNFT Vault", () => { const provider = anchor.AnchorProvider.env(); anchor.setProvider(provider); const payer = provider.wallet as anchor.Wallet; const program = anchor.workspace.CnftVault as anchor.Program; - const [vaultPDA, _bump] = anchor.web3.PublicKey.findProgramAddressSync([Buffer.from('cNFT-vault', 'utf8')], program.programId); + const [vaultPDA, _bump] = anchor.web3.PublicKey.findProgramAddressSync( + [Buffer.from("cNFT-vault", "utf8")], + program.programId, + ); console.log(`Vault address: ${vaultPDA.toBase58()}`); - it('Withdraw a cNFT!', async () => { + it("Withdraw a cNFT!", async () => { // we expect the cNFT to already be in the vault // you can send it there (to vaultPDA) using any regular wallet // the cNFT has the following asset id - const assetId = 'DGWU3mHenDerCvjkeDsKYEbsvXbWvqdo1bVoXy3dkeTd'; // TODO + const assetId = "DGWU3mHenDerCvjkeDsKYEbsvXbWvqdo1bVoXy3dkeTd"; // TODO // and is compressed in the following tree - const tree = new anchor.web3.PublicKey('trezdkTFPKyj4gE9LAJYPpxn8AYVCvM7Mc4JkTb9X5B'); // TODO + const tree = new anchor.web3.PublicKey("trezdkTFPKyj4gE9LAJYPpxn8AYVCvM7Mc4JkTb9X5B"); // TODO const receiver = payer.publicKey; // you can define any pubkey as the receiver here - const [treeAuthority, _bump2] = anchor.web3.PublicKey.findProgramAddressSync([tree.toBuffer()], BUBBLEGUM_PROGRAM_ID); + const [treeAuthority, _bump2] = anchor.web3.PublicKey.findProgramAddressSync( + [tree.toBuffer()], + BUBBLEGUM_PROGRAM_ID, + ); const asset = await getAsset(assetId); @@ -53,24 +59,30 @@ describe('cNFT Vault', () => { .remainingAccounts(proofPathAsAccounts) .rpc(); - console.log('Success!'); + console.log("Success!"); console.log(` Tx Signature: ${sx}`); }); - it('Withdraw two cNFTs!', async () => { + it("Withdraw two cNFTs!", async () => { // TODO change all of these to your values - const assetId1 = 'DGWU3mHenDerCvjkeDsKYEbsvXbWvqdo1bVoXy3dkeTd'; - const assetId2 = '14JojSTdBZvP7f77rCxB3oQK78skTVD6DiXrXUL4objg'; + const assetId1 = "DGWU3mHenDerCvjkeDsKYEbsvXbWvqdo1bVoXy3dkeTd"; + const assetId2 = "14JojSTdBZvP7f77rCxB3oQK78skTVD6DiXrXUL4objg"; - const tree1 = new anchor.web3.PublicKey('trezdkTFPKyj4gE9LAJYPpxn8AYVCvM7Mc4JkTb9X5B'); - const tree2 = new anchor.web3.PublicKey('Feywkti8LLBLfxhSGmYgzUBqpq89qehfB1SMTYV1zCu'); + const tree1 = new anchor.web3.PublicKey("trezdkTFPKyj4gE9LAJYPpxn8AYVCvM7Mc4JkTb9X5B"); + const tree2 = new anchor.web3.PublicKey("Feywkti8LLBLfxhSGmYgzUBqpq89qehfB1SMTYV1zCu"); - const receiver1 = new anchor.web3.PublicKey('Andys9wuoMdUeRiZLgRS5aJwYNFv4Ut6qQi8PNDTAPEM'); - const receiver2 = new anchor.web3.PublicKey('Andys9wuoMdUeRiZLgRS5aJwYNFv4Ut6qQi8PNDTAPEM'); + const receiver1 = new anchor.web3.PublicKey("Andys9wuoMdUeRiZLgRS5aJwYNFv4Ut6qQi8PNDTAPEM"); + const receiver2 = new anchor.web3.PublicKey("Andys9wuoMdUeRiZLgRS5aJwYNFv4Ut6qQi8PNDTAPEM"); // --- - const [treeAuthority1, _bump2] = anchor.web3.PublicKey.findProgramAddressSync([tree1.toBuffer()], BUBBLEGUM_PROGRAM_ID); - const [treeAuthority2, _bump3] = anchor.web3.PublicKey.findProgramAddressSync([tree2.toBuffer()], BUBBLEGUM_PROGRAM_ID); + const [treeAuthority1, _bump2] = anchor.web3.PublicKey.findProgramAddressSync( + [tree1.toBuffer()], + BUBBLEGUM_PROGRAM_ID, + ); + const [treeAuthority2, _bump3] = anchor.web3.PublicKey.findProgramAddressSync( + [tree2.toBuffer()], + BUBBLEGUM_PROGRAM_ID, + ); const asset1 = await getAsset(assetId1); const asset2 = await getAsset(assetId2); @@ -102,11 +114,12 @@ describe('cNFT Vault', () => { }) .remainingAccounts(remainingAccounts) .rpc(); - console.log('Success!'); + console.log("Success!"); console.log(` Tx Signature: ${sx}`); }); }); +// biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 function getInstructionData(asset: any, proof: any): [number[], number[], number[], anchor.BN, number, number] { const root = decode(proof.root); const dataHash = decode(asset.compression.data_hash); diff --git a/compression/cnft-vault/anchor/tests/utils.ts b/compression/cnft-vault/anchor/tests/utils.ts index 43759dd36..70aa141d9 100644 --- a/compression/cnft-vault/anchor/tests/utils.ts +++ b/compression/cnft-vault/anchor/tests/utils.ts @@ -1,9 +1,9 @@ -import { type AccountMeta, Keypair, PublicKey } from '@solana/web3.js'; +import { type AccountMeta, Keypair, PublicKey } from "@solana/web3.js"; -import * as bs58 from 'bs58'; +import * as bs58 from "bs58"; export function loadWalletKey(keypairFile: string): Keypair { - const fs = require('node:fs'); + const fs = require("node:fs"); return Keypair.fromSecretKey(new Uint8Array(JSON.parse(fs.readFileSync(keypairFile).toString()))); } @@ -19,7 +19,7 @@ function bufferToArray(buffer: Buffer): number[] { } export const mapProof = (assetProof: { proof: string[] }): AccountMeta[] => { if (!assetProof.proof || assetProof.proof.length === 0) { - throw new Error('Proof is empty'); + throw new Error("Proof is empty"); } return assetProof.proof.map((node) => ({ pubkey: new PublicKey(node), diff --git a/compression/cutils/anchor/package.json b/compression/cutils/anchor/package.json index d0a67bfdb..8f28e0c00 100644 --- a/compression/cutils/anchor/package.json +++ b/compression/cutils/anchor/package.json @@ -1,27 +1,27 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@metaplex-foundation/js": "^0.19.4", - "@metaplex-foundation/mpl-bubblegum": "^0.7.0", - "@solana/spl-account-compression": "^0.1.8", - "@solana/spl-token": "^0.3.8", - "@solana/web3.js": "^1.98.4", - "axios": "^1.4.0" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "ts-node": "^10.9.1", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@metaplex-foundation/js": "^0.19.4", + "@metaplex-foundation/mpl-bubblegum": "^0.7.0", + "@solana/spl-account-compression": "^0.1.8", + "@solana/spl-token": "^0.3.8", + "@solana/web3.js": "^1.98.4", + "axios": "^1.4.0" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "ts-node": "^10.9.1", + "typescript": "^5.3.3" + } } diff --git a/compression/cutils/anchor/tests/setup.ts b/compression/cutils/anchor/tests/setup.ts index d17721ff7..21b0de775 100644 --- a/compression/cutils/anchor/tests/setup.ts +++ b/compression/cutils/anchor/tests/setup.ts @@ -1,19 +1,19 @@ -import type { CreateMetadataAccountArgsV3 } from '@metaplex-foundation/mpl-token-metadata'; -import type { ValidDepthSizePair } from '@solana/spl-account-compression'; -import { Connection, Keypair } from '@solana/web3.js'; -import { createCollection, createTree } from './utils/compression'; -import { loadOrGenerateKeypair, savePublicKeyToFile } from './utils/helpers'; +import type { CreateMetadataAccountArgsV3 } from "@metaplex-foundation/mpl-token-metadata"; +import type { ValidDepthSizePair } from "@solana/spl-account-compression"; +import { Connection, Keypair } from "@solana/web3.js"; +import { createCollection, createTree } from "./utils/compression"; +import { loadOrGenerateKeypair, savePublicKeyToFile } from "./utils/helpers"; async function _setup() { - const rpc = 'https://api.devnet.solana.com'; - const connection = new Connection(rpc, 'confirmed'); + const rpc = "https://api.devnet.solana.com"; + const connection = new Connection(rpc, "confirmed"); // Collection auth and treeCreator - const payer = loadOrGenerateKeypair('payer'); + const payer = loadOrGenerateKeypair("payer"); // Airdrop await connection.requestAirdrop(payer.publicKey, 1 * 10 ** 9); - console.log('Payer address:', payer.publicKey.toBase58()); + console.log("Payer address:", payer.publicKey.toBase58()); const treeKeypair = Keypair.generate(); const maxDepthSizePair: ValidDepthSizePair = { @@ -24,14 +24,14 @@ async function _setup() { const tree = await createTree(connection, payer, treeKeypair, maxDepthSizePair, canopyDepth); // locally save the addresses for demo - savePublicKeyToFile('treeAddress', tree.treeAddress); + savePublicKeyToFile("treeAddress", tree.treeAddress); const collectionMetadataV3: CreateMetadataAccountArgsV3 = { data: { - name: 'Super Sweet NFT Collection', - symbol: 'SSNC', + name: "Super Sweet NFT Collection", + symbol: "SSNC", // specific json metadata for the collection - uri: 'https://supersweetcollection.notarealurl/collection.json', + uri: "https://supersweetcollection.notarealurl/collection.json", sellerFeeBasisPoints: 100, creators: [ { @@ -51,7 +51,7 @@ async function _setup() { const collection = await createCollection(connection, payer, collectionMetadataV3); // locally save the addresses for the demo - savePublicKeyToFile('collectionMint', collection.mint); + savePublicKeyToFile("collectionMint", collection.mint); } // setup() diff --git a/compression/cutils/anchor/tests/tests.ts b/compression/cutils/anchor/tests/tests.ts index ca62754f9..4acbea02c 100644 --- a/compression/cutils/anchor/tests/tests.ts +++ b/compression/cutils/anchor/tests/tests.ts @@ -1,10 +1,10 @@ -import * as anchor from '@anchor-lang/core'; -import { PROGRAM_ID as BUBBLEGUM_PROGRAM_ID } from '@metaplex-foundation/mpl-bubblegum/dist/src/generated'; -import type { Cutils } from '../target/types/cutils'; -import { loadOrGenerateKeypair, loadPublicKeysFromFile } from './utils/helpers'; -import { getAccounts } from './utils/utils'; +import * as anchor from "@anchor-lang/core"; +import { PROGRAM_ID as BUBBLEGUM_PROGRAM_ID } from "@metaplex-foundation/mpl-bubblegum/dist/src/generated"; +import type { Cutils } from "../target/types/cutils"; +import { loadOrGenerateKeypair, loadPublicKeysFromFile } from "./utils/helpers"; +import { getAccounts } from "./utils/utils"; -describe('cutils', () => { +describe("cutils", () => { const provider = anchor.AnchorProvider.env(); anchor.setProvider(provider); @@ -12,16 +12,16 @@ describe('cutils', () => { // NFT metadata pointer // TODO change - const uri = 'https://arweave.net/nVRvZDaOk5YAdr4ZBEeMjOVhynuv8P3vywvuN5sYSPo'; + const uri = "https://arweave.net/nVRvZDaOk5YAdr4ZBEeMjOVhynuv8P3vywvuN5sYSPo"; - const payer = loadOrGenerateKeypair('payer'); + const payer = loadOrGenerateKeypair("payer"); // cNFT receiver - const testWallet = loadOrGenerateKeypair('testWallet'); + const testWallet = loadOrGenerateKeypair("testWallet"); const { collectionMint, treeAddress } = loadPublicKeysFromFile(); - it('Mint!', async () => { + it("Mint!", async () => { const tx = await program.methods .mint({ uri }) .accounts({ diff --git a/compression/cutils/anchor/tests/utils/compression.ts b/compression/cutils/anchor/tests/utils/compression.ts index 87c710718..77eff4022 100644 --- a/compression/cutils/anchor/tests/utils/compression.ts +++ b/compression/cutils/anchor/tests/utils/compression.ts @@ -5,20 +5,32 @@ import { createCreateTreeInstruction, createMintToCollectionV1Instruction, type MetadataArgs, -} from '@metaplex-foundation/mpl-bubblegum'; +} from "@metaplex-foundation/mpl-bubblegum"; import { type CreateMetadataAccountArgsV3, createCreateMasterEditionV3Instruction, createCreateMetadataAccountV3Instruction, createSetCollectionSizeInstruction, PROGRAM_ID as TOKEN_METADATA_PROGRAM_ID, -} from '@metaplex-foundation/mpl-token-metadata'; -import { createAllocTreeIx, SPL_ACCOUNT_COMPRESSION_PROGRAM_ID, SPL_NOOP_PROGRAM_ID, type ValidDepthSizePair } from '@solana/spl-account-compression'; -import { createAccount, createMint, mintTo, TOKEN_PROGRAM_ID } from '@solana/spl-token'; -import { type Connection, type Keypair, PublicKey, sendAndConfirmTransaction, Transaction, type TransactionInstruction } from '@solana/web3.js'; +} from "@metaplex-foundation/mpl-token-metadata"; +import { + createAllocTreeIx, + SPL_ACCOUNT_COMPRESSION_PROGRAM_ID, + SPL_NOOP_PROGRAM_ID, + type ValidDepthSizePair, +} from "@solana/spl-account-compression"; +import { createAccount, createMint, mintTo, TOKEN_PROGRAM_ID } from "@solana/spl-token"; +import { + type Connection, + type Keypair, + PublicKey, + sendAndConfirmTransaction, + Transaction, + type TransactionInstruction, +} from "@solana/web3.js"; // import local helper functions -import { explorerURL, extractSignatureFromFailedTransaction } from './helpers'; +import { explorerURL, extractSignatureFromFailedTransaction } from "./helpers"; /* Helper function to create a merkle tree on chain, including allocating @@ -31,16 +43,25 @@ export async function createTree( maxDepthSizePair: ValidDepthSizePair, canopyDepth = 0, ) { - console.log('Creating a new Merkle tree...'); - console.log('treeAddress:', treeKeypair.publicKey.toBase58()); + console.log("Creating a new Merkle tree..."); + console.log("treeAddress:", treeKeypair.publicKey.toBase58()); // derive the tree's authority (PDA), owned by Bubblegum - const [treeAuthority, _bump] = PublicKey.findProgramAddressSync([treeKeypair.publicKey.toBuffer()], BUBBLEGUM_PROGRAM_ID); - console.log('treeAuthority:', treeAuthority.toBase58()); + const [treeAuthority, _bump] = PublicKey.findProgramAddressSync( + [treeKeypair.publicKey.toBuffer()], + BUBBLEGUM_PROGRAM_ID, + ); + console.log("treeAuthority:", treeAuthority.toBase58()); // allocate the tree's account on chain with the `space` // NOTE: this will compute the space needed to store the tree on chain (and the lamports required to store it) - const allocTreeIx = await createAllocTreeIx(connection, treeKeypair.publicKey, payer.publicKey, maxDepthSizePair, canopyDepth); + const allocTreeIx = await createAllocTreeIx( + connection, + treeKeypair.publicKey, + payer.publicKey, + maxDepthSizePair, + canopyDepth, + ); // create the instruction to actually create the tree const createTreeIx = createCreateTreeInstruction( @@ -65,7 +86,7 @@ export async function createTree( // create and send the transaction to initialize the tree const tx = new Transaction().add(allocTreeIx).add(createTreeIx); tx.feePayer = payer.publicKey; - console.log('tx'); + console.log("tx"); // send the transaction const txSignature = await sendAndConfirmTransaction( @@ -74,18 +95,19 @@ export async function createTree( // ensuring the `treeKeypair` PDA and the `payer` are BOTH signers [treeKeypair, payer], { - commitment: 'confirmed', + commitment: "confirmed", skipPreflight: true, }, ); - console.log('\nMerkle tree created successfully!'); + console.log("\nMerkle tree created successfully!"); console.log(explorerURL({ txSignature })); // return useful info return { treeAuthority, treeAddress: treeKeypair.publicKey }; + // biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 } catch (err: any) { - console.error('\nFailed to create merkle tree:', err); + console.error("\nFailed to create merkle tree:", err); // log a block explorer link for the failed transaction await extractSignatureFromFailedTransaction(connection, err); @@ -98,7 +120,11 @@ export async function createTree( * Create an NFT collection on-chain, using the regular Metaplex standards * with the `payer` as the authority */ -export async function createCollection(connection: Connection, payer: Keypair, metadataV3: CreateMetadataAccountArgsV3) { +export async function createCollection( + connection: Connection, + payer: Keypair, + metadataV3: CreateMetadataAccountArgsV3, +) { // create and initialize the SPL token mint console.log("Creating the collection's mint..."); const mint = await createMint( @@ -111,10 +137,10 @@ export async function createCollection(connection: Connection, payer: Keypair, m // decimals - use `0` for NFTs since they are non-fungible 0, ); - console.log('Mint address:', mint.toBase58()); + console.log("Mint address:", mint.toBase58()); // create the token account - console.log('Creating a token account...'); + console.log("Creating a token account..."); const tokenAccount = await createAccount( connection, payer, @@ -122,10 +148,10 @@ export async function createCollection(connection: Connection, payer: Keypair, m payer.publicKey, // undefined, undefined, ); - console.log('Token account:', tokenAccount.toBase58()); + console.log("Token account:", tokenAccount.toBase58()); // mint 1 token () - console.log('Minting 1 token for the collection...'); + console.log("Minting 1 token for the collection..."); const _mintSig = await mintTo( connection, payer, @@ -143,10 +169,10 @@ export async function createCollection(connection: Connection, payer: Keypair, m // derive the PDA for the metadata account const [metadataAccount, _bump] = PublicKey.findProgramAddressSync( - [Buffer.from('metadata', 'utf8'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mint.toBuffer()], + [Buffer.from("metadata", "utf8"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mint.toBuffer()], TOKEN_METADATA_PROGRAM_ID, ); - console.log('Metadata account:', metadataAccount.toBase58()); + console.log("Metadata account:", metadataAccount.toBase58()); // create an instruction to create the metadata account const createMetadataIx = createCreateMetadataAccountV3Instruction( @@ -164,10 +190,15 @@ export async function createCollection(connection: Connection, payer: Keypair, m // derive the PDA for the metadata account const [masterEditionAccount, _bump2] = PublicKey.findProgramAddressSync( - [Buffer.from('metadata', 'utf8'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mint.toBuffer(), Buffer.from('edition', 'utf8')], + [ + Buffer.from("metadata", "utf8"), + TOKEN_METADATA_PROGRAM_ID.toBuffer(), + mint.toBuffer(), + Buffer.from("edition", "utf8"), + ], TOKEN_METADATA_PROGRAM_ID, ); - console.log('Master edition account:', masterEditionAccount.toBase58()); + console.log("Master edition account:", masterEditionAccount.toBase58()); // create an instruction to create the metadata account const createMasterEditionIx = createCreateMasterEditionV3Instruction( @@ -205,14 +236,14 @@ export async function createCollection(connection: Connection, payer: Keypair, m // send the transaction to the cluster const txSignature = await sendAndConfirmTransaction(connection, tx, [payer], { - commitment: 'confirmed', + commitment: "confirmed", skipPreflight: true, }); - console.log('\nCollection successfully created!'); + console.log("\nCollection successfully created!"); console.log(explorerURL({ txSignature })); } catch (err) { - console.error('\nFailed to create collection:', err); + console.error("\nFailed to create collection:", err); // log a block explorer link for the failed transaction await extractSignatureFromFailedTransaction(connection, err); @@ -243,7 +274,7 @@ export async function mintCompressedNFT( // derive a PDA (owned by Bubblegum) to act as the signer of the compressed minting const [bubblegumSigner, _bump2] = PublicKey.findProgramAddressSync( // `collection_cpi` is a custom prefix required by the Bubblegum program - [Buffer.from('collection_cpi', 'utf8')], + [Buffer.from("collection_cpi", "utf8")], BUBBLEGUM_PROGRAM_ID, ); @@ -270,8 +301,8 @@ export async function mintCompressedNFT( */ const computedDataHash = new PublicKey(computeDataHash(metadataArgs)).toBase58(); const computedCreatorHash = new PublicKey(computeCreatorHash(metadataArgs.creators)).toBase58(); - console.log('computedDataHash:', computedDataHash); - console.log('computedCreatorHash:', computedCreatorHash); + console.log("computedDataHash:", computedDataHash); + console.log("computedCreatorHash:", computedCreatorHash); /* Add a single mint to collection instruction @@ -327,16 +358,16 @@ export async function mintCompressedNFT( // send the transaction to the cluster const txSignature = await sendAndConfirmTransaction(connection, tx, [payer], { - commitment: 'confirmed', + commitment: "confirmed", skipPreflight: true, }); - console.log('\nSuccessfully minted the compressed NFT!'); + console.log("\nSuccessfully minted the compressed NFT!"); console.log(explorerURL({ txSignature })); return txSignature; } catch (err) { - console.error('\nFailed to mint compressed NFT:', err); + console.error("\nFailed to mint compressed NFT:", err); // log a block explorer link for the failed transaction await extractSignatureFromFailedTransaction(connection, err); diff --git a/compression/cutils/anchor/tests/utils/helpers.ts b/compression/cutils/anchor/tests/utils/helpers.ts index ffe3ad8c4..a793000c9 100644 --- a/compression/cutils/anchor/tests/utils/helpers.ts +++ b/compression/cutils/anchor/tests/utils/helpers.ts @@ -1,26 +1,26 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { type Connection, Keypair, LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js'; +import fs from "node:fs"; +import path from "node:path"; +import { type Connection, Keypair, LAMPORTS_PER_SOL, PublicKey } from "@solana/web3.js"; // define some default locations -const DEFAULT_KEY_DIR_NAME = '.local_keys'; -const DEFAULT_PUBLIC_KEY_FILE = 'keys.json'; -const DEFAULT_DEMO_DATA_FILE = 'demo.json'; +const DEFAULT_KEY_DIR_NAME = ".local_keys"; +const DEFAULT_PUBLIC_KEY_FILE = "keys.json"; +const DEFAULT_DEMO_DATA_FILE = "demo.json"; /* Load locally stored PublicKey addresses */ export function loadPublicKeysFromFile(absPath = `${DEFAULT_KEY_DIR_NAME}/${DEFAULT_PUBLIC_KEY_FILE}`) { try { - if (!absPath) throw Error('No path provided'); - if (!fs.existsSync(absPath)) throw Error('File does not exist.'); + if (!absPath) throw Error("No path provided"); + if (!fs.existsSync(absPath)) throw Error("File does not exist."); // load the public keys from the file - const data = JSON.parse(fs.readFileSync(absPath, { encoding: 'utf-8' })) || {}; + const data = JSON.parse(fs.readFileSync(absPath, { encoding: "utf-8" })) || {}; // convert all loaded keyed values into valid public keys for (const [key, value] of Object.entries(data)) { - data[key] = new PublicKey(value as string) ?? ''; + data[key] = new PublicKey(value as string) ?? ""; } return data; @@ -34,23 +34,28 @@ export function loadPublicKeysFromFile(absPath = `${DEFAULT_KEY_DIR_NAME}/${DEFA /* Locally save a demo data to the filesystem for later retrieval */ -export function saveDemoDataToFile(name: string, newData: any, absPath = `${DEFAULT_KEY_DIR_NAME}/${DEFAULT_DEMO_DATA_FILE}`) { +export function saveDemoDataToFile( + name: string, + // biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 + newData: any, + absPath = `${DEFAULT_KEY_DIR_NAME}/${DEFAULT_DEMO_DATA_FILE}`, +) { try { let data: object = {}; // fetch all the current values, when the storage file exists - if (fs.existsSync(absPath)) data = JSON.parse(fs.readFileSync(absPath, { encoding: 'utf-8' })) || {}; + if (fs.existsSync(absPath)) data = JSON.parse(fs.readFileSync(absPath, { encoding: "utf-8" })) || {}; data = { ...data, [name]: newData }; // actually save the data to the file fs.writeFileSync(absPath, JSON.stringify(data), { - encoding: 'utf-8', + encoding: "utf-8", }); return data; } catch (_err) { - console.warn('Unable to save to file'); + console.warn("Unable to save to file"); // console.warn(err); } @@ -61,23 +66,29 @@ export function saveDemoDataToFile(name: string, newData: any, absPath = `${DEFA /* Locally save a PublicKey addresses to the filesystem for later retrieval */ -export function savePublicKeyToFile(name: string, publicKey: PublicKey, absPath = `${DEFAULT_KEY_DIR_NAME}/${DEFAULT_PUBLIC_KEY_FILE}`) { +export function savePublicKeyToFile( + name: string, + publicKey: PublicKey, + absPath = `${DEFAULT_KEY_DIR_NAME}/${DEFAULT_PUBLIC_KEY_FILE}`, +) { try { // if (!absPath) throw Error("No path provided"); // if (!fs.existsSync(absPath)) throw Error("File does not exist."); // fetch all the current values + // biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 let data: any = loadPublicKeysFromFile(absPath); // convert all loaded keyed values from PublicKeys to strings for (const [key, value] of Object.entries(data)) { + // biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 data[key as any] = (value as PublicKey).toBase58(); } data = { ...data, [name]: publicKey.toBase58() }; // actually save the data to the file fs.writeFileSync(absPath, JSON.stringify(data), { - encoding: 'utf-8', + encoding: "utf-8", }); // reload the keys for sanity @@ -85,7 +96,7 @@ export function savePublicKeyToFile(name: string, publicKey: PublicKey, absPath return data; } catch (_err) { - console.warn('Unable to save to file'); + console.warn("Unable to save to file"); } // always return an object return {}; @@ -96,16 +107,16 @@ export function savePublicKeyToFile(name: string, publicKey: PublicKey, absPath */ export function loadKeypairFromFile(absPath: string) { try { - if (!absPath) throw Error('No path provided'); - if (!fs.existsSync(absPath)) throw Error('File does not exist.'); + if (!absPath) throw Error("No path provided"); + if (!fs.existsSync(absPath)) throw Error("File does not exist."); // load the keypair from the file - const keyfileBytes = JSON.parse(fs.readFileSync(absPath, { encoding: 'utf-8' })); + const keyfileBytes = JSON.parse(fs.readFileSync(absPath, { encoding: "utf-8" })); // parse the loaded secretKey into a valid keypair const keypair = Keypair.fromSecretKey(new Uint8Array(keyfileBytes)); return keypair; } catch (err) { - console.error('loadKeypairFromFile:', err); + console.error("loadKeypairFromFile:", err); throw err; } } @@ -125,7 +136,7 @@ export function saveKeypairToFile(keypair: Keypair, relativeFileName: string, di // write the `secretKey` value as a string fs.writeFileSync(fileName, `[${keypair.secretKey.toString()}]`, { - encoding: 'utf-8', + encoding: "utf-8", }); return fileName; @@ -147,7 +158,7 @@ export function loadOrGenerateKeypair(fileName: string, dirName: string = DEFAUL return keypair; } catch (err) { - console.error('loadOrGenerateKeypair:', err); + console.error("loadOrGenerateKeypair:", err); throw err; } } @@ -162,17 +173,17 @@ export function explorerURL({ }: { address?: string; txSignature?: string; - cluster?: 'devnet' | 'testnet' | 'mainnet' | 'mainnet-beta'; + cluster?: "devnet" | "testnet" | "mainnet" | "mainnet-beta"; }) { let baseUrl: string; // if (address) baseUrl = `https://explorer.solana.com/address/${address}`; else if (txSignature) baseUrl = `https://explorer.solana.com/tx/${txSignature}`; - else return '[unknown]'; + else return "[unknown]"; // auto append the desired search params const url = new URL(baseUrl); - url.searchParams.append('cluster', cluster || 'devnet'); + url.searchParams.append("cluster", cluster || "devnet"); return `${url.toString()}\n`; } @@ -190,7 +201,7 @@ export async function airdropOnLowBalance(connection: Connection, keypair: Keypa if (forceAirdrop === true || balance < MIN_BALANCE_TO_AIRDROP) { console.log(`Requesting airdrop of 1 SOL to ${keypair.publicKey.toBase58()}...`); await connection.requestAirdrop(keypair.publicKey, LAMPORTS_PER_SOL).then((sig) => { - console.log('Tx signature:', sig); + console.log("Tx signature:", sig); // balance = balance + LAMPORTS_PER_SOL; }); @@ -206,11 +217,14 @@ export async function airdropOnLowBalance(connection: Connection, keypair: Keypa /* Helper function to extract a transaction signature from a failed transaction's error message */ +// biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 export async function extractSignatureFromFailedTransaction(connection: Connection, err: any, fetchLogs?: boolean) { if (err?.signature) return err.signature; // extract the failed transaction's signature - const failedSig = new RegExp(/^((.*)?Error: )?(Transaction|Signature) ([A-Z0-9]{32,}) /gim).exec(err?.message?.toString())?.[4]; + const failedSig = new RegExp(/^((.*)?Error: )?(Transaction|Signature) ([A-Z0-9]{32,}) /gim).exec( + err?.message?.toString(), + )?.[4]; // ensure a signature was found if (failedSig) { @@ -222,14 +236,14 @@ export async function extractSignatureFromFailedTransaction(connection: Connecti }) .then((tx) => { console.log(`\n==== Transaction logs for ${failedSig} ====`); - console.log(explorerURL({ txSignature: failedSig }), ''); - console.log(tx?.meta?.logMessages ?? 'No log messages provided by RPC'); - console.log('==== END LOGS ====\n'); + console.log(explorerURL({ txSignature: failedSig }), ""); + console.log(tx?.meta?.logMessages ?? "No log messages provided by RPC"); + console.log("==== END LOGS ====\n"); }); else { - console.log('\n========================================'); + console.log("\n========================================"); console.log(explorerURL({ txSignature: failedSig })); - console.log('========================================\n'); + console.log("========================================\n"); } } @@ -254,7 +268,7 @@ export function numberFormatter(num: number, forceDecimals = false) { Display a separator in the console, with our without a message */ export function printConsoleSeparator(message?: string) { - console.log('\n==============================================='); - console.log('===============================================\n'); + console.log("\n==============================================="); + console.log("===============================================\n"); if (message) console.log(message); } diff --git a/compression/cutils/anchor/tests/utils/readAPI.ts b/compression/cutils/anchor/tests/utils/readAPI.ts index 3562d91c6..7c324845e 100644 --- a/compression/cutils/anchor/tests/utils/readAPI.ts +++ b/compression/cutils/anchor/tests/utils/readAPI.ts @@ -2,20 +2,21 @@ // as it supports more readAPI functionality // this is just a subset of functions for quick availabiity -import axios from 'axios'; +import axios from "axios"; //TODO insert -const RPC_PATH = ''; +const RPC_PATH = ""; +// biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 export async function getAsset(assetId: any, rpcUrl = RPC_PATH): Promise { try { const axiosInstance = axios.create({ baseURL: rpcUrl, }); const response = await axiosInstance.post(rpcUrl, { - jsonrpc: '2.0', - method: 'getAsset', - id: 'rpd-op-123', + jsonrpc: "2.0", + method: "getAsset", + id: "rpd-op-123", params: { id: assetId, }, @@ -26,15 +27,16 @@ export async function getAsset(assetId: any, rpcUrl = RPC_PATH): Promise { } } +// biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 export async function getAssetProof(assetId: any, rpcUrl = RPC_PATH): Promise { try { const axiosInstance = axios.create({ baseURL: rpcUrl, }); const response = await axiosInstance.post(rpcUrl, { - jsonrpc: '2.0', - method: 'getAssetProof', - id: 'rpd-op-123', + jsonrpc: "2.0", + method: "getAssetProof", + id: "rpd-op-123", params: { id: assetId, }, diff --git a/compression/cutils/anchor/tests/utils/utils.ts b/compression/cutils/anchor/tests/utils/utils.ts index 74206b75e..4e3001eee 100644 --- a/compression/cutils/anchor/tests/utils/utils.ts +++ b/compression/cutils/anchor/tests/utils/utils.ts @@ -1,8 +1,8 @@ -import { PROGRAM_ID as BUBBLEGUM_PROGRAM_ID } from '@metaplex-foundation/mpl-bubblegum/dist/src/generated'; -import { PROGRAM_ID as TOKEN_METADATA_PROGRAM_ID } from '@metaplex-foundation/mpl-token-metadata/dist/src/generated'; -import { SPL_ACCOUNT_COMPRESSION_PROGRAM_ID, SPL_NOOP_PROGRAM_ID } from '@solana/spl-account-compression'; -import { type AccountMeta, PublicKey, SystemProgram } from '@solana/web3.js'; -import * as bs58 from 'bs58'; +import { PROGRAM_ID as BUBBLEGUM_PROGRAM_ID } from "@metaplex-foundation/mpl-bubblegum/dist/src/generated"; +import { PROGRAM_ID as TOKEN_METADATA_PROGRAM_ID } from "@metaplex-foundation/mpl-token-metadata/dist/src/generated"; +import { SPL_ACCOUNT_COMPRESSION_PROGRAM_ID, SPL_NOOP_PROGRAM_ID } from "@solana/spl-account-compression"; +import { type AccountMeta, PublicKey, SystemProgram } from "@solana/web3.js"; +import * as bs58 from "bs58"; export function decode(stuff: string) { return bufferToArray(bs58.decode(stuff)); @@ -16,7 +16,7 @@ function bufferToArray(buffer: Buffer): number[] { } export const mapProof = (assetProof: { proof: string[] }): AccountMeta[] => { if (!assetProof.proof || assetProof.proof.length === 0) { - throw new Error('Proof is empty'); + throw new Error("Proof is empty"); } return assetProof.proof.map((node) => ({ pubkey: new PublicKey(node), @@ -32,19 +32,24 @@ export function getAccounts(collectionMint: PublicKey, tree: PublicKey) { // derive a PDA (owned by Bubblegum) to act as the signer of the compressed minting const [bubblegumSigner] = PublicKey.findProgramAddressSync( // `collection_cpi` is a custom prefix required by the Bubblegum program - [Buffer.from('collection_cpi', 'utf8')], + [Buffer.from("collection_cpi", "utf8")], BUBBLEGUM_PROGRAM_ID, ); // collection metadata account const [metadataAccount] = PublicKey.findProgramAddressSync( - [Buffer.from('metadata', 'utf8'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), collectionMint.toBuffer()], + [Buffer.from("metadata", "utf8"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), collectionMint.toBuffer()], TOKEN_METADATA_PROGRAM_ID, ); // collection master edition const [masterEditionAccount] = PublicKey.findProgramAddressSync( - [Buffer.from('metadata', 'utf8'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), collectionMint.toBuffer(), Buffer.from('edition', 'utf8')], + [ + Buffer.from("metadata", "utf8"), + TOKEN_METADATA_PROGRAM_ID.toBuffer(), + collectionMint.toBuffer(), + Buffer.from("edition", "utf8"), + ], TOKEN_METADATA_PROGRAM_ID, ); diff --git a/package.json b/package.json index 3ed3f9c7f..f9b245404 100644 --- a/package.json +++ b/package.json @@ -1,37 +1,38 @@ { - "name": "program-examples", - "version": "1.0.0", - "description": "### :crab: Rust. :snake: Python. :link: All onchain.", - "scripts": { - "sync-package-json": "ts-node scripts/sync-package-json.ts", - "format:fix": "pnpx @biomejs/biome format --write ./", - "lint:fix": "pnpx @biomejs/biome lint --write ./", - "lint": "pnpx @biomejs/biome lint ./", - "fix": "pnpx @biomejs/biome check --write ./", - "check": "pnpx @biomejs/biome check ./", - "prepare": "husky" - }, - "lint-staged": { - "*": [ - "biome check --apply --no-errors-on-unmatched --files-ignore-unknown=true" - ] - }, - "keywords": [], - "author": "Solana Foundation", - "license": "MIT", - "devDependencies": { - "@biomejs/biome": "1.8.1", - "@types/node": "^20.9.0", - "husky": "^9.0.11", - "picocolors": "^1.0.0", - "ts-node": "^10.9.1", - "typescript": "^5.2.2" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/web3.js": "^1.98.4", - "anchor-bankrun": "^0.4.0", - "chai": "^5.1.1", - "solana-bankrun": "^0.3.0" - } + "name": "program-examples", + "version": "1.0.0", + "description": "Solana program (smart contract) examples for Anchor, Native Rust, and Pinocchio.", + "scripts": { + "sync-package-json": "ts-node scripts/sync-package-json.ts", + "format:fix": "pnpx @biomejs/biome format --write ./", + "lint:fix": "pnpx @biomejs/biome lint --write ./", + "lint": "pnpx @biomejs/biome lint ./", + "fix": "pnpx @biomejs/biome check --write ./", + "check": "pnpx @biomejs/biome check ./", + "prepare": "husky" + }, + "lint-staged": { + "*": [ + "biome check --write --no-errors-on-unmatched --files-ignore-unknown=true" + ] + }, + "packageManager": "pnpm@9.13.2", + "keywords": [], + "author": "Solana Foundation", + "license": "MIT", + "devDependencies": { + "@biomejs/biome": "2.4.10", + "@types/node": "^20.9.0", + "husky": "^9.0.11", + "picocolors": "^1.0.0", + "ts-node": "^10.9.1", + "typescript": "^5.2.2" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/web3.js": "^1.98.4", + "anchor-bankrun": "^0.4.0", + "chai": "^5.1.1", + "solana-bankrun": "^0.3.0" + } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5b1f1dc05..13636b489 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -25,8 +25,8 @@ importers: version: 0.3.0(bufferutil@4.0.8)(typescript@5.4.5)(utf-8-validate@5.0.10) devDependencies: '@biomejs/biome': - specifier: 1.8.1 - version: 1.8.1 + specifier: 2.4.10 + version: 2.4.10 '@types/node': specifier: ^20.9.0 version: 20.14.2 @@ -63,59 +63,55 @@ packages: resolution: {integrity: sha512-7dRy4DwXwtzBrPbZflqxnvfxLF8kdZXPkhymtDeFoFqE6ldzjQFgYTtYIFARcLEYDrqfBfYcZt1WqFxRoyC9Rw==} engines: {node: '>=6.9.0'} - '@biomejs/biome@1.8.1': - resolution: {integrity: sha512-fQXGfvq6DIXem12dGQCM2tNF+vsNHH1qs3C7WeOu75Pd0trduoTmoO7G4ntLJ2qDs5wuw981H+cxQhi1uHnAtA==} + '@biomejs/biome@2.4.10': + resolution: {integrity: sha512-xxA3AphFQ1geij4JTHXv4EeSTda1IFn22ye9LdyVPoJU19fNVl0uzfEuhsfQ4Yue/0FaLs2/ccVi4UDiE7R30w==} engines: {node: '>=14.21.3'} hasBin: true - '@biomejs/cli-darwin-arm64@1.8.1': - resolution: {integrity: sha512-XLiB7Uu6GALIOBWzQ2aMD0ru4Ly5/qSeQF7kk3AabzJ/kwsEWSe33iVySBP/SS2qv25cgqNiLksjGcw2bHT3mw==} + '@biomejs/cli-darwin-arm64@2.4.10': + resolution: {integrity: sha512-vuzzI1cWqDVzOMIkYyHbKqp+AkQq4K7k+UCXWpkYcY/HDn1UxdsbsfgtVpa40shem8Kax4TLDLlx8kMAecgqiw==} engines: {node: '>=14.21.3'} cpu: [arm64] os: [darwin] - '@biomejs/cli-darwin-x64@1.8.1': - resolution: {integrity: sha512-uMTSxVLMfqkBVqyc25hSn83jBbp+wtWjzM/pHFlKXt3htJuw7FErVGW0nmQ9Sxa9vJ7GcqoltLMl28VQRIMYzg==} + '@biomejs/cli-darwin-x64@2.4.10': + resolution: {integrity: sha512-14fzASRo+BPotwp7nWULy2W5xeUyFnTaq1V13Etrrxkrih+ez/2QfgFm5Ehtf5vSjtgx/IJycMMpn5kPd5ZNaA==} engines: {node: '>=14.21.3'} cpu: [x64] os: [darwin] - '@biomejs/cli-linux-arm64-musl@1.8.1': - resolution: {integrity: sha512-UQ8Wc01J0wQL+5AYOc7qkJn20B4PZmQL1KrmDZh7ot0DvD6aX4+8mmfd/dG5b6Zjo/44QvCKcvkFGCMRYuhWZA==} + '@biomejs/cli-linux-arm64-musl@2.4.10': + resolution: {integrity: sha512-WrJY6UuiSD/Dh+nwK2qOTu8kdMDlLV3dLMmychIghHPAysWFq1/DGC1pVZx8POE3ZkzKR3PUUnVrtZfMfaJjyQ==} engines: {node: '>=14.21.3'} cpu: [arm64] os: [linux] - libc: [musl] - '@biomejs/cli-linux-arm64@1.8.1': - resolution: {integrity: sha512-3SzZRuC/9Oi2P2IBNPsEj0KXxSXUEYRR2kfRF/Ve8QAfGgrt4qnwuWd6QQKKN5R+oYH691qjm+cXBKEcrP1v/Q==} + '@biomejs/cli-linux-arm64@2.4.10': + resolution: {integrity: sha512-7MH1CMW5uuxQ/s7FLST63qF8B3Hgu2HRdZ7tA1X1+mk+St4JOuIrqdhIBnnyqeyWJNI+Bww7Es5QZ0wIc1Cmkw==} engines: {node: '>=14.21.3'} cpu: [arm64] os: [linux] - libc: [glibc] - '@biomejs/cli-linux-x64-musl@1.8.1': - resolution: {integrity: sha512-fYbP/kNu/rtZ4kKzWVocIdqZOtBSUEg9qUhZaao3dy3CRzafR6u6KDtBeSCnt47O+iLnks1eOR1TUxzr5+QuqA==} + '@biomejs/cli-linux-x64-musl@2.4.10': + resolution: {integrity: sha512-kDTi3pI6PBN6CiczsWYOyP2zk0IJI08EWEQyDMQWW221rPaaEz6FvjLhnU07KMzLv8q3qSuoB93ua6inSQ55Tw==} engines: {node: '>=14.21.3'} cpu: [x64] os: [linux] - libc: [musl] - '@biomejs/cli-linux-x64@1.8.1': - resolution: {integrity: sha512-AeBycVdNrTzsyYKEOtR2R0Ph0hCD0sCshcp2aOnfGP0hCZbtFg09D0SdKLbyzKntisY41HxKVrydYiaApp+2uw==} + '@biomejs/cli-linux-x64@2.4.10': + resolution: {integrity: sha512-tZLvEEi2u9Xu1zAqRjTcpIDGVtldigVvzug2fTuPG0ME/g8/mXpRPcNgLB22bGn6FvLJpHHnqLnwliOu8xjYrg==} engines: {node: '>=14.21.3'} cpu: [x64] os: [linux] - libc: [glibc] - '@biomejs/cli-win32-arm64@1.8.1': - resolution: {integrity: sha512-6tEd1H/iFKpgpE3OIB7oNgW5XkjiVMzMRPL8zYoZ036YfuJ5nMYm9eB9H/y81+8Z76vL48fiYzMPotJwukGPqQ==} + '@biomejs/cli-win32-arm64@2.4.10': + resolution: {integrity: sha512-umwQU6qPzH+ISTf/eHyJ/QoQnJs3V9Vpjz2OjZXe9MVBZ7prgGafMy7yYeRGnlmDAn87AKTF3Q6weLoMGpeqdQ==} engines: {node: '>=14.21.3'} cpu: [arm64] os: [win32] - '@biomejs/cli-win32-x64@1.8.1': - resolution: {integrity: sha512-g2H31jJzYmS4jkvl6TiyEjEX+Nv79a5km/xn+5DARTp5MBFzC9gwceusSSB2AkJKqZzY131AiACAWjKrVt5Ijw==} + '@biomejs/cli-win32-x64@2.4.10': + resolution: {integrity: sha512-aW/JU5GuyH4uxMrNYpoC2kjaHlyJGLgIa3XkhPEZI0uKhZhJZU8BuEyJmvgzSPQNGozBwWjC972RaNdcJ9KyJg==} engines: {node: '>=14.21.3'} cpu: [x64] os: [win32] @@ -430,14 +426,12 @@ packages: engines: {node: '>= 10'} cpu: [x64] os: [linux] - libc: [glibc] solana-bankrun-linux-x64-musl@0.3.0: resolution: {integrity: sha512-xsS2CS2xb1Sw4ivNXM0gPz/qpW9BX0neSvt/pnok5L330Nu9xlTnKAY8FhzzqOP9P9sJlGRM787Y6d0yYwt6xQ==} engines: {node: '>= 10'} cpu: [x64] os: [linux] - libc: [musl] solana-bankrun@0.3.0: resolution: {integrity: sha512-YkH7sa8TB/AoRPzG17CXJtYsRIQHEkEqGLz1Vwc13taXhDBkjO7z6NI5JYw7n0ybRymDHwMYTc7sd+5J40TyVQ==} @@ -567,39 +561,39 @@ snapshots: dependencies: regenerator-runtime: 0.14.1 - '@biomejs/biome@1.8.1': + '@biomejs/biome@2.4.10': optionalDependencies: - '@biomejs/cli-darwin-arm64': 1.8.1 - '@biomejs/cli-darwin-x64': 1.8.1 - '@biomejs/cli-linux-arm64': 1.8.1 - '@biomejs/cli-linux-arm64-musl': 1.8.1 - '@biomejs/cli-linux-x64': 1.8.1 - '@biomejs/cli-linux-x64-musl': 1.8.1 - '@biomejs/cli-win32-arm64': 1.8.1 - '@biomejs/cli-win32-x64': 1.8.1 - - '@biomejs/cli-darwin-arm64@1.8.1': + '@biomejs/cli-darwin-arm64': 2.4.10 + '@biomejs/cli-darwin-x64': 2.4.10 + '@biomejs/cli-linux-arm64': 2.4.10 + '@biomejs/cli-linux-arm64-musl': 2.4.10 + '@biomejs/cli-linux-x64': 2.4.10 + '@biomejs/cli-linux-x64-musl': 2.4.10 + '@biomejs/cli-win32-arm64': 2.4.10 + '@biomejs/cli-win32-x64': 2.4.10 + + '@biomejs/cli-darwin-arm64@2.4.10': optional: true - '@biomejs/cli-darwin-x64@1.8.1': + '@biomejs/cli-darwin-x64@2.4.10': optional: true - '@biomejs/cli-linux-arm64-musl@1.8.1': + '@biomejs/cli-linux-arm64-musl@2.4.10': optional: true - '@biomejs/cli-linux-arm64@1.8.1': + '@biomejs/cli-linux-arm64@2.4.10': optional: true - '@biomejs/cli-linux-x64-musl@1.8.1': + '@biomejs/cli-linux-x64-musl@2.4.10': optional: true - '@biomejs/cli-linux-x64@1.8.1': + '@biomejs/cli-linux-x64@2.4.10': optional: true - '@biomejs/cli-win32-arm64@1.8.1': + '@biomejs/cli-win32-arm64@2.4.10': optional: true - '@biomejs/cli-win32-x64@1.8.1': + '@biomejs/cli-win32-x64@2.4.10': optional: true '@coral-xyz/anchor-errors@0.31.1': {} diff --git a/scripts/lib/change-package-version.ts b/scripts/lib/change-package-version.ts index 0e8dab176..ee32d7c61 100644 --- a/scripts/lib/change-package-version.ts +++ b/scripts/lib/change-package-version.ts @@ -1,7 +1,7 @@ -import { readFileSync } from 'node:fs'; +import { readFileSync } from "node:fs"; export function changePackageVersion(file: string, pkgName: string, pkgVersion: string): [boolean, string] { - const content = JSON.parse(readFileSync(file).toString('utf-8')); + const content = JSON.parse(readFileSync(file).toString("utf-8")); if (content.dependencies?.[pkgName] && content.dependencies[pkgName] !== pkgVersion) { content.dependencies[pkgName] = pkgVersion; return [true, content]; diff --git a/scripts/lib/command-check.ts b/scripts/lib/command-check.ts index 99c3d5bb8..7d13f50dc 100644 --- a/scripts/lib/command-check.ts +++ b/scripts/lib/command-check.ts @@ -1,10 +1,10 @@ -import { basename } from 'node:path'; -import * as p from 'picocolors'; -import { getDepsCount } from './get-deps-count'; -import { getRecursiveFileList } from './get-recursive-file-list'; +import { basename } from "node:path"; +import * as p from "picocolors"; +import { getDepsCount } from "./get-deps-count"; +import { getRecursiveFileList } from "./get-recursive-file-list"; -export function commandCheck(path = '.') { - const files = getRecursiveFileList(path).filter((file) => basename(file) === 'package.json'); +export function commandCheck(path = ".") { + const files = getRecursiveFileList(path).filter((file) => basename(file) === "package.json"); const depsCounter = getDepsCount(files); const single: string[] = []; @@ -17,7 +17,7 @@ export function commandCheck(path = '.') { if (versionsLength === 1) { const count = versions[versionMap[0]].length; - single.push(`${p.green('✔')} ${pkg}@${versionMap[0]} (${count})`); + single.push(`${p.green("✔")} ${pkg}@${versionMap[0]} (${count})`); continue; } @@ -27,7 +27,7 @@ export function commandCheck(path = '.') { } versionCount.sort((a, b) => b.count - a.count); - multiple.push(`${p.yellow('⚠')} ${pkg} has ${versionsLength} versions:`); + multiple.push(`${p.yellow("⚠")} ${pkg} has ${versionsLength} versions:`); for (const { count, version } of versionCount) { multiple.push(` - ${p.bold(version)} (${count})`); diff --git a/scripts/lib/command-help.ts b/scripts/lib/command-help.ts index dfbe8021f..6fe22dd5c 100644 --- a/scripts/lib/command-help.ts +++ b/scripts/lib/command-help.ts @@ -1,26 +1,26 @@ export function commandHelp() { - console.log('Usage: yarn sync-package-json [options]'); - console.log(''); - console.log('Commands:'); - console.log(' check Check package.json files'); - console.log(' help Show this help'); - console.log(' list List package.json files'); - console.log(' set [ver] Set specific version in package.json files'); - console.log(' update Update all versions in package.json files'); - console.log(''); - console.log('Arguments:'); - console.log(' path Path to directory'); - console.log(''); - console.log('Examples:'); - console.log(' yarn sync-package-json check'); - console.log(' yarn sync-package-json check basics'); - console.log(' yarn sync-package-json list'); - console.log(' yarn sync-package-json list basics'); - console.log(' yarn sync-package-json help'); - console.log(' yarn sync-package-json set @coral-xyz/anchor@0.29.0'); - console.log(' yarn sync-package-json set @coral-xyz/anchor@0.29.0 basics'); - console.log(' yarn sync-package-json update'); - console.log(' yarn sync-package-json update basics'); - console.log(' yarn sync-package-json update . @solana/web3.js @solana/spl-token'); + console.log("Usage: yarn sync-package-json [options]"); + console.log(""); + console.log("Commands:"); + console.log(" check Check package.json files"); + console.log(" help Show this help"); + console.log(" list List package.json files"); + console.log(" set [ver] Set specific version in package.json files"); + console.log(" update Update all versions in package.json files"); + console.log(""); + console.log("Arguments:"); + console.log(" path Path to directory"); + console.log(""); + console.log("Examples:"); + console.log(" yarn sync-package-json check"); + console.log(" yarn sync-package-json check basics"); + console.log(" yarn sync-package-json list"); + console.log(" yarn sync-package-json list basics"); + console.log(" yarn sync-package-json help"); + console.log(" yarn sync-package-json set @coral-xyz/anchor@0.29.0"); + console.log(" yarn sync-package-json set @coral-xyz/anchor@0.29.0 basics"); + console.log(" yarn sync-package-json update"); + console.log(" yarn sync-package-json update basics"); + console.log(" yarn sync-package-json update . @solana/web3.js @solana/spl-token"); process.exit(0); } diff --git a/scripts/lib/command-list.ts b/scripts/lib/command-list.ts index a127c1a73..fdda272aa 100644 --- a/scripts/lib/command-list.ts +++ b/scripts/lib/command-list.ts @@ -1,8 +1,8 @@ -import { basename } from 'node:path'; -import { getRecursiveFileList } from './get-recursive-file-list'; +import { basename } from "node:path"; +import { getRecursiveFileList } from "./get-recursive-file-list"; export function commandList(path: string) { - const files = getRecursiveFileList(path).filter((file) => basename(file) === 'package.json'); + const files = getRecursiveFileList(path).filter((file) => basename(file) === "package.json"); for (const file of files) { console.log(file); } diff --git a/scripts/lib/command-set.ts b/scripts/lib/command-set.ts index 33d5be755..cad1dc6c0 100644 --- a/scripts/lib/command-set.ts +++ b/scripts/lib/command-set.ts @@ -1,32 +1,32 @@ -import { writeFileSync } from 'node:fs'; -import { basename } from 'node:path'; -import { changePackageVersion } from './change-package-version'; -import { getRecursiveFileList } from './get-recursive-file-list'; +import { writeFileSync } from "node:fs"; +import { basename } from "node:path"; +import { changePackageVersion } from "./change-package-version"; +import { getRecursiveFileList } from "./get-recursive-file-list"; -export function commandSet(version: string, path = '.') { +export function commandSet(version: string, path = ".") { if (!version) { - console.error('Version is required'); + console.error("Version is required"); process.exit(1); } if ( !version // Strip first character if it's a `@` - .replace(/^@/, '') - .includes('@') + .replace(/^@/, "") + .includes("@") ) { console.error(`Invalid package version: ${version}. Provide package with version, e.g. @solana/web3.js@1.0.0`); process.exit(1); } // Take anything after the second `@` as the version, the rest is the package name - const [pkg, ...rest] = version.split('@').reverse(); - const pkgName = rest.reverse().join('@'); + const [pkg, ...rest] = version.split("@").reverse(); + const pkgName = rest.reverse().join("@"); // Make sure pkgVersions has a ^ prefix, if not add it - const pkgVersion = pkg.startsWith('^') ? pkg : `^${pkg}`; + const pkgVersion = pkg.startsWith("^") ? pkg : `^${pkg}`; console.log(`Setting package ${pkgName} to ${pkgVersion} in ${path}`); - const files = getRecursiveFileList(path).filter((file) => basename(file) === 'package.json'); + const files = getRecursiveFileList(path).filter((file) => basename(file) === "package.json"); let count = 0; for (const file of files) { const [changed, content] = changePackageVersion(file, pkgName, pkgVersion); @@ -36,7 +36,7 @@ export function commandSet(version: string, path = '.') { } } if (count === 0) { - console.log('No files updated'); + console.log("No files updated"); } else { console.log(`Updated ${count} files`); } diff --git a/scripts/lib/command-update.ts b/scripts/lib/command-update.ts index 360d75dd9..02c724a78 100644 --- a/scripts/lib/command-update.ts +++ b/scripts/lib/command-update.ts @@ -1,18 +1,18 @@ -import { execSync } from 'node:child_process'; -import { writeFileSync } from 'node:fs'; -import { basename } from 'node:path'; -import * as p from 'picocolors'; -import { changePackageVersion } from './change-package-version'; +import { execSync } from "node:child_process"; +import { writeFileSync } from "node:fs"; +import { basename } from "node:path"; +import * as p from "picocolors"; +import { changePackageVersion } from "./change-package-version"; -import { getDepsCount } from './get-deps-count'; -import { getRecursiveFileList } from './get-recursive-file-list'; +import { getDepsCount } from "./get-deps-count"; +import { getRecursiveFileList } from "./get-recursive-file-list"; -export function commandUpdate(path = '.', packageNames: string[] = []) { - const files = getRecursiveFileList(path).filter((file) => basename(file) === 'package.json'); +export function commandUpdate(path = ".", packageNames: string[] = []) { + const files = getRecursiveFileList(path).filter((file) => basename(file) === "package.json"); const depsCounter = getDepsCount(files); const pkgNames = Object.keys(depsCounter).sort(); if (packageNames.length > 0) { - console.log(`Updating ${packageNames.join(', ')} in ${files.length} files`); + console.log(`Updating ${packageNames.join(", ")} in ${files.length} files`); } let total = 0; @@ -38,7 +38,7 @@ export function commandUpdate(path = '.', packageNames: string[] = []) { } if (total === 0) { - console.log('No files updated'); + console.log("No files updated"); } else { console.log(`Updated ${total} files`); } diff --git a/scripts/lib/get-deps-count.ts b/scripts/lib/get-deps-count.ts index 4481213a1..087bed171 100644 --- a/scripts/lib/get-deps-count.ts +++ b/scripts/lib/get-deps-count.ts @@ -1,11 +1,11 @@ -import { readFileSync } from 'node:fs'; +import { readFileSync } from "node:fs"; export function getDepsCount(files: string[] = []): Record> { const map: Record = {}; const depsCounter: Record> = {}; for (const file of files) { - const content = JSON.parse(readFileSync(file).toString('utf-8')); + const content = JSON.parse(readFileSync(file).toString("utf-8")); map[file] = content; const deps = content.dependencies ?? {}; diff --git a/scripts/lib/get-recursive-file-list.ts b/scripts/lib/get-recursive-file-list.ts index 8c65fbea1..951df23e5 100644 --- a/scripts/lib/get-recursive-file-list.ts +++ b/scripts/lib/get-recursive-file-list.ts @@ -1,8 +1,8 @@ // Point method at path and return a list of all the files in the directory recursively -import { readdirSync, statSync } from 'node:fs'; +import { readdirSync, statSync } from "node:fs"; export function getRecursiveFileList(path: string): string[] { - const ignore = ['.git', '.github', '.idea', '.next', '.vercel', '.vscode', 'coverage', 'dist', 'node_modules']; + const ignore = [".git", ".github", ".idea", ".next", ".vercel", ".vscode", "coverage", "dist", "node_modules"]; const files: string[] = []; const items = readdirSync(path); @@ -23,6 +23,6 @@ export function getRecursiveFileList(path: string): string[] { return files.filter((file) => { // Remove package.json from the root directory - return path === '.' ? file !== './package.json' : true; + return path === "." ? file !== "./package.json" : true; }); } diff --git a/scripts/lib/index.ts b/scripts/lib/index.ts index 37dfbc8cf..0d9c97099 100644 --- a/scripts/lib/index.ts +++ b/scripts/lib/index.ts @@ -1,5 +1,5 @@ -export * from './command-check'; -export * from './command-help'; -export * from './command-list'; -export * from './command-set'; -export * from './command-update'; +export * from "./command-check"; +export * from "./command-help"; +export * from "./command-list"; +export * from "./command-set"; +export * from "./command-update"; diff --git a/scripts/sync-package-json.ts b/scripts/sync-package-json.ts index 1ecec29bd..56844c92e 100644 --- a/scripts/sync-package-json.ts +++ b/scripts/sync-package-json.ts @@ -1,18 +1,18 @@ -import { commandCheck, commandHelp, commandList, commandSet, commandUpdate } from './lib'; +import { commandCheck, commandHelp, commandList, commandSet, commandUpdate } from "./lib"; const params: string[] = process.argv.slice(3); switch (process.argv[2]) { - case 'check': + case "check": commandCheck(params[0]); break; - case 'list': + case "list": commandList(params[0]); break; - case 'set': + case "set": commandSet(params[0], params[1]); break; - case 'update': + case "update": commandUpdate(params[0], params.slice(1)); break; default: diff --git a/tokens/create-token/anchor/package.json b/tokens/create-token/anchor/package.json index 9dec90fba..59b307edc 100644 --- a/tokens/create-token/anchor/package.json +++ b/tokens/create-token/anchor/package.json @@ -1,21 +1,21 @@ { - "type": "module", - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5" - }, - "scripts": { - "postinstall": "zx prepare.mjs" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "anchor-bankrun": "^0.4.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "solana-bankrun": "^0.3.0", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3", - "zx": "^8.1.4" - } + "type": "module", + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5" + }, + "scripts": { + "postinstall": "zx prepare.mjs" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "anchor-bankrun": "^0.4.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "solana-bankrun": "^0.3.0", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3", + "zx": "^8.1.4" + } } diff --git a/tokens/create-token/anchor/prepare.mjs b/tokens/create-token/anchor/prepare.mjs index 7c5ec464b..fb6b26225 100644 --- a/tokens/create-token/anchor/prepare.mjs +++ b/tokens/create-token/anchor/prepare.mjs @@ -1,17 +1,17 @@ #!/usr/bin/env zx -import { mkdir, rm } from 'node:fs/promises'; -import { join } from 'node:path'; -import { $ } from 'zx'; +import { mkdir, rm } from "node:fs/promises"; +import { join } from "node:path"; +import { $ } from "zx"; const programs = [ { - id: 'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s', - name: 'token_metadata.so', + id: "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s", + name: "token_metadata.so", }, ]; -const outputDir = 'tests/fixtures'; +const outputDir = "tests/fixtures"; const overwrite = true; try { diff --git a/tokens/create-token/anchor/tests/bankrun.test.ts b/tokens/create-token/anchor/tests/bankrun.test.ts index e2ce027f3..37a0ab291 100644 --- a/tokens/create-token/anchor/tests/bankrun.test.ts +++ b/tokens/create-token/anchor/tests/bankrun.test.ts @@ -8,9 +8,7 @@ import type { CreateToken } from "../target/types/create_token"; // requires TypeScript 5.3+, but this project uses typescript ^4.3.5 with ts-mocha. const IDL = require("../target/idl/create_token.json"); const PROGRAM_ID = new PublicKey(IDL.address); -const METADATA_PROGRAM_ID = new PublicKey( - "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s", -); +const METADATA_PROGRAM_ID = new PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"); describe("Bankrun example", async () => { const context = await startAnchor( diff --git a/tokens/create-token/anchor/tests/test.ts b/tokens/create-token/anchor/tests/test.ts index 4f673627b..cafce25ee 100644 --- a/tokens/create-token/anchor/tests/test.ts +++ b/tokens/create-token/anchor/tests/test.ts @@ -1,20 +1,20 @@ -import * as anchor from '@anchor-lang/core'; -import { Keypair } from '@solana/web3.js'; -import type { CreateToken } from '../target/types/create_token'; +import * as anchor from "@anchor-lang/core"; +import { Keypair } from "@solana/web3.js"; +import type { CreateToken } from "../target/types/create_token"; -describe('Create Tokens', () => { +describe("Create Tokens", () => { const provider = anchor.AnchorProvider.env(); anchor.setProvider(provider); const payer = provider.wallet as anchor.Wallet; const program = anchor.workspace.CreateToken as anchor.Program; const metadata = { - name: 'Solana Gold', - symbol: 'GOLDSOL', - uri: 'https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json', + name: "Solana Gold", + symbol: "GOLDSOL", + uri: "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json", }; - it('Create an SPL Token!', async () => { + it("Create an SPL Token!", async () => { // Generate new keypair to use as address for mint account. const mintKeypair = new Keypair(); @@ -28,12 +28,12 @@ describe('Create Tokens', () => { .signers([mintKeypair]) .rpc(); - console.log('Success!'); + console.log("Success!"); console.log(` Mint Address: ${mintKeypair.publicKey}`); console.log(` Transaction Signature: ${transactionSignature}`); }); - it('Create an NFT!', async () => { + it("Create an NFT!", async () => { // Generate new keypair to use as address for mint account. const mintKeypair = new Keypair(); @@ -47,7 +47,7 @@ describe('Create Tokens', () => { .signers([mintKeypair]) .rpc(); - console.log('Success!'); + console.log("Success!"); console.log(` Mint Address: ${mintKeypair.publicKey}`); console.log(` Transaction Signature: ${transactionSignature}`); }); diff --git a/tokens/create-token/native/package.json b/tokens/create-token/native/package.json index 88dcb0d51..192560abc 100644 --- a/tokens/create-token/native/package.json +++ b/tokens/create-token/native/package.json @@ -1,26 +1,26 @@ { - "scripts": { - "test": "pnpm ts-mocha -p ./tsconfig.json -t 1000000 ./tests/test.ts", - "build-and-test": "cargo build-sbf --manifest-path=./program/Cargo.toml --sbf-out-dir=./tests/fixtures && pnpm test", - "build": "cargo build-sbf --manifest-path=./program/Cargo.toml --sbf-out-dir=./program/target/so", - "deploy": "solana program deploy ./program/target/so/hello_solana_program.so" - }, - "dependencies": { - "@metaplex-foundation/mpl-token-metadata": "^2.5.2", - "@solana/spl-token": "^0.3.7", - "@solana/web3.js": "^1.98.4", - "borsh": "^2.0.0", - "buffer": "^6.0.3", - "fs": "^0.0.1-security" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.1", - "@types/mocha": "^9.1.1", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "ts-mocha": "^10.0.0", - "typescript": "^5" - }, - "type": "module" + "scripts": { + "test": "pnpm ts-mocha -p ./tsconfig.json -t 1000000 ./tests/test.ts", + "build-and-test": "cargo build-sbf --manifest-path=./program/Cargo.toml --sbf-out-dir=./tests/fixtures && pnpm test", + "build": "cargo build-sbf --manifest-path=./program/Cargo.toml --sbf-out-dir=./program/target/so", + "deploy": "solana program deploy ./program/target/so/hello_solana_program.so" + }, + "dependencies": { + "@metaplex-foundation/mpl-token-metadata": "^2.5.2", + "@solana/spl-token": "^0.3.7", + "@solana/web3.js": "^1.98.4", + "borsh": "^2.0.0", + "buffer": "^6.0.3", + "fs": "^0.0.1-security" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.1", + "@types/mocha": "^9.1.1", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "ts-mocha": "^10.0.0", + "typescript": "^5" + }, + "type": "module" } diff --git a/tokens/create-token/native/tests/test.ts b/tokens/create-token/native/tests/test.ts index d583c7798..69a530d2a 100644 --- a/tokens/create-token/native/tests/test.ts +++ b/tokens/create-token/native/tests/test.ts @@ -1,6 +1,6 @@ -import { Buffer } from 'node:buffer'; -import { PROGRAM_ID as TOKEN_METADATA_PROGRAM_ID } from '@metaplex-foundation/mpl-token-metadata'; -import { TOKEN_PROGRAM_ID } from '@solana/spl-token'; +import { Buffer } from "node:buffer"; +import { PROGRAM_ID as TOKEN_METADATA_PROGRAM_ID } from "@metaplex-foundation/mpl-token-metadata"; +import { TOKEN_PROGRAM_ID } from "@solana/spl-token"; import { Connection, Keypair, @@ -10,19 +10,19 @@ import { sendAndConfirmTransaction, Transaction, TransactionInstruction, -} from '@solana/web3.js'; -import * as borsh from 'borsh'; +} from "@solana/web3.js"; +import * as borsh from "borsh"; function createKeypairFromFile(path: string): Keypair { - return Keypair.fromSecretKey(Uint8Array.from(JSON.parse(require('node:fs').readFileSync(path, 'utf-8')))); + return Keypair.fromSecretKey(Uint8Array.from(JSON.parse(require("node:fs").readFileSync(path, "utf-8")))); } const CreateTokenArgsSchema = { struct: { - token_title: 'string', - token_symbol: 'string', - token_uri: 'string', - token_decimals: 'u8', + token_title: "string", + token_symbol: "string", + token_uri: "string", + token_decimals: "u8", }, }; @@ -30,26 +30,27 @@ function borshSerialize(schema: borsh.Schema, data: object): Buffer { return Buffer.from(borsh.serialize(schema, data)); } -describe('Create Tokens!', async () => { +describe("Create Tokens!", async () => { // const connection = new Connection(`http://localhost:8899`, 'confirmed'); - const connection = new Connection('https://api.devnet.solana.com/', 'confirmed'); - const payer = createKeypairFromFile(`${require('node:os').homedir()}/.config/solana/id.json`); - const program = createKeypairFromFile('./program/target/deploy/program-keypair.json'); + const connection = new Connection("https://api.devnet.solana.com/", "confirmed"); + const payer = createKeypairFromFile(`${require("node:os").homedir()}/.config/solana/id.json`); + const program = createKeypairFromFile("./program/target/deploy/program-keypair.json"); - it('Create an SPL Token!', async () => { + it("Create an SPL Token!", async () => { const mintKeypair: Keypair = Keypair.generate(); const metadataAddress = PublicKey.findProgramAddressSync( - [Buffer.from('metadata'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mintKeypair.publicKey.toBuffer()], + [Buffer.from("metadata"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mintKeypair.publicKey.toBuffer()], TOKEN_METADATA_PROGRAM_ID, )[0]; // SPL Token default = 9 decimals // const instructionData = borshSerialize(CreateTokenArgsSchema, { - token_title: 'Solana Gold', - token_symbol: 'GOLDSOL', - token_uri: 'https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json', + token_title: "Solana Gold", + token_symbol: "GOLDSOL", + token_uri: + "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json", token_decimals: 9, }); @@ -74,25 +75,26 @@ describe('Create Tokens!', async () => { const sx = await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer, mintKeypair]); - console.log('Success!'); + console.log("Success!"); console.log(` Mint Address: ${mintKeypair.publicKey}`); console.log(` Tx Signature: ${sx}`); }); - it('Create an NFT!', async () => { + it("Create an NFT!", async () => { const mintKeypair: Keypair = Keypair.generate(); const metadataAddress = PublicKey.findProgramAddressSync( - [Buffer.from('metadata'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mintKeypair.publicKey.toBuffer()], + [Buffer.from("metadata"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mintKeypair.publicKey.toBuffer()], TOKEN_METADATA_PROGRAM_ID, )[0]; // NFT default = 0 decimals // const instructionData = borshSerialize(CreateTokenArgsSchema, { - token_title: 'Homer NFT', - token_symbol: 'HOMR', - token_uri: 'https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/nft.json', + token_title: "Homer NFT", + token_symbol: "HOMR", + token_uri: + "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/nft.json", token_decimals: 9, }); @@ -117,7 +119,7 @@ describe('Create Tokens!', async () => { const sx = await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer, mintKeypair]); - console.log('Success!'); + console.log("Success!"); console.log(` Mint Address: ${mintKeypair.publicKey}`); console.log(` Tx Signature: ${sx}`); }); diff --git a/tokens/escrow/anchor/migrations/deploy.ts b/tokens/escrow/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/tokens/escrow/anchor/migrations/deploy.ts +++ b/tokens/escrow/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/escrow/anchor/package.json b/tokens/escrow/anchor/package.json index 06fd044a4..da55f920f 100644 --- a/tokens/escrow/anchor/package.json +++ b/tokens/escrow/anchor/package.json @@ -1,27 +1,27 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana-developers/helpers": "^2.8.1", - "@solana/spl-token": "^0.4.14", - "@solana/web3.js": "^1.98.4" - }, - "license": "MIT", - "devDependencies": { - "@types/bn.js": "^5.2.0", - "@types/chai": "^5.2.3", - "@types/mocha": "^10.0.10", - "anchor-bankrun": "^0.5.0", - "chai": "^6.2.2", - "mocha": "^11.7.5", - "prettier": "^3.7.4", - "solana-bankrun": "^0.4.0", - "ts-mocha": "^11.1.0", - "ts-node": "^10.9.2", - "typescript": "^5.9.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana-developers/helpers": "^2.8.1", + "@solana/spl-token": "^0.4.14", + "@solana/web3.js": "^1.98.4" + }, + "license": "MIT", + "devDependencies": { + "@types/bn.js": "^5.2.0", + "@types/chai": "^5.2.3", + "@types/mocha": "^10.0.10", + "anchor-bankrun": "^0.5.0", + "chai": "^6.2.2", + "mocha": "^11.7.5", + "prettier": "^3.7.4", + "solana-bankrun": "^0.4.0", + "ts-mocha": "^11.1.0", + "ts-node": "^10.9.2", + "typescript": "^5.9.3" + } } diff --git a/tokens/escrow/anchor/register.js b/tokens/escrow/anchor/register.js index 9e438057f..b9c8afd2f 100644 --- a/tokens/escrow/anchor/register.js +++ b/tokens/escrow/anchor/register.js @@ -1,4 +1,4 @@ -import { register } from 'node:module'; -import { pathToFileURL } from 'node:url'; +import { register } from "node:module"; +import { pathToFileURL } from "node:url"; -register('ts-node/esm', pathToFileURL('./')); +register("ts-node/esm", pathToFileURL("./")); diff --git a/tokens/escrow/anchor/tests/bankrun.test.ts b/tokens/escrow/anchor/tests/bankrun.test.ts index d5cfa0768..4a9e34b93 100644 --- a/tokens/escrow/anchor/tests/bankrun.test.ts +++ b/tokens/escrow/anchor/tests/bankrun.test.ts @@ -1,41 +1,38 @@ -import { randomBytes } from 'node:crypto'; -import anchor from '@anchor-lang/core'; +import { randomBytes } from "node:crypto"; +import anchor from "@anchor-lang/core"; + const BN = anchor.BN; + import { createAssociatedTokenAccountIdempotentInstruction, createInitializeMint2Instruction, createMintToInstruction, + getAccount, getAssociatedTokenAddressSync, getMinimumBalanceForRentExemptMint, - getAccount, - unpackAccount, MINT_SIZE, TOKEN_2022_PROGRAM_ID, type TOKEN_PROGRAM_ID, -} from '@solana/spl-token'; -import { - LAMPORTS_PER_SOL, - PublicKey, - SystemProgram, - Transaction, - type TransactionInstruction, -} from '@solana/web3.js'; -import { makeKeypairs } from '@solana-developers/helpers'; -import { BankrunProvider } from 'anchor-bankrun'; -import { assert } from 'chai'; -import { ProgramTestContext, startAnchor } from 'solana-bankrun'; -import type { Escrow } from '../target/types/escrow'; - -const TOKEN_PROGRAM: typeof TOKEN_2022_PROGRAM_ID | typeof TOKEN_PROGRAM_ID = - TOKEN_2022_PROGRAM_ID; -import IDL from '../target/idl/escrow.json' with { type: 'json' }; + unpackAccount, +} from "@solana/spl-token"; +import { LAMPORTS_PER_SOL, PublicKey, SystemProgram, Transaction, type TransactionInstruction } from "@solana/web3.js"; +import { makeKeypairs } from "@solana-developers/helpers"; +import { BankrunProvider } from "anchor-bankrun"; +import { assert } from "chai"; +import { type ProgramTestContext, startAnchor } from "solana-bankrun"; +import type { Escrow } from "../target/types/escrow"; + +const TOKEN_PROGRAM: typeof TOKEN_2022_PROGRAM_ID | typeof TOKEN_PROGRAM_ID = TOKEN_2022_PROGRAM_ID; + +import IDL from "../target/idl/escrow.json" with { type: "json" }; + const PROGRAM_ID = new PublicKey(IDL.address); const getRandomBigNumber = (size = 8) => { return new BN(randomBytes(size)); }; -describe('Escrow Bankrun example', () => { +describe("Escrow Bankrun example", () => { let context: ProgramTestContext; let provider: BankrunProvider; let connection: anchor.web3.Connection; @@ -49,41 +46,24 @@ describe('Escrow Bankrun example', () => { const [alice, bob, tokenMintA, tokenMintB] = makeKeypairs(4); before( - 'Creates Alice and Bob accounts, 2 token mints, and associated token accounts for both tokens for both users', + "Creates Alice and Bob accounts, 2 token mints, and associated token accounts for both tokens for both users", async () => { - context = await startAnchor( - '', - [{ name: 'escrow', programId: PROGRAM_ID }], - [], - ); + context = await startAnchor("", [{ name: "escrow", programId: PROGRAM_ID }], []); provider = new BankrunProvider(context); connection = provider.connection; program = new anchor.Program(IDL, provider); - const [ - aliceTokenAccountA, - aliceTokenAccountB, - bobTokenAccountA, - bobTokenAccountB, - ] = [alice, bob].flatMap((keypair) => - [tokenMintA, tokenMintB].map((mint) => - getAssociatedTokenAddressSync( - mint.publicKey, - keypair.publicKey, - false, - TOKEN_PROGRAM, + const [aliceTokenAccountA, aliceTokenAccountB, bobTokenAccountA, bobTokenAccountB] = [alice, bob].flatMap( + (keypair) => + [tokenMintA, tokenMintB].map((mint) => + getAssociatedTokenAddressSync(mint.publicKey, keypair.publicKey, false, TOKEN_PROGRAM), ), - ), ); // Airdrops to users, and creates two tokens mints 'A' and 'B'" - const minimumLamports = - await getMinimumBalanceForRentExemptMint(connection); + const minimumLamports = await getMinimumBalanceForRentExemptMint(connection); - const sendSolInstructions: Array = [ - alice, - bob, - ].map((account) => + const sendSolInstructions: Array = [alice, bob].map((account) => SystemProgram.transfer({ fromPubkey: provider.publicKey, toPubkey: account.publicKey, @@ -91,10 +71,7 @@ describe('Escrow Bankrun example', () => { }), ); - const createMintInstructions: Array = [ - tokenMintA, - tokenMintB, - ].map((mint) => + const createMintInstructions: Array = [tokenMintA, tokenMintB].map((mint) => SystemProgram.createAccount({ fromPubkey: provider.publicKey, newAccountPubkey: mint.publicKey, @@ -117,13 +94,7 @@ describe('Escrow Bankrun example', () => { ata: bobTokenAccountB, }, ].flatMap((mintDetails) => [ - createInitializeMint2Instruction( - mintDetails.mint, - 6, - mintDetails.authority, - null, - TOKEN_PROGRAM, - ), + createInitializeMint2Instruction(mintDetails.mint, 6, mintDetails.authority, null, TOKEN_PROGRAM), createAssociatedTokenAccountIdempotentInstruction( provider.publicKey, mintDetails.ata, @@ -143,11 +114,7 @@ describe('Escrow Bankrun example', () => { // Add all these instructions to our transaction const tx = new Transaction(); - tx.instructions = [ - ...sendSolInstructions, - ...createMintInstructions, - ...mintTokensInstructions, - ]; + tx.instructions = [...sendSolInstructions, ...createMintInstructions, ...mintTokensInstructions]; await provider.sendAndConfirm(tx, [tokenMintA, tokenMintB, alice, bob]); @@ -173,37 +140,23 @@ describe('Escrow Bankrun example', () => { // Then determine the account addresses we'll use for the offer and the vault const offer = PublicKey.findProgramAddressSync( - [ - Buffer.from('offer'), - accounts.maker.toBuffer(), - offerId.toArrayLike(Buffer, 'le', 8), - ], + [Buffer.from("offer"), accounts.maker.toBuffer(), offerId.toArrayLike(Buffer, "le", 8)], program.programId, )[0]; - const vault = getAssociatedTokenAddressSync( - accounts.tokenMintA, - offer, - true, - TOKEN_PROGRAM, - ); + const vault = getAssociatedTokenAddressSync(accounts.tokenMintA, offer, true, TOKEN_PROGRAM); accounts.offer = offer; accounts.vault = vault; - const transactionSignature = await program.methods + const _transactionSignature = await program.methods .makeOffer(offerId, tokenAOfferedAmount, tokenBWantedAmount) .accounts({ ...accounts }) .signers([alice]) .rpc(); // Check our vault contains the tokens offered - const vaultAccount = await getAccount( - connection, - vault, - 'processed', - TOKEN_PROGRAM, - ); + const vaultAccount = await getAccount(connection, vault, "processed", TOKEN_PROGRAM); const vaultBalance = new BN(vaultAccount.amount.toString()); assert(vaultBalance.eq(tokenAOfferedAmount)); @@ -218,7 +171,7 @@ describe('Escrow Bankrun example', () => { // We'll call this function from multiple tests, so let's seperate it out const take = async () => { - const transactionSignature = await program.methods + const _transactionSignature = await program.methods .takeOffer() .accounts({ ...accounts }) .signers([bob]) @@ -226,38 +179,22 @@ describe('Escrow Bankrun example', () => { // Check the offered tokens are now in Bob's account // (note: there is no before balance as Bob didn't have any offered tokens before the transaction) - const bobTokenAccountInfo = await connection.getAccountInfo( - accounts.takerTokenAccountA, - ); - const bobTokenAccount = unpackAccount( - accounts.takerTokenAccountA, - bobTokenAccountInfo, - TOKEN_PROGRAM, - ); - - const bobTokenAccountBalanceAfter = new BN( - bobTokenAccount.amount.toString(), - ); + const bobTokenAccountInfo = await connection.getAccountInfo(accounts.takerTokenAccountA); + const bobTokenAccount = unpackAccount(accounts.takerTokenAccountA, bobTokenAccountInfo, TOKEN_PROGRAM); + + const bobTokenAccountBalanceAfter = new BN(bobTokenAccount.amount.toString()); assert(bobTokenAccountBalanceAfter.eq(tokenAOfferedAmount)); // Check the wanted tokens are now in Alice's account // (note: there is no before balance as Alice didn't have any wanted tokens before the transaction) - const aliceTokenAccountInfo = await connection.getAccountInfo( - accounts.makerTokenAccountB, - ); - const aliceTokenAccount = unpackAccount( - accounts.makerTokenAccountB, - aliceTokenAccountInfo, - TOKEN_PROGRAM, - ); - - const aliceTokenAccountBalanceAfter = new BN( - aliceTokenAccount.amount.toString(), - ); + const aliceTokenAccountInfo = await connection.getAccountInfo(accounts.makerTokenAccountB); + const aliceTokenAccount = unpackAccount(accounts.makerTokenAccountB, aliceTokenAccountInfo, TOKEN_PROGRAM); + + const aliceTokenAccountBalanceAfter = new BN(aliceTokenAccount.amount.toString()); assert(aliceTokenAccountBalanceAfter.eq(tokenBWantedAmount)); }; - it('Puts the tokens Alice offers into the vault when Alice makes an offer', async () => { + it("Puts the tokens Alice offers into the vault when Alice makes an offer", async () => { await make(); }); diff --git a/tokens/escrow/anchor/tests/escrow.test.ts b/tokens/escrow/anchor/tests/escrow.test.ts index db5f9d96a..c9d44bf7f 100644 --- a/tokens/escrow/anchor/tests/escrow.test.ts +++ b/tokens/escrow/anchor/tests/escrow.test.ts @@ -1,23 +1,16 @@ -import { randomBytes } from 'node:crypto'; -import anchor from '@anchor-lang/core'; +import { randomBytes } from "node:crypto"; +import anchor from "@anchor-lang/core"; + const BN = anchor.BN; -import { - getAssociatedTokenAddressSync, - TOKEN_2022_PROGRAM_ID, - type TOKEN_PROGRAM_ID, -} from '@solana/spl-token'; -import { LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js'; -import { - confirmTransaction, - createAccountsMintsAndTokenAccounts, - makeKeypairs, -} from '@solana-developers/helpers'; -import { assert } from 'chai'; -import type { Escrow } from '../target/types/escrow'; + +import { getAssociatedTokenAddressSync, TOKEN_2022_PROGRAM_ID, type TOKEN_PROGRAM_ID } from "@solana/spl-token"; +import { LAMPORTS_PER_SOL, PublicKey } from "@solana/web3.js"; +import { confirmTransaction, createAccountsMintsAndTokenAccounts, makeKeypairs } from "@solana-developers/helpers"; +import { assert } from "chai"; +import type { Escrow } from "../target/types/escrow"; // Work on both Token Program and new Token Extensions Program -const TOKEN_PROGRAM: typeof TOKEN_2022_PROGRAM_ID | typeof TOKEN_PROGRAM_ID = - TOKEN_2022_PROGRAM_ID; +const TOKEN_PROGRAM: typeof TOKEN_2022_PROGRAM_ID | typeof TOKEN_PROGRAM_ID = TOKEN_2022_PROGRAM_ID; const SECONDS = 1000; @@ -30,7 +23,7 @@ const getRandomBigNumber = (size = 8) => { return new BN(randomBytes(size)); }; -describe('escrow', async () => { +describe("escrow", async () => { // Use the cluster and the keypair from Anchor.toml const provider = anchor.AnchorProvider.env(); anchor.setProvider(provider); @@ -59,30 +52,29 @@ describe('escrow', async () => { const tokenBWantedAmount = new BN(1_000_000); before( - 'Creates Alice and Bob accounts, 2 token mints, and associated token accounts for both tokens for both users', + "Creates Alice and Bob accounts, 2 token mints, and associated token accounts for both tokens for both users", async () => { - const usersMintsAndTokenAccounts = - await createAccountsMintsAndTokenAccounts( + const usersMintsAndTokenAccounts = await createAccountsMintsAndTokenAccounts( + [ + // Alice's token balances + [ + // 1_000_000_000 of token A + 1_000_000_000, + // 0 of token B + 0, + ], + // Bob's token balances [ - // Alice's token balances - [ - // 1_000_000_000 of token A - 1_000_000_000, - // 0 of token B - 0, - ], - // Bob's token balances - [ - // 0 of token A - 0, - // 1_000_000_000 of token B - 1_000_000_000, - ], + // 0 of token A + 0, + // 1_000_000_000 of token B + 1_000_000_000, ], - 1 * LAMPORTS_PER_SOL, - connection, - payer, - ); + ], + 1 * LAMPORTS_PER_SOL, + connection, + payer, + ); // Alice will be the maker (creator) of the offer // Bob will be the taker (acceptor) of the offer @@ -120,26 +112,17 @@ describe('escrow', async () => { }, ); - it('Puts the tokens Alice offers into the vault when Alice makes an offer', async () => { + it("Puts the tokens Alice offers into the vault when Alice makes an offer", async () => { // Pick a random ID for the offer we'll make const offerId = getRandomBigNumber(); // Then determine the account addresses we'll use for the offer and the vault const offer = PublicKey.findProgramAddressSync( - [ - Buffer.from('offer'), - accounts.maker.toBuffer(), - offerId.toArrayLike(Buffer, 'le', 8), - ], + [Buffer.from("offer"), accounts.maker.toBuffer(), offerId.toArrayLike(Buffer, "le", 8)], program.programId, )[0]; - const vault = getAssociatedTokenAddressSync( - accounts.tokenMintA, - offer, - true, - TOKEN_PROGRAM, - ); + const vault = getAssociatedTokenAddressSync(accounts.tokenMintA, offer, true, TOKEN_PROGRAM); accounts.offer = offer; accounts.vault = vault; @@ -177,20 +160,14 @@ describe('escrow', async () => { // Check the offered tokens are now in Bob's account // (note: there is no before balance as Bob didn't have any offered tokens before the transaction) - const bobTokenAccountBalanceAfterResponse = - await connection.getTokenAccountBalance(accounts.takerTokenAccountA); - const bobTokenAccountBalanceAfter = new BN( - bobTokenAccountBalanceAfterResponse.value.amount, - ); + const bobTokenAccountBalanceAfterResponse = await connection.getTokenAccountBalance(accounts.takerTokenAccountA); + const bobTokenAccountBalanceAfter = new BN(bobTokenAccountBalanceAfterResponse.value.amount); assert(bobTokenAccountBalanceAfter.eq(tokenAOfferedAmount)); // Check the wanted tokens are now in Alice's account // (note: there is no before balance as Alice didn't have any wanted tokens before the transaction) - const aliceTokenAccountBalanceAfterResponse = - await connection.getTokenAccountBalance(accounts.makerTokenAccountB); - const aliceTokenAccountBalanceAfter = new BN( - aliceTokenAccountBalanceAfterResponse.value.amount, - ); + const aliceTokenAccountBalanceAfterResponse = await connection.getTokenAccountBalance(accounts.makerTokenAccountB); + const aliceTokenAccountBalanceAfter = new BN(aliceTokenAccountBalanceAfterResponse.value.amount); assert(aliceTokenAccountBalanceAfter.eq(tokenBWantedAmount)); }).slow(ANCHOR_SLOW_TEST_THRESHOLD); }); diff --git a/tokens/escrow/native/tests/account.ts b/tokens/escrow/native/tests/account.ts index 507ad647c..0e88dc80b 100644 --- a/tokens/escrow/native/tests/account.ts +++ b/tokens/escrow/native/tests/account.ts @@ -1,13 +1,13 @@ -import * as borsh from 'borsh'; +import * as borsh from "borsh"; export const OfferSchema = { struct: { - id: 'u64', - maker: { array: { type: 'u8', len: 32 } }, - token_mint_a: { array: { type: 'u8', len: 32 } }, - token_mint_b: { array: { type: 'u8', len: 32 } }, - token_b_wanted_amount: 'u64', - bump: 'u8', + id: "u64", + maker: { array: { type: "u8", len: 32 } }, + token_mint_a: { array: { type: "u8", len: 32 } }, + token_mint_b: { array: { type: "u8", len: 32 } }, + token_b_wanted_amount: "u64", + bump: "u8", }, }; diff --git a/tokens/escrow/native/tests/instruction.ts b/tokens/escrow/native/tests/instruction.ts index 7b033c089..19fa0e753 100644 --- a/tokens/escrow/native/tests/instruction.ts +++ b/tokens/escrow/native/tests/instruction.ts @@ -1,7 +1,7 @@ -import { ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_PROGRAM_ID } from '@solana/spl-token'; -import { PublicKey, SystemProgram, TransactionInstruction } from '@solana/web3.js'; -import BN from 'bn.js'; -import * as borsh from 'borsh'; +import { ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_PROGRAM_ID } from "@solana/spl-token"; +import { type PublicKey, SystemProgram, TransactionInstruction } from "@solana/web3.js"; +import type BN from "bn.js"; +import * as borsh from "borsh"; enum EscrowInstruction { MakeOffer = 0, @@ -10,16 +10,16 @@ enum EscrowInstruction { const MakeOfferSchema = { struct: { - instruction: 'u8', - id: 'u64', - token_a_offered_amount: 'u64', - token_b_wanted_amount: 'u64', + instruction: "u8", + id: "u64", + token_a_offered_amount: "u64", + token_b_wanted_amount: "u64", }, }; const TakeOfferSchema = { struct: { - instruction: 'u8', + instruction: "u8", }, }; @@ -57,7 +57,11 @@ export function buildMakeOffer(props: { { pubkey: props.maker, isSigner: true, isWritable: true }, { pubkey: props.payer, isSigner: true, isWritable: true }, { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false }, - { pubkey: ASSOCIATED_TOKEN_PROGRAM_ID, isSigner: false, isWritable: false }, + { + pubkey: ASSOCIATED_TOKEN_PROGRAM_ID, + isSigner: false, + isWritable: false, + }, { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, ], programId: props.programId, @@ -95,7 +99,11 @@ export function buildTakeOffer(props: { { pubkey: props.taker, isSigner: true, isWritable: true }, { pubkey: props.payer, isSigner: true, isWritable: true }, { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false }, - { pubkey: ASSOCIATED_TOKEN_PROGRAM_ID, isSigner: false, isWritable: false }, + { + pubkey: ASSOCIATED_TOKEN_PROGRAM_ID, + isSigner: false, + isWritable: false, + }, { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }, ], programId: props.programId, diff --git a/tokens/escrow/native/tests/test.ts b/tokens/escrow/native/tests/test.ts index 5ae49b304..62f40bad9 100644 --- a/tokens/escrow/native/tests/test.ts +++ b/tokens/escrow/native/tests/test.ts @@ -1,17 +1,17 @@ -import { describe, test } from 'node:test'; -import { AccountLayout } from '@solana/spl-token'; -import { PublicKey, Transaction } from '@solana/web3.js'; -import { assert } from 'chai'; -import { start } from 'solana-bankrun'; -import * as borsh from 'borsh'; -import { OfferSchema, type OfferRaw } from './account'; -import { buildMakeOffer, buildTakeOffer } from './instruction'; -import { createValues, mintingTokens } from './utils'; - -describe('Escrow!', async () => { +import { describe, test } from "node:test"; +import { AccountLayout } from "@solana/spl-token"; +import { PublicKey, Transaction } from "@solana/web3.js"; +import * as borsh from "borsh"; +import { assert } from "chai"; +import { start } from "solana-bankrun"; +import { type OfferRaw, OfferSchema } from "./account"; +import { buildMakeOffer, buildTakeOffer } from "./instruction"; +import { createValues, mintingTokens } from "./utils"; + +describe("Escrow!", async () => { const values = createValues(); - const context = await start([{ name: 'escrow_native_program', programId: values.programId }], []); + const context = await start([{ name: "escrow_native_program", programId: values.programId }], []); const client = context.banksClient; const payer = context.payer; @@ -19,7 +19,7 @@ describe('Escrow!', async () => { console.log(`Program Address : ${values.programId}`); console.log(`Payer Address : ${payer.publicKey}`); - test('mint tokens to maker and taker', async () => { + test("mint tokens to maker and taker", async () => { // mint token a to maker account await mintingTokens({ context, @@ -35,7 +35,7 @@ describe('Escrow!', async () => { }); }); - test('Make Offer', async () => { + test("Make Offer", async () => { const ix = buildMakeOffer({ id: values.id, maker: values.maker.publicKey, @@ -63,16 +63,16 @@ describe('Escrow!', async () => { const vaultInfo = await client.getAccount(values.vault); const vaultTokenAccount = AccountLayout.decode(vaultInfo.data); - assert(offer.id.toString() === values.id.toString(), 'wrong id'); + assert(offer.id.toString() === values.id.toString(), "wrong id"); // borsh deserializes pubkeys as raw byte arrays, wrap in PublicKey for comparison - assert(new PublicKey(offer.maker).toBase58() === values.maker.publicKey.toBase58(), 'maker key does not match'); - assert(new PublicKey(offer.token_mint_a).toBase58() === values.mintAKeypair.publicKey.toBase58(), 'wrong mint A'); - assert(new PublicKey(offer.token_mint_b).toBase58() === values.mintBKeypair.publicKey.toBase58(), 'wrong mint B'); - assert(offer.token_b_wanted_amount.toString() === values.amountB.toString(), 'unexpected amount B'); - assert(vaultTokenAccount.amount.toString() === values.amountA.toString(), 'unexpected amount A'); + assert(new PublicKey(offer.maker).toBase58() === values.maker.publicKey.toBase58(), "maker key does not match"); + assert(new PublicKey(offer.token_mint_a).toBase58() === values.mintAKeypair.publicKey.toBase58(), "wrong mint A"); + assert(new PublicKey(offer.token_mint_b).toBase58() === values.mintBKeypair.publicKey.toBase58(), "wrong mint B"); + assert(offer.token_b_wanted_amount.toString() === values.amountB.toString(), "unexpected amount B"); + assert(vaultTokenAccount.amount.toString() === values.amountA.toString(), "unexpected amount A"); }); - test('Take Offer', async () => { + test("Take Offer", async () => { const ix = buildTakeOffer({ maker: values.maker.publicKey, offer: values.offer, @@ -95,10 +95,10 @@ describe('Escrow!', async () => { await client.processTransaction(tx); const offerInfo = await client.getAccount(values.offer); - assert(offerInfo === null, 'offer account not closed'); + assert(offerInfo === null, "offer account not closed"); const vaultInfo = await client.getAccount(values.vault); - assert(vaultInfo === null, 'vault account not closed'); + assert(vaultInfo === null, "vault account not closed"); const makerTokenBInfo = await client.getAccount(values.makerAccountB); const makerTokenAccountB = AccountLayout.decode(makerTokenBInfo.data); @@ -106,7 +106,7 @@ describe('Escrow!', async () => { const takerTokenAInfo = await client.getAccount(values.takerAccountA); const takerTokenAccountA = AccountLayout.decode(takerTokenAInfo.data); - assert(takerTokenAccountA.amount.toString() === values.amountA.toString(), 'unexpected amount a'); - assert(makerTokenAccountB.amount.toString() === values.amountB.toString(), 'unexpected amount b'); + assert(takerTokenAccountA.amount.toString() === values.amountA.toString(), "unexpected amount a"); + assert(makerTokenAccountB.amount.toString() === values.amountB.toString(), "unexpected amount b"); }); }); diff --git a/tokens/escrow/native/tests/utils.ts b/tokens/escrow/native/tests/utils.ts index b21d7d1ef..57da01343 100644 --- a/tokens/escrow/native/tests/utils.ts +++ b/tokens/escrow/native/tests/utils.ts @@ -6,19 +6,19 @@ import { getAssociatedTokenAddressSync, MINT_SIZE, TOKEN_PROGRAM_ID, -} from '@solana/spl-token'; -import { Keypair, PublicKey, type Signer, SystemProgram, Transaction } from '@solana/web3.js'; -import BN from 'bn.js'; -import { ProgramTestContext } from 'solana-bankrun'; +} from "@solana/spl-token"; +import { Keypair, PublicKey, type Signer, SystemProgram, Transaction } from "@solana/web3.js"; +import BN from "bn.js"; +import type { ProgramTestContext } from "solana-bankrun"; export async function sleep(seconds: number) { new Promise((resolve) => setTimeout(resolve, seconds * 1000)); } -export const expectRevert = async (promise: Promise) => { +export const expectRevert = async (promise: Promise) => { try { await promise; - throw new Error('Expected a revert'); + throw new Error("Expected a revert"); } catch { return; } @@ -50,7 +50,13 @@ export const mintingTokens = async ({ lamports: new BN(lamports.toString()).toNumber(), programId: TOKEN_PROGRAM_ID, }), - createInitializeMint2Instruction(mint.publicKey, decimals, context.payer.publicKey, context.payer.publicKey, TOKEN_PROGRAM_ID), + createInitializeMint2Instruction( + mint.publicKey, + decimals, + context.payer.publicKey, + context.payer.publicKey, + TOKEN_PROGRAM_ID, + ), ); transaction.recentBlockhash = context.lastBlockhash; transaction.sign(context.payer, mint); @@ -82,7 +88,9 @@ export const mintingTokens = async ({ } async function mintTo(context: ProgramTestContext, mint: PublicKey, destination: PublicKey, amount: number | bigint) { - const transaction = new Transaction().add(createMintToInstruction(mint, destination, context.payer.publicKey, amount, [], TOKEN_PROGRAM_ID)); + const transaction = new Transaction().add( + createMintToInstruction(mint, destination, context.payer.publicKey, amount, [], TOKEN_PROGRAM_ID), + ); transaction.recentBlockhash = context.lastBlockhash; transaction.sign(context.payer); @@ -138,7 +146,10 @@ export function createValues(defaults?: TestValuesDefaults): TestValues { mintBKeypair = Keypair.generate(); } - const offer = PublicKey.findProgramAddressSync([Buffer.from('offer'), maker.publicKey.toBuffer(), Buffer.from(id.toArray('le', 8))], programId)[0]; + const offer = PublicKey.findProgramAddressSync( + [Buffer.from("offer"), maker.publicKey.toBuffer(), Buffer.from(id.toArray("le", 8))], + programId, + )[0]; return { id, diff --git a/tokens/external-delegate-token-master/anchor/package.json b/tokens/external-delegate-token-master/anchor/package.json index 7b479380b..3d30046da 100644 --- a/tokens/external-delegate-token-master/anchor/package.json +++ b/tokens/external-delegate-token-master/anchor/package.json @@ -1,35 +1,35 @@ { - "type": "module", - "name": "external-delegate-token-master", - "version": "1.0.0", - "license": "MIT", - "scripts": { - "test": "jest --detectOpenHandles --forceExit", - "test:watch": "jest --watch", - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check", - "build": "anchor build" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.3.9", - "@solana/web3.js": "^1.98.4", - "ethers": "^5.7.2" - }, - "devDependencies": { - "@babel/core": "^7.23.7", - "@babel/preset-env": "^7.23.7", - "@babel/preset-typescript": "^7.23.7", - "@testing-library/jest-dom": "^6.1.6", - "@types/chai": "^4.3.0", - "@types/jest": "^29.5.11", - "@types/node": "^18.0.0", - "babel-jest": "^29.7.0", - "chai": "^4.3.4", - "jest": "^29.7.0", - "prettier": "^2.6.2", - "solana-bankrun": "^0.2.0", - "ts-jest": "^29.1.1", - "typescript": "^5.3.3" - } + "type": "module", + "name": "external-delegate-token-master", + "version": "1.0.0", + "license": "MIT", + "scripts": { + "test": "jest --detectOpenHandles --forceExit", + "test:watch": "jest --watch", + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check", + "build": "anchor build" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.3.9", + "@solana/web3.js": "^1.98.4", + "ethers": "^5.7.2" + }, + "devDependencies": { + "@babel/core": "^7.23.7", + "@babel/preset-env": "^7.23.7", + "@babel/preset-typescript": "^7.23.7", + "@testing-library/jest-dom": "^6.1.6", + "@types/chai": "^4.3.0", + "@types/jest": "^29.5.11", + "@types/node": "^18.0.0", + "babel-jest": "^29.7.0", + "chai": "^4.3.4", + "jest": "^29.7.0", + "prettier": "^2.6.2", + "solana-bankrun": "^0.2.0", + "ts-jest": "^29.1.1", + "typescript": "^5.3.3" + } } diff --git a/tokens/external-delegate-token-master/anchor/tests/external-delegate-token-master.test.ts b/tokens/external-delegate-token-master/anchor/tests/external-delegate-token-master.test.ts index 3b9334897..713f9db17 100644 --- a/tokens/external-delegate-token-master/anchor/tests/external-delegate-token-master.test.ts +++ b/tokens/external-delegate-token-master/anchor/tests/external-delegate-token-master.test.ts @@ -1,12 +1,13 @@ -import { createMint, getOrCreateAssociatedTokenAccount, mintTo } from '@solana/spl-token'; -import { Connection, Keypair, PublicKey, SystemProgram } from '@solana/web3.js'; -import { expect } from 'chai'; -import { start } from 'solana-bankrun'; +import { createMint, getOrCreateAssociatedTokenAccount, mintTo } from "@solana/spl-token"; +import { Connection, Keypair, PublicKey, SystemProgram } from "@solana/web3.js"; +import { expect } from "chai"; +import { start } from "solana-bankrun"; jest.setTimeout(30000); // Set timeout to 30 seconds const ACCOUNT_SIZE = 8 + 32 + 20; // Define your account size here +// biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 async function retryWithBackoff(fn: () => Promise, retries = 5, delay = 500): Promise { try { return await fn(); @@ -17,8 +18,10 @@ async function retryWithBackoff(fn: () => Promise, retries = 5, delay = 500 } } -describe('External Delegate Token Master Tests', () => { +describe("External Delegate Token Master Tests", () => { + // biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 let context: any; + // biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 let _program: any; let authority: Keypair; let userAccount: Keypair; @@ -34,15 +37,15 @@ describe('External Delegate Token Master Tests', () => { const programs = [ { - name: 'external_delegate_token_master', - programId: new PublicKey('FYPkt5VWMvtyWZDMGCwoKFkE3wXTzphicTpnNGuHWVbD'), - program: 'target/deploy/external_delegate_token_master.so', + name: "external_delegate_token_master", + programId: new PublicKey("FYPkt5VWMvtyWZDMGCwoKFkE3wXTzphicTpnNGuHWVbD"), + program: "target/deploy/external_delegate_token_master.so", }, ]; context = await retryWithBackoff(async () => await start(programs, [])); - const connection = new Connection('https://api.devnet.solana.com', 'confirmed'); + const connection = new Connection("https://api.devnet.solana.com", "confirmed"); context.connection = connection; // Airdrop SOL to authority with retry logic @@ -64,7 +67,9 @@ describe('External Delegate Token Master Tests', () => { _recipientTokenAccount = recipientTokenAccountInfo.address; // Mint tokens to the user's account - await retryWithBackoff(async () => await mintTo(connection, authority, mint, userTokenAccount, authority, 1000000000)); + await retryWithBackoff( + async () => await mintTo(connection, authority, mint, userTokenAccount, authority, 1000000000), + ); // Find program-derived address (PDA) [_userPda, _bumpSeed] = await retryWithBackoff( @@ -72,7 +77,7 @@ describe('External Delegate Token Master Tests', () => { ); }); - it('should initialize user account', async () => { + it("should initialize user account", async () => { const space = ACCOUNT_SIZE; const rentExempt = await retryWithBackoff(async () => { return await context.connection.getMinimumBalanceForRentExemption(space); @@ -102,8 +107,8 @@ describe('External Delegate Token Master Tests', () => { expect(account.ethereumAddress).to.deep.equal(new Array(20).fill(0)); }); - it('should set ethereum address', async () => { - const ethereumAddress = Buffer.from('1C8cd0c38F8DE35d6056c7C7aBFa7e65D260E816', 'hex'); + it("should set ethereum address", async () => { + const ethereumAddress = Buffer.from("1C8cd0c38F8DE35d6056c7C7aBFa7e65D260E816", "hex"); await context.program.methods .setEthereumAddress(ethereumAddress) @@ -118,7 +123,7 @@ describe('External Delegate Token Master Tests', () => { expect(account.ethereumAddress).to.deep.equal(Array.from(ethereumAddress)); }); - it('should perform authority transfer', async () => { + it("should perform authority transfer", async () => { const newAuthority = Keypair.generate(); await context.program.methods @@ -135,7 +140,7 @@ describe('External Delegate Token Master Tests', () => { }); afterEach(async () => { - if (context && typeof context.terminate === 'function') { + if (context && typeof context.terminate === "function") { await context.terminate(); } }); diff --git a/tokens/external-delegate-token-master/anchor/tests/types.ts b/tokens/external-delegate-token-master/anchor/tests/types.ts index 191287b59..af8faa3a2 100644 --- a/tokens/external-delegate-token-master/anchor/tests/types.ts +++ b/tokens/external-delegate-token-master/anchor/tests/types.ts @@ -1,7 +1,8 @@ // tests/types.ts -import { PublicKey } from '@solana/web3.js'; +import type { PublicKey } from "@solana/web3.js"; export interface ProgramTestContext { + // biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 connection: any; programs: { programId: PublicKey; diff --git a/tokens/nft-minter/anchor/package.json b/tokens/nft-minter/anchor/package.json index 3b548a433..4cecf0fbc 100644 --- a/tokens/nft-minter/anchor/package.json +++ b/tokens/nft-minter/anchor/package.json @@ -1,20 +1,20 @@ { - "type": "module", - "scripts": { - "postinstall": "zx prepare.mjs" - }, - "devDependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.3.11", - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "anchor-bankrun": "^0.4.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "solana-bankrun": "^0.3.0", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3", - "zx": "^8.1.4" - } + "type": "module", + "scripts": { + "postinstall": "zx prepare.mjs" + }, + "devDependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.3.11", + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "anchor-bankrun": "^0.4.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "solana-bankrun": "^0.3.0", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3", + "zx": "^8.1.4" + } } diff --git a/tokens/nft-minter/anchor/prepare.mjs b/tokens/nft-minter/anchor/prepare.mjs index 7c5ec464b..fb6b26225 100644 --- a/tokens/nft-minter/anchor/prepare.mjs +++ b/tokens/nft-minter/anchor/prepare.mjs @@ -1,17 +1,17 @@ #!/usr/bin/env zx -import { mkdir, rm } from 'node:fs/promises'; -import { join } from 'node:path'; -import { $ } from 'zx'; +import { mkdir, rm } from "node:fs/promises"; +import { join } from "node:path"; +import { $ } from "zx"; const programs = [ { - id: 'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s', - name: 'token_metadata.so', + id: "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s", + name: "token_metadata.so", }, ]; -const outputDir = 'tests/fixtures'; +const outputDir = "tests/fixtures"; const overwrite = true; try { diff --git a/tokens/nft-minter/anchor/tests/bankrun.test.ts b/tokens/nft-minter/anchor/tests/bankrun.test.ts index 77a9e535a..63958d563 100644 --- a/tokens/nft-minter/anchor/tests/bankrun.test.ts +++ b/tokens/nft-minter/anchor/tests/bankrun.test.ts @@ -8,9 +8,7 @@ import type { NftMinter } from "../target/types/nft_minter"; // Use require() for JSON import — "import ... with { type: "json" }" needs TS 5.3+ const IDL = require("../target/idl/nft_minter.json"); const PROGRAM_ID = new PublicKey(IDL.address); -const METADATA_PROGRAM_ID = new PublicKey( - "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s", -); +const METADATA_PROGRAM_ID = new PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"); describe("NFT bankrun Minter", async () => { const context = await startAnchor( @@ -38,10 +36,7 @@ describe("NFT bankrun Minter", async () => { const mintKeypair = new Keypair(); // Derive the associated token address account for the mint and payer. - const associatedTokenAccountAddress = getAssociatedTokenAddressSync( - mintKeypair.publicKey, - payer.publicKey, - ); + const associatedTokenAccountAddress = getAssociatedTokenAddressSync(mintKeypair.publicKey, payer.publicKey); const transactionSignature = await program.methods .mintNft(metadata.name, metadata.symbol, metadata.uri) diff --git a/tokens/nft-minter/anchor/tests/test.ts b/tokens/nft-minter/anchor/tests/test.ts index 4b0bd3fda..08d3f3453 100644 --- a/tokens/nft-minter/anchor/tests/test.ts +++ b/tokens/nft-minter/anchor/tests/test.ts @@ -1,9 +1,9 @@ -import * as anchor from '@anchor-lang/core'; -import { getAssociatedTokenAddressSync } from '@solana/spl-token'; -import { Keypair } from '@solana/web3.js'; -import type { NftMinter } from '../target/types/nft_minter'; +import * as anchor from "@anchor-lang/core"; +import { getAssociatedTokenAddressSync } from "@solana/spl-token"; +import { Keypair } from "@solana/web3.js"; +import type { NftMinter } from "../target/types/nft_minter"; -describe('NFT Minter', () => { +describe("NFT Minter", () => { const provider = anchor.AnchorProvider.env(); anchor.setProvider(provider); const payer = provider.wallet as anchor.Wallet; @@ -11,12 +11,12 @@ describe('NFT Minter', () => { // The metadata for our NFT const metadata = { - name: 'Homer NFT', - symbol: 'HOMR', - uri: 'https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/nft.json', + name: "Homer NFT", + symbol: "HOMR", + uri: "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/nft.json", }; - it('Create an NFT!', async () => { + it("Create an NFT!", async () => { // Generate a keypair to use as the address of our mint account const mintKeypair = new Keypair(); @@ -33,7 +33,7 @@ describe('NFT Minter', () => { .signers([mintKeypair]) .rpc({ skipPreflight: true }); - console.log('Success!'); + console.log("Success!"); console.log(` Mint Address: ${mintKeypair.publicKey}`); console.log(` Transaction Signature: ${transactionSignature}`); }); diff --git a/tokens/nft-minter/native/tests/instructions.ts b/tokens/nft-minter/native/tests/instructions.ts index 72e047d58..91caed0d2 100644 --- a/tokens/nft-minter/native/tests/instructions.ts +++ b/tokens/nft-minter/native/tests/instructions.ts @@ -1,4 +1,4 @@ -import * as borsh from 'borsh'; +import * as borsh from "borsh"; export enum NftMinterInstruction { Create = 0, @@ -7,14 +7,14 @@ export enum NftMinterInstruction { export const CreateTokenArgsSchema = { struct: { - instruction: 'u8', - token_title: 'string', - token_symbol: 'string', - token_uri: 'string', + instruction: "u8", + token_title: "string", + token_symbol: "string", + token_uri: "string", }, }; -export const MintToArgsSchema = { struct: { instruction: 'u8' } }; +export const MintToArgsSchema = { struct: { instruction: "u8" } }; export function borshSerialize(schema: borsh.Schema, data: object): Buffer { return Buffer.from(borsh.serialize(schema, data)); diff --git a/tokens/nft-minter/native/tests/test.ts b/tokens/nft-minter/native/tests/test.ts index cc26800f9..040f11cc5 100644 --- a/tokens/nft-minter/native/tests/test.ts +++ b/tokens/nft-minter/native/tests/test.ts @@ -1,6 +1,6 @@ -import { Buffer } from 'node:buffer'; -import { PROGRAM_ID as TOKEN_METADATA_PROGRAM_ID } from '@metaplex-foundation/mpl-token-metadata'; -import { ASSOCIATED_TOKEN_PROGRAM_ID, getAssociatedTokenAddress, TOKEN_PROGRAM_ID } from '@solana/spl-token'; +import { Buffer } from "node:buffer"; +import { PROGRAM_ID as TOKEN_METADATA_PROGRAM_ID } from "@metaplex-foundation/mpl-token-metadata"; +import { ASSOCIATED_TOKEN_PROGRAM_ID, getAssociatedTokenAddress, TOKEN_PROGRAM_ID } from "@solana/spl-token"; import { Connection, Keypair, @@ -10,32 +10,33 @@ import { sendAndConfirmTransaction, Transaction, TransactionInstruction, -} from '@solana/web3.js'; -import { borshSerialize, CreateTokenArgsSchema, MintToArgsSchema, NftMinterInstruction } from './instructions'; +} from "@solana/web3.js"; +import { borshSerialize, CreateTokenArgsSchema, MintToArgsSchema, NftMinterInstruction } from "./instructions"; function createKeypairFromFile(path: string): Keypair { - return Keypair.fromSecretKey(Uint8Array.from(JSON.parse(require('node:fs').readFileSync(path, 'utf-8')))); + return Keypair.fromSecretKey(Uint8Array.from(JSON.parse(require("node:fs").readFileSync(path, "utf-8")))); } -describe('NFT Minter', async () => { +describe("NFT Minter", async () => { // const connection = new Connection(`http://localhost:8899`, 'confirmed'); - const connection = new Connection('https://api.devnet.solana.com/', 'confirmed'); - const payer = createKeypairFromFile(`${require('node:os').homedir()}/.config/solana/id.json`); - const program = createKeypairFromFile('./program/target/deploy/program-keypair.json'); + const connection = new Connection("https://api.devnet.solana.com/", "confirmed"); + const payer = createKeypairFromFile(`${require("node:os").homedir()}/.config/solana/id.json`); + const program = createKeypairFromFile("./program/target/deploy/program-keypair.json"); const mintKeypair: Keypair = Keypair.generate(); - it('Create an NFT!', async () => { + it("Create an NFT!", async () => { const metadataAddress = PublicKey.findProgramAddressSync( - [Buffer.from('metadata'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mintKeypair.publicKey.toBuffer()], + [Buffer.from("metadata"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mintKeypair.publicKey.toBuffer()], TOKEN_METADATA_PROGRAM_ID, )[0]; const instructionData = borshSerialize(CreateTokenArgsSchema, { instruction: NftMinterInstruction.Create, - nft_title: 'Homer NFT', - nft_symbol: 'HOMR', - nft_uri: 'https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/nft.json', + nft_title: "Homer NFT", + nft_symbol: "HOMR", + nft_uri: + "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/nft.json", }); const ix = new TransactionInstruction({ @@ -59,19 +60,24 @@ describe('NFT Minter', async () => { const sx = await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer, mintKeypair]); - console.log('Success!'); + console.log("Success!"); console.log(` Mint Address: ${mintKeypair.publicKey}`); console.log(` Tx Signature: ${sx}`); }); - it('Mint the NFT to your wallet!', async () => { + it("Mint the NFT to your wallet!", async () => { const metadataAddress = PublicKey.findProgramAddressSync( - [Buffer.from('metadata'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mintKeypair.publicKey.toBuffer()], + [Buffer.from("metadata"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mintKeypair.publicKey.toBuffer()], TOKEN_METADATA_PROGRAM_ID, )[0]; const editionAddress = PublicKey.findProgramAddressSync( - [Buffer.from('metadata'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mintKeypair.publicKey.toBuffer(), Buffer.from('edition')], + [ + Buffer.from("metadata"), + TOKEN_METADATA_PROGRAM_ID.toBuffer(), + mintKeypair.publicKey.toBuffer(), + Buffer.from("edition"), + ], TOKEN_METADATA_PROGRAM_ID, )[0]; @@ -113,7 +119,7 @@ describe('NFT Minter', async () => { const sx = await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer]); - console.log('Success!'); + console.log("Success!"); console.log(` ATA Address: ${associatedTokenAccountAddress}`); console.log(` Tx Signature: ${sx}`); }); diff --git a/tokens/nft-operations/anchor/package.json b/tokens/nft-operations/anchor/package.json index d0d9862f2..903bf47bc 100644 --- a/tokens/nft-operations/anchor/package.json +++ b/tokens/nft-operations/anchor/package.json @@ -1,29 +1,29 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check", - "postinstall": "zx prepare.mjs" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@metaplex-foundation/mpl-token-metadata": "^3.1.2", - "@metaplex-foundation/umi": "^0.9.0", - "@solana/spl-token": "^0.4.6", - "axios": "^1.6.7", - "node-fetch": "^3.3.2" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "anchor-bankrun": "^0.4.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "solana-bankrun": "^0.3.0", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3", - "zx": "^8.1.4" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check", + "postinstall": "zx prepare.mjs" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@metaplex-foundation/mpl-token-metadata": "^3.1.2", + "@metaplex-foundation/umi": "^0.9.0", + "@solana/spl-token": "^0.4.6", + "axios": "^1.6.7", + "node-fetch": "^3.3.2" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "anchor-bankrun": "^0.4.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "solana-bankrun": "^0.3.0", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3", + "zx": "^8.1.4" + } } diff --git a/tokens/nft-operations/anchor/prepare.mjs b/tokens/nft-operations/anchor/prepare.mjs index 7c5ec464b..fb6b26225 100644 --- a/tokens/nft-operations/anchor/prepare.mjs +++ b/tokens/nft-operations/anchor/prepare.mjs @@ -1,17 +1,17 @@ #!/usr/bin/env zx -import { mkdir, rm } from 'node:fs/promises'; -import { join } from 'node:path'; -import { $ } from 'zx'; +import { mkdir, rm } from "node:fs/promises"; +import { join } from "node:path"; +import { $ } from "zx"; const programs = [ { - id: 'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s', - name: 'token_metadata.so', + id: "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s", + name: "token_metadata.so", }, ]; -const outputDir = 'tests/fixtures'; +const outputDir = "tests/fixtures"; const overwrite = true; try { diff --git a/tokens/nft-operations/anchor/tests/bankrun.test.ts b/tokens/nft-operations/anchor/tests/bankrun.test.ts index 4babd06d9..b48ab0d3e 100644 --- a/tokens/nft-operations/anchor/tests/bankrun.test.ts +++ b/tokens/nft-operations/anchor/tests/bankrun.test.ts @@ -1,10 +1,6 @@ import * as anchor from "@anchor-lang/core"; import { ASSOCIATED_PROGRAM_ID } from "@anchor-lang/core/dist/cjs/utils/token"; -import { - ASSOCIATED_TOKEN_PROGRAM_ID, - TOKEN_PROGRAM_ID, - getAssociatedTokenAddressSync, -} from "@solana/spl-token"; +import { ASSOCIATED_TOKEN_PROGRAM_ID, getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID } from "@solana/spl-token"; import { Keypair, PublicKey, SystemProgram } from "@solana/web3.js"; import { BankrunProvider } from "anchor-bankrun"; import { startAnchor } from "solana-bankrun"; @@ -12,166 +8,140 @@ import type { MintNft } from "../target/types/mint_nft"; const IDL = require("../target/idl/mint_nft.json"); const PROGRAM_ID = new PublicKey(IDL.address); -const METADATA_PROGRAM_ID = new PublicKey( - "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s", -); +const METADATA_PROGRAM_ID = new PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"); describe("mint-nft bankrun", async () => { - const context = await startAnchor( - "", - [ - { name: "mint_nft", programId: PROGRAM_ID }, - { name: "token_metadata", programId: METADATA_PROGRAM_ID }, - ], - [], - ); - const provider = new BankrunProvider(context); - anchor.setProvider(provider); - const wallet = provider.wallet as anchor.Wallet; - const program = new anchor.Program(IDL, provider); - - const TOKEN_METADATA_PROGRAM_ID = new anchor.web3.PublicKey( - "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s", - ); - - const mintAuthority = anchor.web3.PublicKey.findProgramAddressSync( - [Buffer.from("authority")], - program.programId, - )[0]; - - const collectionKeypair = Keypair.generate(); - const collectionMint = collectionKeypair.publicKey; - - const mintKeypair = Keypair.generate(); - const mint = mintKeypair.publicKey; - - const getMetadata = async ( - mint: anchor.web3.PublicKey, - ): Promise => { - return anchor.web3.PublicKey.findProgramAddressSync( - [ - Buffer.from("metadata"), - TOKEN_METADATA_PROGRAM_ID.toBuffer(), - mint.toBuffer(), - ], - TOKEN_METADATA_PROGRAM_ID, - )[0]; - }; - - const getMasterEdition = async ( - mint: anchor.web3.PublicKey, - ): Promise => { - return anchor.web3.PublicKey.findProgramAddressSync( - [ - Buffer.from("metadata"), - TOKEN_METADATA_PROGRAM_ID.toBuffer(), - mint.toBuffer(), - Buffer.from("edition"), - ], - TOKEN_METADATA_PROGRAM_ID, - )[0]; - }; - - it("Create Collection NFT", async () => { - console.log("\nCollection Mint Key: ", collectionMint.toBase58()); - - const metadata = await getMetadata(collectionMint); - console.log("Collection Metadata Account: ", metadata.toBase58()); - - const masterEdition = await getMasterEdition(collectionMint); - console.log("Master Edition Account: ", masterEdition.toBase58()); - - const destination = getAssociatedTokenAddressSync( - collectionMint, - wallet.publicKey, - ); - console.log("Destination ATA = ", destination.toBase58()); - - const tx = await program.methods - .createCollection() - .accountsPartial({ - user: wallet.publicKey, - mint: collectionMint, - mintAuthority, - metadata, - masterEdition, - destination, - systemProgram: SystemProgram.programId, - tokenProgram: TOKEN_PROGRAM_ID, - associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID, - tokenMetadataProgram: TOKEN_METADATA_PROGRAM_ID, - }) - .signers([collectionKeypair]) - .rpc({ - skipPreflight: true, - }); - console.log("\nCollection NFT minted: TxID - ", tx); - }); - - it("Mint NFT", async () => { - console.log("\nMint", mint.toBase58()); - - const metadata = await getMetadata(mint); - console.log("Metadata", metadata.toBase58()); - - const masterEdition = await getMasterEdition(mint); - console.log("Master Edition", masterEdition.toBase58()); - - const destination = getAssociatedTokenAddressSync(mint, wallet.publicKey); - console.log("Destination", destination.toBase58()); - - const tx = await program.methods - .mintNft() - .accountsPartial({ - owner: wallet.publicKey, - destination, - metadata, - masterEdition, - mint, - mintAuthority, - collectionMint, - systemProgram: SystemProgram.programId, - tokenProgram: TOKEN_PROGRAM_ID, - associatedTokenProgram: ASSOCIATED_PROGRAM_ID, - tokenMetadataProgram: TOKEN_METADATA_PROGRAM_ID, - }) - .signers([mintKeypair]) - .rpc({ - skipPreflight: true, - }); - console.log("\nNFT Minted! Your transaction signature", tx); - }); - - it("Verify Collection", async () => { - const mintMetadata = await getMetadata(mint); - console.log("\nMint Metadata", mintMetadata.toBase58()); - - const collectionMetadata = await getMetadata(collectionMint); - console.log("Collection Metadata", collectionMetadata.toBase58()); - - const collectionMasterEdition = await getMasterEdition(collectionMint); - console.log( - "Collection Master Edition", - collectionMasterEdition.toBase58(), - ); - - const tx = await program.methods - .verifyCollection() - .accountsPartial({ - authority: wallet.publicKey, - metadata: mintMetadata, - mint, - mintAuthority, - collectionMint, - collectionMetadata, - collectionMasterEdition, - systemProgram: SystemProgram.programId, - sysvarInstruction: anchor.web3.SYSVAR_INSTRUCTIONS_PUBKEY, - tokenMetadataProgram: TOKEN_METADATA_PROGRAM_ID, - }) - .rpc({ - skipPreflight: true, - }); - console.log("\nCollection Verified! Your transaction signature", tx); - }); + const context = await startAnchor( + "", + [ + { name: "mint_nft", programId: PROGRAM_ID }, + { name: "token_metadata", programId: METADATA_PROGRAM_ID }, + ], + [], + ); + const provider = new BankrunProvider(context); + anchor.setProvider(provider); + const wallet = provider.wallet as anchor.Wallet; + const program = new anchor.Program(IDL, provider); + + const TOKEN_METADATA_PROGRAM_ID = new anchor.web3.PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"); + + const mintAuthority = anchor.web3.PublicKey.findProgramAddressSync([Buffer.from("authority")], program.programId)[0]; + + const collectionKeypair = Keypair.generate(); + const collectionMint = collectionKeypair.publicKey; + + const mintKeypair = Keypair.generate(); + const mint = mintKeypair.publicKey; + + const getMetadata = async (mint: anchor.web3.PublicKey): Promise => { + return anchor.web3.PublicKey.findProgramAddressSync( + [Buffer.from("metadata"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mint.toBuffer()], + TOKEN_METADATA_PROGRAM_ID, + )[0]; + }; + + const getMasterEdition = async (mint: anchor.web3.PublicKey): Promise => { + return anchor.web3.PublicKey.findProgramAddressSync( + [Buffer.from("metadata"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mint.toBuffer(), Buffer.from("edition")], + TOKEN_METADATA_PROGRAM_ID, + )[0]; + }; + + it("Create Collection NFT", async () => { + console.log("\nCollection Mint Key: ", collectionMint.toBase58()); + + const metadata = await getMetadata(collectionMint); + console.log("Collection Metadata Account: ", metadata.toBase58()); + + const masterEdition = await getMasterEdition(collectionMint); + console.log("Master Edition Account: ", masterEdition.toBase58()); + + const destination = getAssociatedTokenAddressSync(collectionMint, wallet.publicKey); + console.log("Destination ATA = ", destination.toBase58()); + + const tx = await program.methods + .createCollection() + .accountsPartial({ + user: wallet.publicKey, + mint: collectionMint, + mintAuthority, + metadata, + masterEdition, + destination, + systemProgram: SystemProgram.programId, + tokenProgram: TOKEN_PROGRAM_ID, + associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID, + tokenMetadataProgram: TOKEN_METADATA_PROGRAM_ID, + }) + .signers([collectionKeypair]) + .rpc({ + skipPreflight: true, + }); + console.log("\nCollection NFT minted: TxID - ", tx); + }); + + it("Mint NFT", async () => { + console.log("\nMint", mint.toBase58()); + + const metadata = await getMetadata(mint); + console.log("Metadata", metadata.toBase58()); + + const masterEdition = await getMasterEdition(mint); + console.log("Master Edition", masterEdition.toBase58()); + + const destination = getAssociatedTokenAddressSync(mint, wallet.publicKey); + console.log("Destination", destination.toBase58()); + + const tx = await program.methods + .mintNft() + .accountsPartial({ + owner: wallet.publicKey, + destination, + metadata, + masterEdition, + mint, + mintAuthority, + collectionMint, + systemProgram: SystemProgram.programId, + tokenProgram: TOKEN_PROGRAM_ID, + associatedTokenProgram: ASSOCIATED_PROGRAM_ID, + tokenMetadataProgram: TOKEN_METADATA_PROGRAM_ID, + }) + .signers([mintKeypair]) + .rpc({ + skipPreflight: true, + }); + console.log("\nNFT Minted! Your transaction signature", tx); + }); + + it("Verify Collection", async () => { + const mintMetadata = await getMetadata(mint); + console.log("\nMint Metadata", mintMetadata.toBase58()); + + const collectionMetadata = await getMetadata(collectionMint); + console.log("Collection Metadata", collectionMetadata.toBase58()); + + const collectionMasterEdition = await getMasterEdition(collectionMint); + console.log("Collection Master Edition", collectionMasterEdition.toBase58()); + + const tx = await program.methods + .verifyCollection() + .accountsPartial({ + authority: wallet.publicKey, + metadata: mintMetadata, + mint, + mintAuthority, + collectionMint, + collectionMetadata, + collectionMasterEdition, + systemProgram: SystemProgram.programId, + sysvarInstruction: anchor.web3.SYSVAR_INSTRUCTIONS_PUBKEY, + tokenMetadataProgram: TOKEN_METADATA_PROGRAM_ID, + }) + .rpc({ + skipPreflight: true, + }); + console.log("\nCollection Verified! Your transaction signature", tx); + }); }); diff --git a/tokens/nft-operations/anchor/tests/mint-nft.ts b/tokens/nft-operations/anchor/tests/mint-nft.ts index 198e93f70..e17981279 100644 --- a/tokens/nft-operations/anchor/tests/mint-nft.ts +++ b/tokens/nft-operations/anchor/tests/mint-nft.ts @@ -1,12 +1,12 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; -import type NodeWallet from '@anchor-lang/core/dist/cjs/nodewallet'; -import { ASSOCIATED_PROGRAM_ID } from '@anchor-lang/core/dist/cjs/utils/token'; -import { ASSOCIATED_TOKEN_PROGRAM_ID, getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID } from '@solana/spl-token'; -import { Keypair, SystemProgram } from '@solana/web3.js'; -import type { MintNft } from '../target/types/mint_nft'; - -describe('mint-nft', () => { +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; +import type NodeWallet from "@anchor-lang/core/dist/cjs/nodewallet"; +import { ASSOCIATED_PROGRAM_ID } from "@anchor-lang/core/dist/cjs/utils/token"; +import { ASSOCIATED_TOKEN_PROGRAM_ID, getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID } from "@solana/spl-token"; +import { Keypair, SystemProgram } from "@solana/web3.js"; +import type { MintNft } from "../target/types/mint_nft"; + +describe("mint-nft", () => { // Configure the client to use the local cluster. const provider = anchor.AnchorProvider.env(); anchor.setProvider(provider); @@ -15,9 +15,9 @@ describe('mint-nft', () => { const program = anchor.workspace.MintNft as Program; - const TOKEN_METADATA_PROGRAM_ID = new anchor.web3.PublicKey('metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s'); + const TOKEN_METADATA_PROGRAM_ID = new anchor.web3.PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"); - const mintAuthority = anchor.web3.PublicKey.findProgramAddressSync([Buffer.from('authority')], program.programId)[0]; + const mintAuthority = anchor.web3.PublicKey.findProgramAddressSync([Buffer.from("authority")], program.programId)[0]; const collectionKeypair = Keypair.generate(); const collectionMint = collectionKeypair.publicKey; @@ -27,29 +27,29 @@ describe('mint-nft', () => { const getMetadata = async (mint: anchor.web3.PublicKey): Promise => { return anchor.web3.PublicKey.findProgramAddressSync( - [Buffer.from('metadata'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mint.toBuffer()], + [Buffer.from("metadata"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mint.toBuffer()], TOKEN_METADATA_PROGRAM_ID, )[0]; }; const getMasterEdition = async (mint: anchor.web3.PublicKey): Promise => { return anchor.web3.PublicKey.findProgramAddressSync( - [Buffer.from('metadata'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mint.toBuffer(), Buffer.from('edition')], + [Buffer.from("metadata"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mint.toBuffer(), Buffer.from("edition")], TOKEN_METADATA_PROGRAM_ID, )[0]; }; - it('Create Collection NFT', async () => { - console.log('\nCollection Mint Key: ', collectionMint.toBase58()); + it("Create Collection NFT", async () => { + console.log("\nCollection Mint Key: ", collectionMint.toBase58()); const metadata = await getMetadata(collectionMint); - console.log('Collection Metadata Account: ', metadata.toBase58()); + console.log("Collection Metadata Account: ", metadata.toBase58()); const masterEdition = await getMasterEdition(collectionMint); - console.log('Master Edition Account: ', masterEdition.toBase58()); + console.log("Master Edition Account: ", masterEdition.toBase58()); const destination = getAssociatedTokenAddressSync(collectionMint, wallet.publicKey); - console.log('Destination ATA = ', destination.toBase58()); + console.log("Destination ATA = ", destination.toBase58()); const tx = await program.methods .createCollection() @@ -69,20 +69,20 @@ describe('mint-nft', () => { .rpc({ skipPreflight: true, }); - console.log('\nCollection NFT minted: TxID - ', tx); + console.log("\nCollection NFT minted: TxID - ", tx); }); - it('Mint NFT', async () => { - console.log('\nMint', mint.toBase58()); + it("Mint NFT", async () => { + console.log("\nMint", mint.toBase58()); const metadata = await getMetadata(mint); - console.log('Metadata', metadata.toBase58()); + console.log("Metadata", metadata.toBase58()); const masterEdition = await getMasterEdition(mint); - console.log('Master Edition', masterEdition.toBase58()); + console.log("Master Edition", masterEdition.toBase58()); const destination = getAssociatedTokenAddressSync(mint, wallet.publicKey); - console.log('Destination', destination.toBase58()); + console.log("Destination", destination.toBase58()); const tx = await program.methods .mintNft() @@ -103,18 +103,18 @@ describe('mint-nft', () => { .rpc({ skipPreflight: true, }); - console.log('\nNFT Minted! Your transaction signature', tx); + console.log("\nNFT Minted! Your transaction signature", tx); }); - it('Verify Collection', async () => { + it("Verify Collection", async () => { const mintMetadata = await getMetadata(mint); - console.log('\nMint Metadata', mintMetadata.toBase58()); + console.log("\nMint Metadata", mintMetadata.toBase58()); const collectionMetadata = await getMetadata(collectionMint); - console.log('Collection Metadata', collectionMetadata.toBase58()); + console.log("Collection Metadata", collectionMetadata.toBase58()); const collectionMasterEdition = await getMasterEdition(collectionMint); - console.log('Collection Master Edition', collectionMasterEdition.toBase58()); + console.log("Collection Master Edition", collectionMasterEdition.toBase58()); const tx = await program.methods .verifyCollection() @@ -133,6 +133,6 @@ describe('mint-nft', () => { .rpc({ skipPreflight: true, }); - console.log('\nCollection Verified! Your transaction signature', tx); + console.log("\nCollection Verified! Your transaction signature", tx); }); }); diff --git a/tokens/pda-mint-authority/anchor/package.json b/tokens/pda-mint-authority/anchor/package.json index 4042e17fa..cae91ba71 100644 --- a/tokens/pda-mint-authority/anchor/package.json +++ b/tokens/pda-mint-authority/anchor/package.json @@ -1,22 +1,22 @@ { - "type": "module", - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.3.8" - }, - "scripts": { - "postinstall": "zx prepare.mjs" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "anchor-bankrun": "^0.4.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "solana-bankrun": "^0.3.0", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3", - "zx": "^8.1.4" - } + "type": "module", + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.3.8" + }, + "scripts": { + "postinstall": "zx prepare.mjs" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "anchor-bankrun": "^0.4.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "solana-bankrun": "^0.3.0", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3", + "zx": "^8.1.4" + } } diff --git a/tokens/pda-mint-authority/anchor/prepare.mjs b/tokens/pda-mint-authority/anchor/prepare.mjs index 7c5ec464b..fb6b26225 100644 --- a/tokens/pda-mint-authority/anchor/prepare.mjs +++ b/tokens/pda-mint-authority/anchor/prepare.mjs @@ -1,17 +1,17 @@ #!/usr/bin/env zx -import { mkdir, rm } from 'node:fs/promises'; -import { join } from 'node:path'; -import { $ } from 'zx'; +import { mkdir, rm } from "node:fs/promises"; +import { join } from "node:path"; +import { $ } from "zx"; const programs = [ { - id: 'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s', - name: 'token_metadata.so', + id: "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s", + name: "token_metadata.so", }, ]; -const outputDir = 'tests/fixtures'; +const outputDir = "tests/fixtures"; const overwrite = true; try { diff --git a/tokens/pda-mint-authority/anchor/tests/bankrun.test.ts b/tokens/pda-mint-authority/anchor/tests/bankrun.test.ts index 7c4b0a991..2948ee994 100644 --- a/tokens/pda-mint-authority/anchor/tests/bankrun.test.ts +++ b/tokens/pda-mint-authority/anchor/tests/bankrun.test.ts @@ -4,76 +4,66 @@ import { PublicKey } from "@solana/web3.js"; import { BankrunProvider } from "anchor-bankrun"; import { BN } from "bn.js"; import { startAnchor } from "solana-bankrun"; +import IDL from "../target/idl/token_minter.json"; import type { TokenMinter } from "../target/types/token_minter"; -import IDL from "../target/idl/token_minter.json"; const PROGRAM_ID = new PublicKey(IDL.address); -const METADATA_PROGRAM_ID = new PublicKey( - "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s", -); +const METADATA_PROGRAM_ID = new PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"); describe("NFT Minter", async () => { - const context = await startAnchor( - "", - [ - { name: "token_minter", programId: PROGRAM_ID }, - { name: "token_metadata", programId: METADATA_PROGRAM_ID }, - ], - [], - ); - const provider = new BankrunProvider(context); - anchor.setProvider(provider); - const payer = provider.wallet as anchor.Wallet; - const program = new anchor.Program(IDL, provider); + const context = await startAnchor( + "", + [ + { name: "token_minter", programId: PROGRAM_ID }, + { name: "token_metadata", programId: METADATA_PROGRAM_ID }, + ], + [], + ); + const provider = new BankrunProvider(context); + anchor.setProvider(provider); + const payer = provider.wallet as anchor.Wallet; + const program = new anchor.Program(IDL, provider); - // Derive the PDA to use as mint account address. - // This same PDA is also used as the mint authority. - const [mintPDA] = PublicKey.findProgramAddressSync( - [Buffer.from("mint")], - program.programId, - ); + // Derive the PDA to use as mint account address. + // This same PDA is also used as the mint authority. + const [mintPDA] = PublicKey.findProgramAddressSync([Buffer.from("mint")], program.programId); - const metadata = { - name: "Solana Gold", - symbol: "GOLDSOL", - uri: "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json", - }; + const metadata = { + name: "Solana Gold", + symbol: "GOLDSOL", + uri: "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json", + }; - it("Create a token!", async () => { - const transactionSignature = await program.methods - .createToken(metadata.name, metadata.symbol, metadata.uri) - .accounts({ - payer: payer.publicKey, - }) - .rpc(); + it("Create a token!", async () => { + const transactionSignature = await program.methods + .createToken(metadata.name, metadata.symbol, metadata.uri) + .accounts({ + payer: payer.publicKey, + }) + .rpc(); - console.log("Success!"); - console.log(` Mint Address: ${mintPDA}`); - console.log(` Transaction Signature: ${transactionSignature}`); - }); + console.log("Success!"); + console.log(` Mint Address: ${mintPDA}`); + console.log(` Transaction Signature: ${transactionSignature}`); + }); - it("Mint 1 Token!", async () => { - // Derive the associated token address account for the mint and payer. - const associatedTokenAccountAddress = getAssociatedTokenAddressSync( - mintPDA, - payer.publicKey, - ); + it("Mint 1 Token!", async () => { + // Derive the associated token address account for the mint and payer. + const associatedTokenAccountAddress = getAssociatedTokenAddressSync(mintPDA, payer.publicKey); - // Amount of tokens to mint. - const amount = new BN(100); + // Amount of tokens to mint. + const amount = new BN(100); - const transactionSignature = await program.methods - .mintToken(amount) - .accounts({ - payer: payer.publicKey, - associatedTokenAccount: associatedTokenAccountAddress, - }) - .rpc(); + const transactionSignature = await program.methods + .mintToken(amount) + .accounts({ + payer: payer.publicKey, + associatedTokenAccount: associatedTokenAccountAddress, + }) + .rpc(); - console.log("Success!"); - console.log( - ` Associated Token Account Address: ${associatedTokenAccountAddress}`, - ); - console.log(` Transaction Signature: ${transactionSignature}`); - }); + console.log("Success!"); + console.log(` Associated Token Account Address: ${associatedTokenAccountAddress}`); + console.log(` Transaction Signature: ${transactionSignature}`); + }); }); diff --git a/tokens/pda-mint-authority/anchor/tests/test.ts b/tokens/pda-mint-authority/anchor/tests/test.ts index 9371ebf86..a13a5b413 100644 --- a/tokens/pda-mint-authority/anchor/tests/test.ts +++ b/tokens/pda-mint-authority/anchor/tests/test.ts @@ -5,59 +5,51 @@ import { BN } from "bn.js"; import type { TokenMinter } from "../target/types/token_minter"; describe("NFT Minter", () => { - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); - const payer = provider.wallet as anchor.Wallet; - const program = anchor.workspace.TokenMinter as anchor.Program; - - // Derive the PDA to use as mint account address. - // This same PDA is also used as the mint authority. - const [mintPDA] = PublicKey.findProgramAddressSync( - [Buffer.from("mint")], - program.programId, - ); - - const metadata = { - name: "Solana Gold", - symbol: "GOLDSOL", - uri: "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json", - }; - - it("Create a token!", async () => { - const transactionSignature = await program.methods - .createToken(metadata.name, metadata.symbol, metadata.uri) - .accounts({ - payer: payer.publicKey, - }) - .rpc(); - - console.log("Success!"); - console.log(` Mint Address: ${mintPDA}`); - console.log(` Transaction Signature: ${transactionSignature}`); - }); - - it("Mint 1 Token!", async () => { - // Derive the associated token address account for the mint and payer. - const associatedTokenAccountAddress = getAssociatedTokenAddressSync( - mintPDA, - payer.publicKey, - ); - - // Amount of tokens to mint. - const amount = new BN(100); - - const transactionSignature = await program.methods - .mintToken(amount) - .accounts({ - payer: payer.publicKey, - associatedTokenAccount: associatedTokenAccountAddress, - }) - .rpc(); - - console.log("Success!"); - console.log( - ` Associated Token Account Address: ${associatedTokenAccountAddress}`, - ); - console.log(` Transaction Signature: ${transactionSignature}`); - }); + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); + const payer = provider.wallet as anchor.Wallet; + const program = anchor.workspace.TokenMinter as anchor.Program; + + // Derive the PDA to use as mint account address. + // This same PDA is also used as the mint authority. + const [mintPDA] = PublicKey.findProgramAddressSync([Buffer.from("mint")], program.programId); + + const metadata = { + name: "Solana Gold", + symbol: "GOLDSOL", + uri: "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json", + }; + + it("Create a token!", async () => { + const transactionSignature = await program.methods + .createToken(metadata.name, metadata.symbol, metadata.uri) + .accounts({ + payer: payer.publicKey, + }) + .rpc(); + + console.log("Success!"); + console.log(` Mint Address: ${mintPDA}`); + console.log(` Transaction Signature: ${transactionSignature}`); + }); + + it("Mint 1 Token!", async () => { + // Derive the associated token address account for the mint and payer. + const associatedTokenAccountAddress = getAssociatedTokenAddressSync(mintPDA, payer.publicKey); + + // Amount of tokens to mint. + const amount = new BN(100); + + const transactionSignature = await program.methods + .mintToken(amount) + .accounts({ + payer: payer.publicKey, + associatedTokenAccount: associatedTokenAccountAddress, + }) + .rpc(); + + console.log("Success!"); + console.log(` Associated Token Account Address: ${associatedTokenAccountAddress}`); + console.log(` Transaction Signature: ${transactionSignature}`); + }); }); diff --git a/tokens/pda-mint-authority/native/tests/instructions.ts b/tokens/pda-mint-authority/native/tests/instructions.ts index c06932ef9..0995c6c98 100644 --- a/tokens/pda-mint-authority/native/tests/instructions.ts +++ b/tokens/pda-mint-authority/native/tests/instructions.ts @@ -1,4 +1,4 @@ -import * as borsh from 'borsh'; +import * as borsh from "borsh"; export enum NftMinterInstruction { Init = 0, @@ -6,18 +6,18 @@ export enum NftMinterInstruction { Mint = 2, } -export const InitArgsSchema = { struct: { instruction: 'u8' } }; +export const InitArgsSchema = { struct: { instruction: "u8" } }; export const CreateTokenArgsSchema = { struct: { - instruction: 'u8', - nft_title: 'string', - nft_symbol: 'string', - nft_uri: 'string', + instruction: "u8", + nft_title: "string", + nft_symbol: "string", + nft_uri: "string", }, }; -export const MintToArgsSchema = { struct: { instruction: 'u8' } }; +export const MintToArgsSchema = { struct: { instruction: "u8" } }; export function borshSerialize(schema: borsh.Schema, data: object): Buffer { return Buffer.from(borsh.serialize(schema, data)); diff --git a/tokens/pda-mint-authority/native/tests/test.ts b/tokens/pda-mint-authority/native/tests/test.ts index 5528d3c11..65e31ee38 100644 --- a/tokens/pda-mint-authority/native/tests/test.ts +++ b/tokens/pda-mint-authority/native/tests/test.ts @@ -1,6 +1,6 @@ -import { Buffer } from 'node:buffer'; -import { PROGRAM_ID as TOKEN_METADATA_PROGRAM_ID } from '@metaplex-foundation/mpl-token-metadata'; -import { ASSOCIATED_TOKEN_PROGRAM_ID, getAssociatedTokenAddress, TOKEN_PROGRAM_ID } from '@solana/spl-token'; +import { Buffer } from "node:buffer"; +import { PROGRAM_ID as TOKEN_METADATA_PROGRAM_ID } from "@metaplex-foundation/mpl-token-metadata"; +import { ASSOCIATED_TOKEN_PROGRAM_ID, getAssociatedTokenAddress, TOKEN_PROGRAM_ID } from "@solana/spl-token"; import { Connection, Keypair, @@ -10,24 +10,33 @@ import { sendAndConfirmTransaction, Transaction, TransactionInstruction, -} from '@solana/web3.js'; -import { borshSerialize, InitArgsSchema, CreateTokenArgsSchema, MintToArgsSchema, NftMinterInstruction } from './instructions'; +} from "@solana/web3.js"; +import { + borshSerialize, + CreateTokenArgsSchema, + InitArgsSchema, + MintToArgsSchema, + NftMinterInstruction, +} from "./instructions"; function createKeypairFromFile(path: string): Keypair { - return Keypair.fromSecretKey(Uint8Array.from(JSON.parse(require('node:fs').readFileSync(path, 'utf-8')))); + return Keypair.fromSecretKey(Uint8Array.from(JSON.parse(require("node:fs").readFileSync(path, "utf-8")))); } -describe('NFT Minter', async () => { +describe("NFT Minter", async () => { // const connection = new Connection(`http://localhost:8899`, 'confirmed'); - const connection = new Connection('https://api.devnet.solana.com/', 'confirmed'); - const payer = createKeypairFromFile(`${require('node:os').homedir()}/.config/solana/id.json`); - const program = createKeypairFromFile('./program/target/deploy/program-keypair.json'); + const connection = new Connection("https://api.devnet.solana.com/", "confirmed"); + const payer = createKeypairFromFile(`${require("node:os").homedir()}/.config/solana/id.json`); + const program = createKeypairFromFile("./program/target/deploy/program-keypair.json"); - const mintAuthorityPublicKey = PublicKey.findProgramAddressSync([Buffer.from('mint_authority')], program.publicKey)[0]; + const mintAuthorityPublicKey = PublicKey.findProgramAddressSync( + [Buffer.from("mint_authority")], + program.publicKey, + )[0]; const mintKeypair: Keypair = Keypair.generate(); - it('Init Mint Authority PDA', async () => { + it("Init Mint Authority PDA", async () => { const instructionData = borshSerialize(InitArgsSchema, { instruction: NftMinterInstruction.Init, }); @@ -44,22 +53,23 @@ describe('NFT Minter', async () => { const sx = await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer], { skipPreflight: true }); - console.log('Success!'); + console.log("Success!"); console.log(` Mint Address: ${mintKeypair.publicKey}`); console.log(` Tx Signature: ${sx}`); }); - it('Create an NFT!', async () => { + it("Create an NFT!", async () => { const metadataAddress = PublicKey.findProgramAddressSync( - [Buffer.from('metadata'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mintKeypair.publicKey.toBuffer()], + [Buffer.from("metadata"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mintKeypair.publicKey.toBuffer()], TOKEN_METADATA_PROGRAM_ID, )[0]; const instructionData = borshSerialize(CreateTokenArgsSchema, { instruction: NftMinterInstruction.Create, - nft_title: 'Homer NFT', - nft_symbol: 'HOMR', - nft_uri: 'https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/nft.json', + nft_title: "Homer NFT", + nft_symbol: "HOMR", + nft_uri: + "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/nft.json", }); const ix = new TransactionInstruction({ @@ -81,21 +91,28 @@ describe('NFT Minter', async () => { data: instructionData, }); - const sx = await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer, mintKeypair], { skipPreflight: true }); + const sx = await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer, mintKeypair], { + skipPreflight: true, + }); - console.log('Success!'); + console.log("Success!"); console.log(` Mint Address: ${mintKeypair.publicKey}`); console.log(` Tx Signature: ${sx}`); }); - it('Mint the NFT to your wallet!', async () => { + it("Mint the NFT to your wallet!", async () => { const metadataAddress = PublicKey.findProgramAddressSync( - [Buffer.from('metadata'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mintKeypair.publicKey.toBuffer()], + [Buffer.from("metadata"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mintKeypair.publicKey.toBuffer()], TOKEN_METADATA_PROGRAM_ID, )[0]; const editionAddress = PublicKey.findProgramAddressSync( - [Buffer.from('metadata'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mintKeypair.publicKey.toBuffer(), Buffer.from('edition')], + [ + Buffer.from("metadata"), + TOKEN_METADATA_PROGRAM_ID.toBuffer(), + mintKeypair.publicKey.toBuffer(), + Buffer.from("edition"), + ], TOKEN_METADATA_PROGRAM_ID, )[0]; @@ -137,7 +154,7 @@ describe('NFT Minter', async () => { const sx = await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer]); - console.log('Success!'); + console.log("Success!"); console.log(` ATA Address: ${associatedTokenAccountAddress}`); console.log(` Tx Signature: ${sx}`); }); diff --git a/tokens/spl-token-minter/anchor/package.json b/tokens/spl-token-minter/anchor/package.json index 4042e17fa..cae91ba71 100644 --- a/tokens/spl-token-minter/anchor/package.json +++ b/tokens/spl-token-minter/anchor/package.json @@ -1,22 +1,22 @@ { - "type": "module", - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.3.8" - }, - "scripts": { - "postinstall": "zx prepare.mjs" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "anchor-bankrun": "^0.4.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "solana-bankrun": "^0.3.0", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3", - "zx": "^8.1.4" - } + "type": "module", + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.3.8" + }, + "scripts": { + "postinstall": "zx prepare.mjs" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "anchor-bankrun": "^0.4.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "solana-bankrun": "^0.3.0", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3", + "zx": "^8.1.4" + } } diff --git a/tokens/spl-token-minter/anchor/prepare.mjs b/tokens/spl-token-minter/anchor/prepare.mjs index 7c5ec464b..fb6b26225 100644 --- a/tokens/spl-token-minter/anchor/prepare.mjs +++ b/tokens/spl-token-minter/anchor/prepare.mjs @@ -1,17 +1,17 @@ #!/usr/bin/env zx -import { mkdir, rm } from 'node:fs/promises'; -import { join } from 'node:path'; -import { $ } from 'zx'; +import { mkdir, rm } from "node:fs/promises"; +import { join } from "node:path"; +import { $ } from "zx"; const programs = [ { - id: 'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s', - name: 'token_metadata.so', + id: "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s", + name: "token_metadata.so", }, ]; -const outputDir = 'tests/fixtures'; +const outputDir = "tests/fixtures"; const overwrite = true; try { diff --git a/tokens/spl-token-minter/anchor/tests/bankrun.test.ts b/tokens/spl-token-minter/anchor/tests/bankrun.test.ts index c740d1ddb..7c59e6eee 100644 --- a/tokens/spl-token-minter/anchor/tests/bankrun.test.ts +++ b/tokens/spl-token-minter/anchor/tests/bankrun.test.ts @@ -4,78 +4,71 @@ import { Keypair, PublicKey } from "@solana/web3.js"; import { BankrunProvider } from "anchor-bankrun"; import { BN } from "bn.js"; import { startAnchor } from "solana-bankrun"; +import IDL from "../target/idl/spl_token_minter.json"; import type { SplTokenMinter } from "../target/types/spl_token_minter"; -import IDL from "../target/idl/spl_token_minter.json"; const PROGRAM_ID = new PublicKey(IDL.address); -const METADATA_PROGRAM_ID = new PublicKey( - "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s", -); +const METADATA_PROGRAM_ID = new PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"); describe("SPL Token Minter", async () => { - const context = await startAnchor( - "", - [ - { name: "spl_token_minter", programId: PROGRAM_ID }, - { name: "token_metadata", programId: METADATA_PROGRAM_ID }, - ], - [], - ); + const context = await startAnchor( + "", + [ + { name: "spl_token_minter", programId: PROGRAM_ID }, + { name: "token_metadata", programId: METADATA_PROGRAM_ID }, + ], + [], + ); - const provider = new BankrunProvider(context); - anchor.setProvider(provider); - const payer = provider.wallet as anchor.Wallet; - const program = new anchor.Program(IDL, provider); + const provider = new BankrunProvider(context); + anchor.setProvider(provider); + const payer = provider.wallet as anchor.Wallet; + const program = new anchor.Program(IDL, provider); - const metadata = { - name: "Solana Gold", - symbol: "GOLDSOL", - uri: "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json", - }; + const metadata = { + name: "Solana Gold", + symbol: "GOLDSOL", + uri: "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json", + }; - // Generate new keypair to use as address for mint account. - const mintKeypair = new Keypair(); + // Generate new keypair to use as address for mint account. + const mintKeypair = new Keypair(); - it("Create an SPL Token!", async () => { - const transactionSignature = await program.methods - .createToken(metadata.name, metadata.symbol, metadata.uri) - .accounts({ - payer: payer.publicKey, - mintAccount: mintKeypair.publicKey, - }) - .signers([mintKeypair]) - .rpc(); + it("Create an SPL Token!", async () => { + const transactionSignature = await program.methods + .createToken(metadata.name, metadata.symbol, metadata.uri) + .accounts({ + payer: payer.publicKey, + mintAccount: mintKeypair.publicKey, + }) + .signers([mintKeypair]) + .rpc(); - console.log("Success!"); - console.log(` Mint Address: ${mintKeypair.publicKey}`); - console.log(` Transaction Signature: ${transactionSignature}`); - }); + console.log("Success!"); + console.log(` Mint Address: ${mintKeypair.publicKey}`); + console.log(` Transaction Signature: ${transactionSignature}`); + }); - it("Mint some tokens to your wallet!", async () => { - // Derive the associated token address account for the mint and payer. - const associatedTokenAccountAddress = getAssociatedTokenAddressSync( - mintKeypair.publicKey, - payer.publicKey, - ); + it("Mint some tokens to your wallet!", async () => { + // Derive the associated token address account for the mint and payer. + const associatedTokenAccountAddress = getAssociatedTokenAddressSync(mintKeypair.publicKey, payer.publicKey); - // Amount of tokens to mint. - const amount = new BN(100); + // Amount of tokens to mint. + const amount = new BN(100); - // Mint the tokens to the associated token account. - const transactionSignature = await program.methods - .mintToken(amount) - .accounts({ - mintAuthority: payer.publicKey, - recipient: payer.publicKey, - mintAccount: mintKeypair.publicKey, - associatedTokenAccount: associatedTokenAccountAddress, - }) - .rpc(); + // Mint the tokens to the associated token account. + const transactionSignature = await program.methods + .mintToken(amount) + .accounts({ + mintAuthority: payer.publicKey, + recipient: payer.publicKey, + mintAccount: mintKeypair.publicKey, + associatedTokenAccount: associatedTokenAccountAddress, + }) + .rpc(); - console.log("Success!"); - console.log( - ` Associated Token Account Address: ${associatedTokenAccountAddress}`, - ); - console.log(` Transaction Signature: ${transactionSignature}`); - }); + console.log("Success!"); + console.log(` Associated Token Account Address: ${associatedTokenAccountAddress}`); + console.log(` Transaction Signature: ${transactionSignature}`); + }); }); diff --git a/tokens/spl-token-minter/anchor/tests/test.ts b/tokens/spl-token-minter/anchor/tests/test.ts index d06dad462..d3d94516b 100644 --- a/tokens/spl-token-minter/anchor/tests/test.ts +++ b/tokens/spl-token-minter/anchor/tests/test.ts @@ -5,61 +5,55 @@ import { BN } from "bn.js"; import type { SplTokenMinter } from "../target/types/spl_token_minter"; describe("SPL Token Minter", () => { - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); - const payer = provider.wallet as anchor.Wallet; - const program = anchor.workspace - .SplTokenMinter as anchor.Program; - - const metadata = { - name: "Solana Gold", - symbol: "GOLDSOL", - uri: "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json", - }; - - // Generate new keypair to use as address for mint account. - const mintKeypair = new Keypair(); - - it("Create an SPL Token!", async () => { - const transactionSignature = await program.methods - .createToken(metadata.name, metadata.symbol, metadata.uri) - .accounts({ - payer: payer.publicKey, - mintAccount: mintKeypair.publicKey, - }) - .signers([mintKeypair]) - .rpc(); - - console.log("Success!"); - console.log(` Mint Address: ${mintKeypair.publicKey}`); - console.log(` Transaction Signature: ${transactionSignature}`); - }); - - it("Mint some tokens to your wallet!", async () => { - // Derive the associated token address account for the mint and payer. - const associatedTokenAccountAddress = getAssociatedTokenAddressSync( - mintKeypair.publicKey, - payer.publicKey, - ); - - // Amount of tokens to mint. - const amount = new BN(100); - - // Mint the tokens to the associated token account. - const transactionSignature = await program.methods - .mintToken(amount) - .accounts({ - mintAuthority: payer.publicKey, - recipient: payer.publicKey, - mintAccount: mintKeypair.publicKey, - associatedTokenAccount: associatedTokenAccountAddress, - }) - .rpc(); - - console.log("Success!"); - console.log( - ` Associated Token Account Address: ${associatedTokenAccountAddress}`, - ); - console.log(` Transaction Signature: ${transactionSignature}`); - }); + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); + const payer = provider.wallet as anchor.Wallet; + const program = anchor.workspace.SplTokenMinter as anchor.Program; + + const metadata = { + name: "Solana Gold", + symbol: "GOLDSOL", + uri: "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json", + }; + + // Generate new keypair to use as address for mint account. + const mintKeypair = new Keypair(); + + it("Create an SPL Token!", async () => { + const transactionSignature = await program.methods + .createToken(metadata.name, metadata.symbol, metadata.uri) + .accounts({ + payer: payer.publicKey, + mintAccount: mintKeypair.publicKey, + }) + .signers([mintKeypair]) + .rpc(); + + console.log("Success!"); + console.log(` Mint Address: ${mintKeypair.publicKey}`); + console.log(` Transaction Signature: ${transactionSignature}`); + }); + + it("Mint some tokens to your wallet!", async () => { + // Derive the associated token address account for the mint and payer. + const associatedTokenAccountAddress = getAssociatedTokenAddressSync(mintKeypair.publicKey, payer.publicKey); + + // Amount of tokens to mint. + const amount = new BN(100); + + // Mint the tokens to the associated token account. + const transactionSignature = await program.methods + .mintToken(amount) + .accounts({ + mintAuthority: payer.publicKey, + recipient: payer.publicKey, + mintAccount: mintKeypair.publicKey, + associatedTokenAccount: associatedTokenAccountAddress, + }) + .rpc(); + + console.log("Success!"); + console.log(` Associated Token Account Address: ${associatedTokenAccountAddress}`); + console.log(` Transaction Signature: ${transactionSignature}`); + }); }); diff --git a/tokens/spl-token-minter/native/tests/instructions.ts b/tokens/spl-token-minter/native/tests/instructions.ts index e62cde477..70df73542 100644 --- a/tokens/spl-token-minter/native/tests/instructions.ts +++ b/tokens/spl-token-minter/native/tests/instructions.ts @@ -1,4 +1,4 @@ -import * as borsh from 'borsh'; +import * as borsh from "borsh"; export enum SplMinterInstruction { Create = 0, @@ -7,17 +7,17 @@ export enum SplMinterInstruction { export const CreateTokenArgsSchema = { struct: { - instruction: 'u8', - token_title: 'string', - token_symbol: 'string', - token_uri: 'string', + instruction: "u8", + token_title: "string", + token_symbol: "string", + token_uri: "string", }, }; export const MintToArgsSchema = { struct: { - instruction: 'u8', - quantity: 'u64', + instruction: "u8", + quantity: "u64", }, }; diff --git a/tokens/spl-token-minter/native/tests/test.ts b/tokens/spl-token-minter/native/tests/test.ts index 9a9c956ab..e15166765 100644 --- a/tokens/spl-token-minter/native/tests/test.ts +++ b/tokens/spl-token-minter/native/tests/test.ts @@ -1,6 +1,6 @@ -import { Buffer } from 'node:buffer'; -import { PROGRAM_ID as TOKEN_METADATA_PROGRAM_ID } from '@metaplex-foundation/mpl-token-metadata'; -import { ASSOCIATED_TOKEN_PROGRAM_ID, getAssociatedTokenAddress, TOKEN_PROGRAM_ID } from '@solana/spl-token'; +import { Buffer } from "node:buffer"; +import { PROGRAM_ID as TOKEN_METADATA_PROGRAM_ID } from "@metaplex-foundation/mpl-token-metadata"; +import { ASSOCIATED_TOKEN_PROGRAM_ID, getAssociatedTokenAddress, TOKEN_PROGRAM_ID } from "@solana/spl-token"; import { Connection, Keypair, @@ -10,33 +10,34 @@ import { sendAndConfirmTransaction, Transaction, TransactionInstruction, -} from '@solana/web3.js'; -import { BN } from 'bn.js'; -import { borshSerialize, CreateTokenArgsSchema, MintToArgsSchema, SplMinterInstruction } from './instructions'; +} from "@solana/web3.js"; +import { BN } from "bn.js"; +import { borshSerialize, CreateTokenArgsSchema, MintToArgsSchema, SplMinterInstruction } from "./instructions"; function createKeypairFromFile(path: string): Keypair { - return Keypair.fromSecretKey(Uint8Array.from(JSON.parse(require('node:fs').readFileSync(path, 'utf-8')))); + return Keypair.fromSecretKey(Uint8Array.from(JSON.parse(require("node:fs").readFileSync(path, "utf-8")))); } -describe('SPL Token Minter', async () => { +describe("SPL Token Minter", async () => { // const connection = new Connection(`http://localhost:8899`, 'confirmed'); - const connection = new Connection('https://api.devnet.solana.com/', 'confirmed'); - const payer = createKeypairFromFile(`${require('node:os').homedir()}/.config/solana/id.json`); - const program = createKeypairFromFile('./program/target/deploy/program-keypair.json'); + const connection = new Connection("https://api.devnet.solana.com/", "confirmed"); + const payer = createKeypairFromFile(`${require("node:os").homedir()}/.config/solana/id.json`); + const program = createKeypairFromFile("./program/target/deploy/program-keypair.json"); const mintKeypair: Keypair = Keypair.generate(); - it('Create an SPL Token!', async () => { + it("Create an SPL Token!", async () => { const metadataAddress = PublicKey.findProgramAddressSync( - [Buffer.from('metadata'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mintKeypair.publicKey.toBuffer()], + [Buffer.from("metadata"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), mintKeypair.publicKey.toBuffer()], TOKEN_METADATA_PROGRAM_ID, )[0]; const instructionData = borshSerialize(CreateTokenArgsSchema, { instruction: SplMinterInstruction.Create, - token_title: 'Solana Gold', - token_symbol: 'GOLDSOL', - token_uri: 'https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json', + token_title: "Solana Gold", + token_symbol: "GOLDSOL", + token_uri: + "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json", }); const ix = new TransactionInstruction({ @@ -60,12 +61,12 @@ describe('SPL Token Minter', async () => { const sx = await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer, mintKeypair]); - console.log('Success!'); + console.log("Success!"); console.log(` Mint Address: ${mintKeypair.publicKey}`); console.log(` Tx Signature: ${sx}`); }); - it('Mint some tokens to your wallet!', async () => { + it("Mint some tokens to your wallet!", async () => { const associatedTokenAccountAddress = await getAssociatedTokenAddress(mintKeypair.publicKey, payer.publicKey); const instructionData = borshSerialize(MintToArgsSchema, { @@ -97,7 +98,7 @@ describe('SPL Token Minter', async () => { const sx = await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer]); - console.log('Success!'); + console.log("Success!"); console.log(` ATA Address: ${associatedTokenAccountAddress}`); console.log(` Tx Signature: ${sx}`); }); diff --git a/tokens/token-2022/basics/anchor/migrations/deploy.ts b/tokens/token-2022/basics/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/tokens/token-2022/basics/anchor/migrations/deploy.ts +++ b/tokens/token-2022/basics/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/token-2022/basics/anchor/package.json b/tokens/token-2022/basics/anchor/package.json index 5b2bb974f..273b394d6 100644 --- a/tokens/token-2022/basics/anchor/package.json +++ b/tokens/token-2022/basics/anchor/package.json @@ -1,23 +1,23 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/web3.js": "^1.98.4" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "anchor-bankrun": "^0.4.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "solana-bankrun": "^0.3.0", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/web3.js": "^1.98.4" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "anchor-bankrun": "^0.4.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "solana-bankrun": "^0.3.0", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-2022/basics/anchor/tests/anchor.ts b/tokens/token-2022/basics/anchor/tests/anchor.ts index f46a2078f..92e50943a 100644 --- a/tokens/token-2022/basics/anchor/tests/anchor.ts +++ b/tokens/token-2022/basics/anchor/tests/anchor.ts @@ -5,96 +5,72 @@ import BN from "bn.js"; import type { Anchor } from "../target/types/anchor"; describe("anchor", () => { - // Configure the client to use the local cluster. - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); - - const program = anchor.workspace.Anchor as Program; - const connection = program.provider.connection; - const TOKEN_2022_PROGRAM_ID = new anchor.web3.PublicKey( - "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb", - ); - const wallet = provider.wallet as anchor.Wallet; - const ATA_PROGRAM_ID = new anchor.web3.PublicKey( - "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL", - ); - - const tokenName = "TestToken"; - const [mint] = anchor.web3.PublicKey.findProgramAddressSync( - [ - Buffer.from("token-2022-token"), - wallet.publicKey.toBytes(), - Buffer.from(tokenName), - ], - program.programId, - ); - const [payerATA] = anchor.web3.PublicKey.findProgramAddressSync( - [ - wallet.publicKey.toBytes(), - TOKEN_2022_PROGRAM_ID.toBytes(), - mint.toBytes(), - ], - ATA_PROGRAM_ID, - ); - - const receiver = anchor.web3.Keypair.generate(); - - const [receiverATA] = anchor.web3.PublicKey.findProgramAddressSync( - [ - receiver.publicKey.toBytes(), - TOKEN_2022_PROGRAM_ID.toBytes(), - mint.toBytes(), - ], - ATA_PROGRAM_ID, - ); - - it("Create Token-2022 Token", async () => { - await connection.requestAirdrop(receiver.publicKey, 1000000000); - await connection.requestAirdrop(wallet.publicKey, 1000000000); - const tx = new anchor.web3.Transaction(); - - const ix = await program.methods - .createToken(tokenName) - .accounts({ - signer: wallet.publicKey, - tokenProgram: TOKEN_2022_PROGRAM_ID, - }) - .instruction(); - - tx.add(ix); - - const sig = await sendAndConfirmTransaction( - program.provider.connection, - tx, - [wallet.payer], - ); - console.log("Your transaction signature", sig); - }); - - it("Initialize payer ATA", async () => { - const tx = new anchor.web3.Transaction(); - - const ix = await program.methods - .createAssociatedTokenAccount() - .accounts({ - tokenAccount: payerATA, - mint: mint, - signer: wallet.publicKey, - tokenProgram: TOKEN_2022_PROGRAM_ID, - }) - .instruction(); - - tx.add(ix); - - const sig = await sendAndConfirmTransaction( - program.provider.connection, - tx, - [wallet.payer], - ); - console.log("Your transaction signature", sig); - }); - - /* + // Configure the client to use the local cluster. + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); + + const program = anchor.workspace.Anchor as Program; + const connection = program.provider.connection; + const TOKEN_2022_PROGRAM_ID = new anchor.web3.PublicKey("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"); + const wallet = provider.wallet as anchor.Wallet; + const ATA_PROGRAM_ID = new anchor.web3.PublicKey("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"); + + const tokenName = "TestToken"; + const [mint] = anchor.web3.PublicKey.findProgramAddressSync( + [Buffer.from("token-2022-token"), wallet.publicKey.toBytes(), Buffer.from(tokenName)], + program.programId, + ); + const [payerATA] = anchor.web3.PublicKey.findProgramAddressSync( + [wallet.publicKey.toBytes(), TOKEN_2022_PROGRAM_ID.toBytes(), mint.toBytes()], + ATA_PROGRAM_ID, + ); + + const receiver = anchor.web3.Keypair.generate(); + + const [receiverATA] = anchor.web3.PublicKey.findProgramAddressSync( + [receiver.publicKey.toBytes(), TOKEN_2022_PROGRAM_ID.toBytes(), mint.toBytes()], + ATA_PROGRAM_ID, + ); + + it("Create Token-2022 Token", async () => { + await connection.requestAirdrop(receiver.publicKey, 1000000000); + await connection.requestAirdrop(wallet.publicKey, 1000000000); + const tx = new anchor.web3.Transaction(); + + const ix = await program.methods + .createToken(tokenName) + .accounts({ + signer: wallet.publicKey, + tokenProgram: TOKEN_2022_PROGRAM_ID, + }) + .instruction(); + + tx.add(ix); + + const sig = await sendAndConfirmTransaction(program.provider.connection, tx, [wallet.payer]); + console.log("Your transaction signature", sig); + }); + + it("Initialize payer ATA", async () => { + const tx = new anchor.web3.Transaction(); + + const ix = await program.methods + .createAssociatedTokenAccount() + .accounts({ + tokenAccount: payerATA, + mint: mint, + signer: wallet.publicKey, + tokenProgram: TOKEN_2022_PROGRAM_ID, + }) + .instruction(); + + tx.add(ix); + + const sig = await sendAndConfirmTransaction(program.provider.connection, tx, [wallet.payer]); + console.log("Your transaction signature", sig); + }); + + /* // This instruction is included only as a reference, but is not required to run this test, because we are using "init" in the program's transfer instruction. The create_associated_token_account instruction on the program is provided as a reference as well. it("Initialize receiver ATA", async () => { const tx = new anchor.web3.Transaction(); @@ -119,52 +95,44 @@ describe("anchor", () => { }); */ - it("Mint Token to payer", async () => { - const tx = new anchor.web3.Transaction(); - - const ix = await program.methods - .mintToken(new BN(200000000)) - .accounts({ - mint: mint, - signer: wallet.publicKey, - receiver: payerATA, - tokenProgram: TOKEN_2022_PROGRAM_ID, - }) - .instruction(); - - tx.add(ix); - - const sig = await sendAndConfirmTransaction( - program.provider.connection, - tx, - [wallet.payer], - ); - console.log("Your transaction signature", sig); - }); - - // Using init in the transfer instruction, as init if needed is bot working with Token 2022 yet. - it("Transfer Token", async () => { - const tx = new anchor.web3.Transaction(); - - const ix = await program.methods - .transferToken(new BN(100)) - .accounts({ - mint: mint, - signer: wallet.publicKey, - from: payerATA, - to: receiver.publicKey, - tokenProgram: TOKEN_2022_PROGRAM_ID, - toAta: receiverATA, - }) - .instruction(); - - tx.add(ix); - - const sig = await sendAndConfirmTransaction( - program.provider.connection, - tx, - [wallet.payer], - ); - console.log("Your transaction signature", sig); - }); + it("Mint Token to payer", async () => { + const tx = new anchor.web3.Transaction(); + + const ix = await program.methods + .mintToken(new BN(200000000)) + .accounts({ + mint: mint, + signer: wallet.publicKey, + receiver: payerATA, + tokenProgram: TOKEN_2022_PROGRAM_ID, + }) + .instruction(); + + tx.add(ix); + + const sig = await sendAndConfirmTransaction(program.provider.connection, tx, [wallet.payer]); + console.log("Your transaction signature", sig); + }); + + // Using init in the transfer instruction, as init if needed is bot working with Token 2022 yet. + it("Transfer Token", async () => { + const tx = new anchor.web3.Transaction(); + + const ix = await program.methods + .transferToken(new BN(100)) + .accounts({ + mint: mint, + signer: wallet.publicKey, + from: payerATA, + to: receiver.publicKey, + tokenProgram: TOKEN_2022_PROGRAM_ID, + toAta: receiverATA, + }) + .instruction(); + + tx.add(ix); + + const sig = await sendAndConfirmTransaction(program.provider.connection, tx, [wallet.payer]); + console.log("Your transaction signature", sig); + }); }); diff --git a/tokens/token-2022/basics/anchor/tests/bankrun.test.ts b/tokens/token-2022/basics/anchor/tests/bankrun.test.ts index b62269651..2edae2ed8 100644 --- a/tokens/token-2022/basics/anchor/tests/bankrun.test.ts +++ b/tokens/token-2022/basics/anchor/tests/bankrun.test.ts @@ -11,95 +11,75 @@ const IDL = require("../target/idl/anchor.json"); const PROGRAM_ID = new PublicKey(IDL.address); describe("anchor", async () => { - const context = await startAnchor( - "", - [{ name: "anchor", programId: PROGRAM_ID }], - [], - ); - const provider = new BankrunProvider(context); - anchor.setProvider(provider); - const program = new anchor.Program(IDL, provider); - const client = context.banksClient; - const TOKEN_2022_PROGRAM_ID = new anchor.web3.PublicKey( - "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb", - ); - const wallet = provider.wallet as anchor.Wallet; - const ATA_PROGRAM_ID = new anchor.web3.PublicKey( - "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL", - ); - - const tokenName = "TestToken"; - const [mint] = anchor.web3.PublicKey.findProgramAddressSync( - [ - Buffer.from("token-2022-token"), - wallet.publicKey.toBytes(), - Buffer.from(tokenName), - ], - program.programId, - ); - const [payerATA] = anchor.web3.PublicKey.findProgramAddressSync( - [ - wallet.publicKey.toBytes(), - TOKEN_2022_PROGRAM_ID.toBytes(), - mint.toBytes(), - ], - ATA_PROGRAM_ID, - ); - - const receiver = anchor.web3.Keypair.generate(); - - const [receiverATA] = anchor.web3.PublicKey.findProgramAddressSync( - [ - receiver.publicKey.toBytes(), - TOKEN_2022_PROGRAM_ID.toBytes(), - mint.toBytes(), - ], - ATA_PROGRAM_ID, - ); - - it("Create Token-2022 Token", async () => { - // await connection.requestAirdrop(receiver.publicKey, 1000000000); - // await connection.requestAirdrop(wallet.publicKey, 1000000000); - const tx = new anchor.web3.Transaction(); - const [blockhash, _height] = await client.getLatestBlockhash(); - - const ix = await program.methods - .createToken(tokenName) - .accounts({ - signer: wallet.publicKey, - tokenProgram: TOKEN_2022_PROGRAM_ID, - }) - .instruction(); - - tx.recentBlockhash = blockhash; - tx.add(ix); - tx.sign(wallet.payer); - const sig = await client.processTransaction(tx); - console.log("Your transaction signature", sig); - }); - - it("Initialize payer ATA", async () => { - const tx = new anchor.web3.Transaction(); - const [blockhash, _height] = await client.getLatestBlockhash(); - - const ix = await program.methods - .createAssociatedTokenAccount() - .accounts({ - tokenAccount: payerATA, - mint: mint, - signer: wallet.publicKey, - tokenProgram: TOKEN_2022_PROGRAM_ID, - }) - .instruction(); - - tx.recentBlockhash = blockhash; - tx.add(ix); - tx.sign(wallet.payer); - const sig = await client.processTransaction(tx); - console.log("Your transaction signature", sig); - }); - - /* + const context = await startAnchor("", [{ name: "anchor", programId: PROGRAM_ID }], []); + const provider = new BankrunProvider(context); + anchor.setProvider(provider); + const program = new anchor.Program(IDL, provider); + const client = context.banksClient; + const TOKEN_2022_PROGRAM_ID = new anchor.web3.PublicKey("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"); + const wallet = provider.wallet as anchor.Wallet; + const ATA_PROGRAM_ID = new anchor.web3.PublicKey("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"); + + const tokenName = "TestToken"; + const [mint] = anchor.web3.PublicKey.findProgramAddressSync( + [Buffer.from("token-2022-token"), wallet.publicKey.toBytes(), Buffer.from(tokenName)], + program.programId, + ); + const [payerATA] = anchor.web3.PublicKey.findProgramAddressSync( + [wallet.publicKey.toBytes(), TOKEN_2022_PROGRAM_ID.toBytes(), mint.toBytes()], + ATA_PROGRAM_ID, + ); + + const receiver = anchor.web3.Keypair.generate(); + + const [receiverATA] = anchor.web3.PublicKey.findProgramAddressSync( + [receiver.publicKey.toBytes(), TOKEN_2022_PROGRAM_ID.toBytes(), mint.toBytes()], + ATA_PROGRAM_ID, + ); + + it("Create Token-2022 Token", async () => { + // await connection.requestAirdrop(receiver.publicKey, 1000000000); + // await connection.requestAirdrop(wallet.publicKey, 1000000000); + const tx = new anchor.web3.Transaction(); + const [blockhash, _height] = await client.getLatestBlockhash(); + + const ix = await program.methods + .createToken(tokenName) + .accounts({ + signer: wallet.publicKey, + tokenProgram: TOKEN_2022_PROGRAM_ID, + }) + .instruction(); + + tx.recentBlockhash = blockhash; + tx.add(ix); + tx.sign(wallet.payer); + const sig = await client.processTransaction(tx); + console.log("Your transaction signature", sig); + }); + + it("Initialize payer ATA", async () => { + const tx = new anchor.web3.Transaction(); + const [blockhash, _height] = await client.getLatestBlockhash(); + + const ix = await program.methods + .createAssociatedTokenAccount() + .accounts({ + tokenAccount: payerATA, + mint: mint, + signer: wallet.publicKey, + tokenProgram: TOKEN_2022_PROGRAM_ID, + }) + .instruction(); + + tx.recentBlockhash = blockhash; + tx.add(ix); + tx.sign(wallet.payer); + const sig = await client.processTransaction(tx); + console.log("Your transaction signature", sig); + }); + + /* // This instruction is included only as a reference, but is not required to run this test, because we are using "init" in the program's transfer instruction. The create_associated_token_account instruction on the program is provided as a reference as well. it("Initialize receiver ATA", async () => { const tx = new anchor.web3.Transaction(); @@ -124,48 +104,48 @@ describe("anchor", async () => { }); */ - it("Mint Token to payer", async () => { - const tx = new anchor.web3.Transaction(); - const [blockhash, _height] = await client.getLatestBlockhash(); - - const ix = await program.methods - .mintToken(new BN(200000000)) - .accounts({ - mint: mint, - signer: wallet.publicKey, - receiver: payerATA, - tokenProgram: TOKEN_2022_PROGRAM_ID, - }) - .instruction(); - - tx.recentBlockhash = blockhash; - tx.add(ix); - tx.sign(wallet.payer); - const sig = await client.processTransaction(tx); - console.log("Your transaction signature", sig); - }); - - // Using init in the transfer instruction, as init if needed is bot working with Token 2022 yet. - it("Transfer Token", async () => { - const tx = new anchor.web3.Transaction(); - const [blockhash, _height] = await client.getLatestBlockhash(); - - const ix = await program.methods - .transferToken(new BN(100)) - .accounts({ - mint: mint, - signer: wallet.publicKey, - from: payerATA, - to: receiver.publicKey, - tokenProgram: TOKEN_2022_PROGRAM_ID, - toAta: receiverATA, - }) - .instruction(); - - tx.recentBlockhash = blockhash; - tx.add(ix); - tx.sign(wallet.payer); - const sig = await client.processTransaction(tx); - console.log("Your transaction signature", sig); - }); + it("Mint Token to payer", async () => { + const tx = new anchor.web3.Transaction(); + const [blockhash, _height] = await client.getLatestBlockhash(); + + const ix = await program.methods + .mintToken(new BN(200000000)) + .accounts({ + mint: mint, + signer: wallet.publicKey, + receiver: payerATA, + tokenProgram: TOKEN_2022_PROGRAM_ID, + }) + .instruction(); + + tx.recentBlockhash = blockhash; + tx.add(ix); + tx.sign(wallet.payer); + const sig = await client.processTransaction(tx); + console.log("Your transaction signature", sig); + }); + + // Using init in the transfer instruction, as init if needed is bot working with Token 2022 yet. + it("Transfer Token", async () => { + const tx = new anchor.web3.Transaction(); + const [blockhash, _height] = await client.getLatestBlockhash(); + + const ix = await program.methods + .transferToken(new BN(100)) + .accounts({ + mint: mint, + signer: wallet.publicKey, + from: payerATA, + to: receiver.publicKey, + tokenProgram: TOKEN_2022_PROGRAM_ID, + toAta: receiverATA, + }) + .instruction(); + + tx.recentBlockhash = blockhash; + tx.add(ix); + tx.sign(wallet.payer); + const sig = await client.processTransaction(tx); + console.log("Your transaction signature", sig); + }); }); diff --git a/tokens/token-2022/cpi-guard/anchor/migrations/deploy.ts b/tokens/token-2022/cpi-guard/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/tokens/token-2022/cpi-guard/anchor/migrations/deploy.ts +++ b/tokens/token-2022/cpi-guard/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/token-2022/cpi-guard/anchor/package.json b/tokens/token-2022/cpi-guard/anchor/package.json index ec93e2a0e..2c9c49143 100644 --- a/tokens/token-2022/cpi-guard/anchor/package.json +++ b/tokens/token-2022/cpi-guard/anchor/package.json @@ -1,23 +1,23 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.4.6" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "anchor-bankrun": "^0.4.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "solana-bankrun": "^0.3.0", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.4.6" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "anchor-bankrun": "^0.4.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "solana-bankrun": "^0.3.0", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-2022/cpi-guard/anchor/tests/cpi-guard.ts b/tokens/token-2022/cpi-guard/anchor/tests/cpi-guard.ts index 6a727a599..f9b3969b4 100644 --- a/tokens/token-2022/cpi-guard/anchor/tests/cpi-guard.ts +++ b/tokens/token-2022/cpi-guard/anchor/tests/cpi-guard.ts @@ -1,5 +1,5 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; import { createEnableCpiGuardInstruction, createInitializeAccountInstruction, @@ -9,11 +9,11 @@ import { getAccountLen, mintTo, TOKEN_2022_PROGRAM_ID, -} from '@solana/spl-token'; -import { SystemProgram, sendAndConfirmTransaction, Transaction } from '@solana/web3.js'; -import type { CpiGuard } from '../target/types/cpi_guard'; +} from "@solana/spl-token"; +import { SystemProgram, sendAndConfirmTransaction, Transaction } from "@solana/web3.js"; +import type { CpiGuard } from "../target/types/cpi_guard"; -describe('cpi-guard', () => { +describe("cpi-guard", () => { // Configure the client to use the local cluster. const provider = anchor.AnchorProvider.env(); const connection = provider.connection; @@ -25,7 +25,7 @@ describe('cpi-guard', () => { const mintKeypair = new anchor.web3.Keypair(); const tokenKeypair = new anchor.web3.Keypair(); - it('Create Token Account with CpiGuard extension', async () => { + it("Create Token Account with CpiGuard extension", async () => { await createMint( connection, wallet.payer, // Payer of the transaction and initialization fees @@ -60,9 +60,18 @@ describe('cpi-guard', () => { ); // Instruction to initialize the CpiGuard Extension - const enableCpiGuiardInstruction = createEnableCpiGuardInstruction(tokenKeypair.publicKey, wallet.publicKey, [], TOKEN_2022_PROGRAM_ID); + const enableCpiGuiardInstruction = createEnableCpiGuardInstruction( + tokenKeypair.publicKey, + wallet.publicKey, + [], + TOKEN_2022_PROGRAM_ID, + ); - const transaction = new Transaction().add(createAccountInstruction, initializeAccountInstruction, enableCpiGuiardInstruction); + const transaction = new Transaction().add( + createAccountInstruction, + initializeAccountInstruction, + enableCpiGuiardInstruction, + ); const transactionSignature = await sendAndConfirmTransaction( connection, @@ -70,12 +79,22 @@ describe('cpi-guard', () => { [wallet.payer, tokenKeypair], // Signers ); - await mintTo(connection, wallet.payer, mintKeypair.publicKey, tokenKeypair.publicKey, wallet.payer, 1, [], null, TOKEN_2022_PROGRAM_ID); + await mintTo( + connection, + wallet.payer, + mintKeypair.publicKey, + tokenKeypair.publicKey, + wallet.payer, + 1, + [], + null, + TOKEN_2022_PROGRAM_ID, + ); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); - it('Transfer, expect fail', async () => { + it("Transfer, expect fail", async () => { try { await program.methods .cpiTransfer() @@ -86,16 +105,21 @@ describe('cpi-guard', () => { }) .rpc({ skipPreflight: true }); } catch (error) { - console.log('\nExpect Error:', error.message); + console.log("\nExpect Error:", error.message); } }); - it('Disable CpiGuard', async () => { - const transactionSignature = await disableCpiGuard(connection, wallet.payer, tokenKeypair.publicKey, wallet.publicKey); - console.log('Your transaction signature', transactionSignature); + it("Disable CpiGuard", async () => { + const transactionSignature = await disableCpiGuard( + connection, + wallet.payer, + tokenKeypair.publicKey, + wallet.publicKey, + ); + console.log("Your transaction signature", transactionSignature); }); - it('Transfer, expect success', async () => { + it("Transfer, expect success", async () => { const transactionSignature = await program.methods .cpiTransfer() .accounts({ @@ -104,6 +128,6 @@ describe('cpi-guard', () => { mintAccount: mintKeypair.publicKey, }) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); }); diff --git a/tokens/token-2022/default-account-state/anchor/migrations/deploy.ts b/tokens/token-2022/default-account-state/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/tokens/token-2022/default-account-state/anchor/migrations/deploy.ts +++ b/tokens/token-2022/default-account-state/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/token-2022/default-account-state/anchor/package.json b/tokens/token-2022/default-account-state/anchor/package.json index f800607c4..0ab4611da 100644 --- a/tokens/token-2022/default-account-state/anchor/package.json +++ b/tokens/token-2022/default-account-state/anchor/package.json @@ -1,21 +1,21 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.4.6" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.4.6" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-2022/default-account-state/anchor/tests/default-account-state.ts b/tokens/token-2022/default-account-state/anchor/tests/default-account-state.ts index ae32cccbb..3e82cc4c2 100644 --- a/tokens/token-2022/default-account-state/anchor/tests/default-account-state.ts +++ b/tokens/token-2022/default-account-state/anchor/tests/default-account-state.ts @@ -1,9 +1,9 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; -import { createAccount, mintTo, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; -import type { DefaultAccountState } from '../target/types/default_account_state'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; +import { createAccount, mintTo, TOKEN_2022_PROGRAM_ID } from "@solana/spl-token"; +import type { DefaultAccountState } from "../target/types/default_account_state"; -describe('default-account-state', () => { +describe("default-account-state", () => { const provider = anchor.AnchorProvider.env(); const connection = provider.connection; const wallet = provider.wallet as anchor.Wallet; @@ -13,16 +13,16 @@ describe('default-account-state', () => { const mintKeypair = new anchor.web3.Keypair(); - it('Create Mint with DefaultAccountState extension', async () => { + it("Create Mint with DefaultAccountState extension", async () => { const transactionSignature = await program.methods .initialize() .accounts({ mintAccount: mintKeypair.publicKey }) .signers([mintKeypair]) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); - it('Attempt Mint Token, expect fail', async () => { + it("Attempt Mint Token, expect fail", async () => { const amount = 1; // Create a token account, default state is frozen @@ -50,20 +50,20 @@ describe('default-account-state', () => { TOKEN_2022_PROGRAM_ID, // Token Extension Program ID ); } catch (error) { - console.log('\nExpect Error:', error.logs); + console.log("\nExpect Error:", error.logs); } }); - it('Update DefaultAccountState', async () => { + it("Update DefaultAccountState", async () => { // Update the default state to initialized (not frozen) const transactionSignature = await program.methods .updateDefaultState({ initialized: {} }) .accounts({ mintAccount: mintKeypair.publicKey }) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); - it('Attempt Mint Token, expect success', async () => { + it("Attempt Mint Token, expect success", async () => { const amount = 1; // Create a token account, default state is initialized (not frozen) diff --git a/tokens/token-2022/default-account-state/native/tests/test.ts b/tokens/token-2022/default-account-state/native/tests/test.ts index 01631bd34..381e14945 100644 --- a/tokens/token-2022/default-account-state/native/tests/test.ts +++ b/tokens/token-2022/default-account-state/native/tests/test.ts @@ -1,24 +1,30 @@ -import { Buffer } from 'node:buffer'; -import { describe, test } from 'node:test'; -import { TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; -import { Keypair, PublicKey, SYSVAR_RENT_PUBKEY, SystemProgram, Transaction, TransactionInstruction } from '@solana/web3.js'; -import * as borsh from 'borsh'; -import { assert } from 'chai'; -import { start } from 'solana-bankrun'; +import { Buffer } from "node:buffer"; +import { describe, test } from "node:test"; +import { TOKEN_2022_PROGRAM_ID } from "@solana/spl-token"; +import { + Keypair, + PublicKey, + SYSVAR_RENT_PUBKEY, + SystemProgram, + Transaction, + TransactionInstruction, +} from "@solana/web3.js"; +import * as borsh from "borsh"; +import { assert } from "chai"; +import { start } from "solana-bankrun"; - -const CreateTokenArgsSchema = { struct: { token_decimals: 'u8' } }; +const CreateTokenArgsSchema = { struct: { token_decimals: "u8" } }; function borshSerialize(schema: borsh.Schema, data: object): Buffer { return Buffer.from(borsh.serialize(schema, data)); } -describe('Create Token', async () => { +describe("Create Token", async () => { const PROGRAM_ID = PublicKey.unique(); const context = await start( [ { - name: 'token_2022_default_account_state_program', + name: "token_2022_default_account_state_program", programId: PROGRAM_ID, }, ], @@ -27,7 +33,7 @@ describe('Create Token', async () => { const client = context.banksClient; const payer = context.payer; - test('Create a Token-22 SPL-Token !', async () => { + test("Create a Token-22 SPL-Token !", async () => { const blockhash = context.lastBlockhash; const mintKeypair: Keypair = Keypair.generate(); @@ -56,6 +62,6 @@ describe('Create Token', async () => { const transaction = await client.processTransaction(tx); assert(transaction.logMessages[0].startsWith(`Program ${PROGRAM_ID}`)); - console.log('Token Mint Address: ', mintKeypair.publicKey.toBase58()); + console.log("Token Mint Address: ", mintKeypair.publicKey.toBase58()); }); }); diff --git a/tokens/token-2022/group/anchor/migrations/deploy.ts b/tokens/token-2022/group/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/tokens/token-2022/group/anchor/migrations/deploy.ts +++ b/tokens/token-2022/group/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/token-2022/group/anchor/package.json b/tokens/token-2022/group/anchor/package.json index 198383d3f..a41a8b7d2 100644 --- a/tokens/token-2022/group/anchor/package.json +++ b/tokens/token-2022/group/anchor/package.json @@ -1,20 +1,20 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-2022/group/anchor/tests/group.ts b/tokens/token-2022/group/anchor/tests/group.ts index 7756b0ca3..c3344bce5 100644 --- a/tokens/token-2022/group/anchor/tests/group.ts +++ b/tokens/token-2022/group/anchor/tests/group.ts @@ -1,8 +1,8 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; -import type { Group } from '../target/types/group'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; +import type { Group } from "../target/types/group"; -describe('group', () => { +describe("group", () => { // Configure the client to use the local cluster. const provider = anchor.AnchorProvider.env(); const _connection = provider.connection; @@ -11,8 +11,8 @@ describe('group', () => { const program = anchor.workspace.Group as Program; - it('Create Mint with Group Pointer', async () => { + it("Create Mint with Group Pointer", async () => { const transactionSignature = await program.methods.testInitializeGroup().accounts({}).rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); }); diff --git a/tokens/token-2022/immutable-owner/anchor/migrations/deploy.ts b/tokens/token-2022/immutable-owner/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/tokens/token-2022/immutable-owner/anchor/migrations/deploy.ts +++ b/tokens/token-2022/immutable-owner/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/token-2022/immutable-owner/anchor/package.json b/tokens/token-2022/immutable-owner/anchor/package.json index f800607c4..0ab4611da 100644 --- a/tokens/token-2022/immutable-owner/anchor/package.json +++ b/tokens/token-2022/immutable-owner/anchor/package.json @@ -1,21 +1,21 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.4.6" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.4.6" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-2022/immutable-owner/anchor/tests/immutable-owner.ts b/tokens/token-2022/immutable-owner/anchor/tests/immutable-owner.ts index 8e2015dba..7202b1d5b 100644 --- a/tokens/token-2022/immutable-owner/anchor/tests/immutable-owner.ts +++ b/tokens/token-2022/immutable-owner/anchor/tests/immutable-owner.ts @@ -1,9 +1,9 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; -import { AuthorityType, createMint, setAuthority, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; -import type { ImmutableOwner } from '../target/types/immutable_owner'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; +import { AuthorityType, createMint, setAuthority, TOKEN_2022_PROGRAM_ID } from "@solana/spl-token"; +import type { ImmutableOwner } from "../target/types/immutable_owner"; -describe('immutable-owner', () => { +describe("immutable-owner", () => { // Configure the client to use the local cluster. const provider = anchor.AnchorProvider.env(); const connection = provider.connection; @@ -14,7 +14,7 @@ describe('immutable-owner', () => { const tokenKeypair = new anchor.web3.Keypair(); - it('Create Token Account with ImmutableOwner extension', async () => { + it("Create Token Account with ImmutableOwner extension", async () => { const mint = await createMint( connection, wallet.payer, // Payer of the transaction and initialization fees @@ -34,10 +34,10 @@ describe('immutable-owner', () => { }) .signers([tokenKeypair]) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); - it('Attempt to change token account owner, expect fail', async () => { + it("Attempt to change token account owner, expect fail", async () => { try { await setAuthority( connection, // Connection to use @@ -51,7 +51,7 @@ describe('immutable-owner', () => { TOKEN_2022_PROGRAM_ID, // Token Extension Program ID ); } catch (error) { - console.log('\nExpect Error:', error.logs); + console.log("\nExpect Error:", error.logs); } }); }); diff --git a/tokens/token-2022/interest-bearing/anchor/migrations/deploy.ts b/tokens/token-2022/interest-bearing/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/tokens/token-2022/interest-bearing/anchor/migrations/deploy.ts +++ b/tokens/token-2022/interest-bearing/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/token-2022/interest-bearing/anchor/package.json b/tokens/token-2022/interest-bearing/anchor/package.json index f800607c4..0ab4611da 100644 --- a/tokens/token-2022/interest-bearing/anchor/package.json +++ b/tokens/token-2022/interest-bearing/anchor/package.json @@ -1,21 +1,21 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.4.6" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.4.6" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-2022/interest-bearing/anchor/tests/interest-bearing.ts b/tokens/token-2022/interest-bearing/anchor/tests/interest-bearing.ts index 45a2938a7..bc1f83a19 100644 --- a/tokens/token-2022/interest-bearing/anchor/tests/interest-bearing.ts +++ b/tokens/token-2022/interest-bearing/anchor/tests/interest-bearing.ts @@ -1,9 +1,9 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; -import { amountToUiAmount, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; -import type { InterestBearing } from '../target/types/interest_bearing'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; +import { amountToUiAmount, TOKEN_2022_PROGRAM_ID } from "@solana/spl-token"; +import type { InterestBearing } from "../target/types/interest_bearing"; -describe('interest-bearing', () => { +describe("interest-bearing", () => { // Configure the client to use the local cluster. const provider = anchor.AnchorProvider.env(); const connection = provider.connection; @@ -14,7 +14,7 @@ describe('interest-bearing', () => { const mintKeypair = new anchor.web3.Keypair(); - it('Create Mint with InterestBearingConfig extension', async () => { + it("Create Mint with InterestBearingConfig extension", async () => { const rate = 0; const transactionSignature = await program.methods @@ -22,17 +22,20 @@ describe('interest-bearing', () => { .accounts({ mintAccount: mintKeypair.publicKey }) .signers([mintKeypair]) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); - it('Update Mint with Interest Rate', async () => { + it("Update Mint with Interest Rate", async () => { const rate = 100; - const transactionSignature = await program.methods.updateRate(rate).accounts({ mintAccount: mintKeypair.publicKey }).rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + const transactionSignature = await program.methods + .updateRate(rate) + .accounts({ mintAccount: mintKeypair.publicKey }) + .rpc({ skipPreflight: true }); + console.log("Your transaction signature", transactionSignature); }); - it('Calculate accrued interest', async () => { + it("Calculate accrued interest", async () => { await sleep(1); const amount = 1000; @@ -46,7 +49,7 @@ describe('interest-bearing', () => { TOKEN_2022_PROGRAM_ID, // Token Extension Program ID ); - console.log('\nAmount with Accrued Interest:', uiAmount); + console.log("\nAmount with Accrued Interest:", uiAmount); }); }); diff --git a/tokens/token-2022/memo-transfer/anchor/migrations/deploy.ts b/tokens/token-2022/memo-transfer/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/tokens/token-2022/memo-transfer/anchor/migrations/deploy.ts +++ b/tokens/token-2022/memo-transfer/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/token-2022/memo-transfer/anchor/package.json b/tokens/token-2022/memo-transfer/anchor/package.json index a3f2b8fe6..6c9523931 100644 --- a/tokens/token-2022/memo-transfer/anchor/package.json +++ b/tokens/token-2022/memo-transfer/anchor/package.json @@ -1,22 +1,22 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-memo": "^0.2.5", - "@solana/spl-token": "^0.4.6" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-memo": "^0.2.5", + "@solana/spl-token": "^0.4.6" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-2022/memo-transfer/anchor/tests/memo-transfer.ts b/tokens/token-2022/memo-transfer/anchor/tests/memo-transfer.ts index 3a236ca14..5071464b0 100644 --- a/tokens/token-2022/memo-transfer/anchor/tests/memo-transfer.ts +++ b/tokens/token-2022/memo-transfer/anchor/tests/memo-transfer.ts @@ -1,11 +1,11 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; -import { createMemoInstruction } from '@solana/spl-memo'; -import { createAccount, createMint, createTransferInstruction, mintTo, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; -import { sendAndConfirmTransaction, Transaction } from '@solana/web3.js'; -import type { MemoTransfer } from '../target/types/memo_transfer'; - -describe('memo-transfer', () => { +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; +import { createMemoInstruction } from "@solana/spl-memo"; +import { createAccount, createMint, createTransferInstruction, mintTo, TOKEN_2022_PROGRAM_ID } from "@solana/spl-token"; +import { sendAndConfirmTransaction, Transaction } from "@solana/web3.js"; +import type { MemoTransfer } from "../target/types/memo_transfer"; + +describe("memo-transfer", () => { // Configure the client to use the local cluster. const provider = anchor.AnchorProvider.env(); const connection = provider.connection; @@ -17,7 +17,7 @@ describe('memo-transfer', () => { const mintKeypair = new anchor.web3.Keypair(); const tokenKeypair = new anchor.web3.Keypair(); - it('Create Token Account with RequiredMemo extension', async () => { + it("Create Token Account with RequiredMemo extension", async () => { await createMint( connection, wallet.payer, // Payer of the transaction and initialization fees @@ -37,10 +37,10 @@ describe('memo-transfer', () => { }) .signers([tokenKeypair]) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); - it('Attempt transfer without memo, expect fail', async () => { + it("Attempt transfer without memo, expect fail", async () => { // Create a new token account to transfer to const sourceTokenAccount = await createAccount( connection, @@ -52,7 +52,17 @@ describe('memo-transfer', () => { TOKEN_2022_PROGRAM_ID, // Token Extension Program ID ); - await mintTo(connection, wallet.payer, mintKeypair.publicKey, sourceTokenAccount, wallet.payer, 1, [], null, TOKEN_2022_PROGRAM_ID); + await mintTo( + connection, + wallet.payer, + mintKeypair.publicKey, + sourceTokenAccount, + wallet.payer, + 1, + [], + null, + TOKEN_2022_PROGRAM_ID, + ); const transferInstruction = createTransferInstruction( sourceTokenAccount, // Source Token Account @@ -73,11 +83,11 @@ describe('memo-transfer', () => { [wallet.payer], // Signers ); } catch (error) { - console.log('\nExpect Error:', error.logs); + console.log("\nExpect Error:", error.logs); } }); - it('Attempt transfer with memo, expect success', async () => { + it("Attempt transfer with memo, expect success", async () => { // Create a new token account to transfer to const sourceTokenAccount = await createAccount( connection, @@ -89,9 +99,19 @@ describe('memo-transfer', () => { TOKEN_2022_PROGRAM_ID, // Token Extension Program ID ); - await mintTo(connection, wallet.payer, mintKeypair.publicKey, sourceTokenAccount, wallet.payer, 1, [], null, TOKEN_2022_PROGRAM_ID); + await mintTo( + connection, + wallet.payer, + mintKeypair.publicKey, + sourceTokenAccount, + wallet.payer, + 1, + [], + null, + TOKEN_2022_PROGRAM_ID, + ); - const memoInstruction = createMemoInstruction('hello, world', [wallet.publicKey]); + const memoInstruction = createMemoInstruction("hello, world", [wallet.publicKey]); const transferInstruction = createTransferInstruction( sourceTokenAccount, // Source Token Account @@ -110,20 +130,20 @@ describe('memo-transfer', () => { [wallet.payer], // Signers ); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); - it('Disable RequiredMemo extension', async () => { + it("Disable RequiredMemo extension", async () => { const transactionSignature = await program.methods .disable() .accounts({ tokenAccount: tokenKeypair.publicKey, }) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); - it('Attempt transfer without memo, expect success', async () => { + it("Attempt transfer without memo, expect success", async () => { // Create a new token account to transfer to const sourceTokenAccount = await createAccount( connection, @@ -135,7 +155,17 @@ describe('memo-transfer', () => { TOKEN_2022_PROGRAM_ID, // Token Extension Program ID ); - await mintTo(connection, wallet.payer, mintKeypair.publicKey, sourceTokenAccount, wallet.payer, 1, [], null, TOKEN_2022_PROGRAM_ID); + await mintTo( + connection, + wallet.payer, + mintKeypair.publicKey, + sourceTokenAccount, + wallet.payer, + 1, + [], + null, + TOKEN_2022_PROGRAM_ID, + ); const transferInstruction = createTransferInstruction( sourceTokenAccount, // Source Token Account @@ -154,6 +184,6 @@ describe('memo-transfer', () => { [wallet.payer], // Signers ); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); }); diff --git a/tokens/token-2022/metadata/anchor/migrations/deploy.ts b/tokens/token-2022/metadata/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/tokens/token-2022/metadata/anchor/migrations/deploy.ts +++ b/tokens/token-2022/metadata/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/token-2022/metadata/anchor/package.json b/tokens/token-2022/metadata/anchor/package.json index 95288be45..f46c7b95c 100644 --- a/tokens/token-2022/metadata/anchor/package.json +++ b/tokens/token-2022/metadata/anchor/package.json @@ -1,21 +1,21 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token-metadata": "^0.1.4" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token-metadata": "^0.1.4" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-2022/metadata/anchor/tests/metadata.ts b/tokens/token-2022/metadata/anchor/tests/metadata.ts index c788bd0f9..b88a03944 100644 --- a/tokens/token-2022/metadata/anchor/tests/metadata.ts +++ b/tokens/token-2022/metadata/anchor/tests/metadata.ts @@ -1,9 +1,9 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; -import { unpack } from '@solana/spl-token-metadata'; -import type { Metadata } from '../target/types/metadata'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; +import { unpack } from "@solana/spl-token-metadata"; +import type { Metadata } from "../target/types/metadata"; -describe('metadata', () => { +describe("metadata", () => { const provider = anchor.AnchorProvider.env(); anchor.setProvider(provider); @@ -12,52 +12,52 @@ describe('metadata', () => { const mintKeypair = new anchor.web3.Keypair(); const metadata = { - name: 'OPOS', - symbol: 'OPOS', - uri: 'https://raw.githubusercontent.com/solana-developers/opos-asset/main/assets/DeveloperPortal/metadata.json', + name: "OPOS", + symbol: "OPOS", + uri: "https://raw.githubusercontent.com/solana-developers/opos-asset/main/assets/DeveloperPortal/metadata.json", }; - it('Create Mint with MetadataPointer and TokenMetadata Extensions', async () => { + it("Create Mint with MetadataPointer and TokenMetadata Extensions", async () => { const tx = await program.methods .initialize(metadata) .accounts({ mintAccount: mintKeypair.publicKey }) .signers([mintKeypair]) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', tx); + console.log("Your transaction signature", tx); }); - it('Update existing metadata field', async () => { + it("Update existing metadata field", async () => { // Add your test here. const tx = await program.methods .updateField({ field: { name: {} }, // Update the name field - value: 'Solana', + value: "Solana", }) .accounts({ mintAccount: mintKeypair.publicKey }) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', tx); + console.log("Your transaction signature", tx); }); - it('Update metadata with custom field', async () => { + it("Update metadata with custom field", async () => { const tx = await program.methods .updateField({ - field: { key: { 0: 'color' } }, // Add a custom field named "color" - value: 'red', + field: { key: { 0: "color" } }, // Add a custom field named "color" + value: "red", }) .accounts({ mintAccount: mintKeypair.publicKey }) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', tx); + console.log("Your transaction signature", tx); }); - it('Remove custom field', async () => { + it("Remove custom field", async () => { const tx = await program.methods - .removeKey('color') // Remove the custom field named "color" + .removeKey("color") // Remove the custom field named "color" .accounts({ mintAccount: mintKeypair.publicKey }) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', tx); + console.log("Your transaction signature", tx); }); - it('Change update authority', async () => { + it("Change update authority", async () => { const tx = await program.methods .updateAuthority() .accounts({ @@ -65,45 +65,45 @@ describe('metadata', () => { newAuthority: null, // Set the update authority to null }) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', tx); + console.log("Your transaction signature", tx); }); - it('Emit metadata, decode transaction logs', async () => { + it("Emit metadata, decode transaction logs", async () => { const txSignature = await program.methods .emit() .accounts({ mintAccount: mintKeypair.publicKey }) - .rpc({ commitment: 'confirmed', skipPreflight: true }); - console.log('Your transaction signature', txSignature); + .rpc({ commitment: "confirmed", skipPreflight: true }); + console.log("Your transaction signature", txSignature); // Fetch the transaction response const transactionResponse = await provider.connection.getTransaction(txSignature, { - commitment: 'confirmed', + commitment: "confirmed", }); // Extract the log message that starts with "Program return:" - const prefix = 'Program return: '; + const prefix = "Program return: "; let log = transactionResponse.meta.logMessages.find((log) => log.startsWith(prefix)); log = log.slice(prefix.length); - const [_, data] = log.split(' ', 2); + const [_, data] = log.split(" ", 2); // Decode the data from base64 and unpack it into TokenMetadata - const buffer = Buffer.from(data, 'base64'); + const buffer = Buffer.from(data, "base64"); const metadata = unpack(buffer); - console.log('Metadata', metadata); + console.log("Metadata", metadata); }); - it('Emit metadata, decode simulated transaction', async () => { + it("Emit metadata, decode simulated transaction", async () => { const simulateResponse = await program.methods.emit().accounts({ mintAccount: mintKeypair.publicKey }).simulate(); // Extract the log message that starts with "Program return:" - const prefix = 'Program return: '; + const prefix = "Program return: "; let log = simulateResponse.raw.find((log) => log.startsWith(prefix)); log = log.slice(prefix.length); - const [_, data] = log.split(' ', 2); + const [_, data] = log.split(" ", 2); // Decode the data from base64 and unpack it into TokenMetadata - const buffer = Buffer.from(data, 'base64'); + const buffer = Buffer.from(data, "base64"); const metadata = unpack(buffer); - console.log('Metadata', metadata); + console.log("Metadata", metadata); }); }); diff --git a/tokens/token-2022/mint-close-authority/anchor/migrations/deploy.ts b/tokens/token-2022/mint-close-authority/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/tokens/token-2022/mint-close-authority/anchor/migrations/deploy.ts +++ b/tokens/token-2022/mint-close-authority/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/token-2022/mint-close-authority/anchor/package.json b/tokens/token-2022/mint-close-authority/anchor/package.json index f800607c4..0ab4611da 100644 --- a/tokens/token-2022/mint-close-authority/anchor/package.json +++ b/tokens/token-2022/mint-close-authority/anchor/package.json @@ -1,21 +1,21 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.4.6" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.4.6" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-2022/mint-close-authority/anchor/tests/mint-close-authority.ts b/tokens/token-2022/mint-close-authority/anchor/tests/mint-close-authority.ts index 73b08722a..05d1bc7a5 100644 --- a/tokens/token-2022/mint-close-authority/anchor/tests/mint-close-authority.ts +++ b/tokens/token-2022/mint-close-authority/anchor/tests/mint-close-authority.ts @@ -1,9 +1,9 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; -import { closeAccount, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; -import type { MintCloseAuthority } from '../target/types/mint_close_authority'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; +import { closeAccount, TOKEN_2022_PROGRAM_ID } from "@solana/spl-token"; +import type { MintCloseAuthority } from "../target/types/mint_close_authority"; -describe('mint-close-authority', () => { +describe("mint-close-authority", () => { // Configure the client to use the local cluster. const provider = anchor.AnchorProvider.env(); const connection = provider.connection; @@ -14,30 +14,33 @@ describe('mint-close-authority', () => { const mintKeypair = new anchor.web3.Keypair(); - it('Create Mint with Close Authority', async () => { + it("Create Mint with Close Authority", async () => { const transactionSignature = await program.methods .initialize() .accounts({ mintAccount: mintKeypair.publicKey }) .signers([mintKeypair]) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); - it('Close Mint with Anchor CPI', async () => { - const transactionSignature = await program.methods.close().accounts({ mintAccount: mintKeypair.publicKey }).rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + it("Close Mint with Anchor CPI", async () => { + const transactionSignature = await program.methods + .close() + .accounts({ mintAccount: mintKeypair.publicKey }) + .rpc({ skipPreflight: true }); + console.log("Your transaction signature", transactionSignature); }); - it('Create Mint with Close Authority again', async () => { + it("Create Mint with Close Authority again", async () => { const transactionSignature = await program.methods .initialize() .accounts({ mintAccount: mintKeypair.publicKey }) .signers([mintKeypair]) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); - it('Close Mint using @solana/spl-token', async () => { + it("Close Mint using @solana/spl-token", async () => { const transactionSignature = await closeAccount( connection, wallet.payer, // Transaction fee payer @@ -48,6 +51,6 @@ describe('mint-close-authority', () => { undefined, // Confirmation options TOKEN_2022_PROGRAM_ID, // Token Extension Program ID ); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); }); diff --git a/tokens/token-2022/mint-close-authority/native/tests/test.ts b/tokens/token-2022/mint-close-authority/native/tests/test.ts index 8d4ce50f2..822c359df 100644 --- a/tokens/token-2022/mint-close-authority/native/tests/test.ts +++ b/tokens/token-2022/mint-close-authority/native/tests/test.ts @@ -1,24 +1,30 @@ -import { Buffer } from 'node:buffer'; -import { describe, test } from 'node:test'; -import { TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; -import { Keypair, PublicKey, SYSVAR_RENT_PUBKEY, SystemProgram, Transaction, TransactionInstruction } from '@solana/web3.js'; -import * as borsh from 'borsh'; -import { assert } from 'chai'; -import { start } from 'solana-bankrun'; +import { Buffer } from "node:buffer"; +import { describe, test } from "node:test"; +import { TOKEN_2022_PROGRAM_ID } from "@solana/spl-token"; +import { + Keypair, + PublicKey, + SYSVAR_RENT_PUBKEY, + SystemProgram, + Transaction, + TransactionInstruction, +} from "@solana/web3.js"; +import * as borsh from "borsh"; +import { assert } from "chai"; +import { start } from "solana-bankrun"; - -const CreateTokenArgsSchema = { struct: { token_decimals: 'u8' } }; +const CreateTokenArgsSchema = { struct: { token_decimals: "u8" } }; function borshSerialize(schema: borsh.Schema, data: object): Buffer { return Buffer.from(borsh.serialize(schema, data)); } -describe('Create Token', async () => { +describe("Create Token", async () => { const PROGRAM_ID = PublicKey.unique(); const context = await start( [ { - name: 'token_2022_mint_close_authority_program', + name: "token_2022_mint_close_authority_program", programId: PROGRAM_ID, }, ], @@ -27,7 +33,7 @@ describe('Create Token', async () => { const client = context.banksClient; const payer = context.payer; - test('Create a Token-22 SPL-Token !', async () => { + test("Create a Token-22 SPL-Token !", async () => { const mintKeypair: Keypair = Keypair.generate(); const instructionData = borshSerialize(CreateTokenArgsSchema, { @@ -56,6 +62,6 @@ describe('Create Token', async () => { const transaction = await client.processTransaction(tx); assert(transaction.logMessages[0].startsWith(`Program ${PROGRAM_ID}`)); - console.log('Token Mint Address: ', mintKeypair.publicKey.toBase58()); + console.log("Token Mint Address: ", mintKeypair.publicKey.toBase58()); }); }); diff --git a/tokens/token-2022/multiple-extensions/native/tests/test.ts b/tokens/token-2022/multiple-extensions/native/tests/test.ts index 94757d648..f5b165793 100644 --- a/tokens/token-2022/multiple-extensions/native/tests/test.ts +++ b/tokens/token-2022/multiple-extensions/native/tests/test.ts @@ -1,25 +1,31 @@ -import { Buffer } from 'node:buffer'; -import { describe, test } from 'node:test'; -import { TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; -import { Keypair, PublicKey, SYSVAR_RENT_PUBKEY, SystemProgram, Transaction, TransactionInstruction } from '@solana/web3.js'; -import * as borsh from 'borsh'; -import { assert } from 'chai'; -import { start } from 'solana-bankrun'; - - -const CreateTokenArgsSchema = { struct: { token_decimals: 'u8' } }; +import { Buffer } from "node:buffer"; +import { describe, test } from "node:test"; +import { TOKEN_2022_PROGRAM_ID } from "@solana/spl-token"; +import { + Keypair, + PublicKey, + SYSVAR_RENT_PUBKEY, + SystemProgram, + Transaction, + TransactionInstruction, +} from "@solana/web3.js"; +import * as borsh from "borsh"; +import { assert } from "chai"; +import { start } from "solana-bankrun"; + +const CreateTokenArgsSchema = { struct: { token_decimals: "u8" } }; function borshSerialize(schema: borsh.Schema, data: object): Buffer { return Buffer.from(borsh.serialize(schema, data)); } -describe('Create Token', async () => { +describe("Create Token", async () => { const PROGRAM_ID = PublicKey.unique(); - const context = await start([{ name: 'token_2022_multiple_extensions_program', programId: PROGRAM_ID }], []); + const context = await start([{ name: "token_2022_multiple_extensions_program", programId: PROGRAM_ID }], []); const client = context.banksClient; const payer = context.payer; - test('Create a Token-22 SPL-Token !', async () => { + test("Create a Token-22 SPL-Token !", async () => { const blockhash = context.lastBlockhash; const mintKeypair: Keypair = Keypair.generate(); @@ -48,6 +54,6 @@ describe('Create Token', async () => { const transaction = await client.processTransaction(tx); assert(transaction.logMessages[0].startsWith(`Program ${PROGRAM_ID}`)); - console.log('Token Mint Address: ', mintKeypair.publicKey.toBase58()); + console.log("Token Mint Address: ", mintKeypair.publicKey.toBase58()); }); }); diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/anchor/migrations/deploy.ts b/tokens/token-2022/nft-meta-data-pointer/anchor-example/anchor/migrations/deploy.ts index 0a1222c93..20e6e1c1b 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/anchor/migrations/deploy.ts +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@project-serum/anchor'); +const anchor = require("@project-serum/anchor"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/anchor/package.json b/tokens/token-2022/nft-meta-data-pointer/anchor-example/anchor/package.json index 691d96bb6..07210e989 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/anchor/package.json +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/anchor/package.json @@ -1,24 +1,24 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@coral-xyz/spl-token": "0.30.0", - "@solana/spl-token": "^0.4.0" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "browserify-sign": ">=4.2.2", - "chai": "^4.3.4", - "crypto-js": ">=4.2.0", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^4.3.5" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@coral-xyz/spl-token": "0.30.0", + "@solana/spl-token": "^0.4.0" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "browserify-sign": ">=4.2.2", + "chai": "^4.3.4", + "crypto-js": ">=4.2.0", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^4.3.5" + } } diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/anchor/tests/lumberjack.ts b/tokens/token-2022/nft-meta-data-pointer/anchor-example/anchor/tests/lumberjack.ts index bbba9941f..ebb22db4e 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/anchor/tests/lumberjack.ts +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/anchor/tests/lumberjack.ts @@ -1,30 +1,30 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; import { ASSOCIATED_TOKEN_PROGRAM_ID, getAssociatedTokenAddressSync, getOrCreateAssociatedTokenAccount, TOKEN_2022_PROGRAM_ID, -} from '@solana/spl-token'; -import { Keypair } from '@solana/web3.js'; -import type { ExtensionNft } from '../target/types/extension_nft'; +} from "@solana/spl-token"; +import { Keypair } from "@solana/web3.js"; +import type { ExtensionNft } from "../target/types/extension_nft"; -describe('extension_nft', () => { +describe("extension_nft", () => { const provider = anchor.AnchorProvider.env(); anchor.setProvider(provider); const program = anchor.workspace.ExtensionNft as Program; const payer = provider.wallet as anchor.Wallet; - it('Mint nft!', async () => { + it("Mint nft!", async () => { const balance = await anchor.getProvider().connection.getBalance(payer.publicKey); if (balance < 1e8) { const res = await anchor.getProvider().connection.requestAirdrop(payer.publicKey, 1e9); - await anchor.getProvider().connection.confirmTransaction(res, 'confirmed'); + await anchor.getProvider().connection.confirmTransaction(res, "confirmed"); } const mint = new Keypair(); - console.log('Mint public key', mint.publicKey.toBase58()); + console.log("Mint public key", mint.publicKey.toBase58()); const destinationTokenAccount = getAssociatedTokenAddressSync( mint.publicKey, @@ -45,7 +45,7 @@ describe('extension_nft', () => { .signers([mint]) .rpc(); - console.log('Mint nft tx', tx); - await anchor.getProvider().connection.confirmTransaction(tx, 'confirmed'); + console.log("Mint nft tx", tx); + await anchor.getProvider().connection.confirmTransaction(tx, "confirmed"); }); }); diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/ChopTreeButton.tsx b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/ChopTreeButton.tsx index 4e3aefb1e..be58a2616 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/ChopTreeButton.tsx +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/ChopTreeButton.tsx @@ -1,40 +1,37 @@ -import Image from "next/image" -import { useCallback, useState } from "react" -import { Button, HStack, VStack } from "@chakra-ui/react" -import { useConnection, useWallet } from "@solana/wallet-adapter-react" -import { useSessionWallet } from "@magicblock-labs/gum-react-sdk" -import { useGameState } from "@/contexts/GameStateProvider" -import { GAME_DATA_SEED, gameDataPDA, program } from "@/utils/anchor" -import { PublicKey } from "@solana/web3.js" -import { useNftState } from "@/contexts/NftProvider" -import { TOKEN_2022_PROGRAM_ID } from "@solana/spl-token" +import { Button, HStack, VStack } from "@chakra-ui/react"; +import { useSessionWallet } from "@magicblock-labs/gum-react-sdk"; +import { TOKEN_2022_PROGRAM_ID } from "@solana/spl-token"; +import { useConnection, useWallet } from "@solana/wallet-adapter-react"; +import { PublicKey } from "@solana/web3.js"; +import Image from "next/image"; +import { useCallback, useState } from "react"; +import { useGameState } from "@/contexts/GameStateProvider"; +import { useNftState } from "@/contexts/NftProvider"; +import { GAME_DATA_SEED, gameDataPDA, program } from "@/utils/anchor"; const ChopTreeButton = () => { - const { publicKey, sendTransaction } = useWallet() - const { connection } = useConnection() - const sessionWallet = useSessionWallet() - const { gameState, playerDataPDA } = useGameState() - const [isLoadingSession, setIsLoadingSession] = useState(false) - const [isLoadingMainWallet, setIsLoadingMainWallet] = useState(false) - const [transactionCounter, setTransactionCounter] = useState(0) - const { nftState: nftState } = useNftState() + const { publicKey, sendTransaction } = useWallet(); + const { connection } = useConnection(); + const sessionWallet = useSessionWallet(); + const { gameState, playerDataPDA } = useGameState(); + const [isLoadingSession, setIsLoadingSession] = useState(false); + const [isLoadingMainWallet, setIsLoadingMainWallet] = useState(false); + const [transactionCounter, setTransactionCounter] = useState(0); + const { nftState } = useNftState(); const onChopClick = useCallback(async () => { - setIsLoadingSession(true) - if (!playerDataPDA || !sessionWallet) return + setIsLoadingSession(true); + if (!playerDataPDA || !sessionWallet?.publicKey) return; setTransactionCounter(transactionCounter + 1); - const nftAuthority = await PublicKey.findProgramAddress( - [Buffer.from("nft_authority")], - program.programId - ); + const nftAuthority = await PublicKey.findProgramAddress([Buffer.from("nft_authority")], program.programId); let nft = null; - - for (var i = 0; i < nftState.items.length; i++) { + + for (let i = 0; i < nftState.items.length; i++) { try { const nftData = nftState.items[i]; - if (nftData.authorities[0] == nftAuthority[0].toBase58()) { + if (nftData.authorities[0] === nftAuthority[0].toBase58()) { nft = nftData; } console.log("NFT data", nftData); @@ -56,35 +53,32 @@ const ChopTreeButton = () => { .accounts({ player: playerDataPDA, gameData: gameDataPDA, - signer: sessionWallet.publicKey!, + signer: sessionWallet.publicKey, sessionToken: sessionWallet.sessionToken, nftAuthority: nftAuthority[0], mint: nft.id, }) - .transaction() + .transaction(); - const txids = await sessionWallet.signAndSendTransaction!(transaction) + const txids = await sessionWallet.signAndSendTransaction?.(transaction); if (txids && txids.length > 0) { - console.log("Transaction sent:", txids) + console.log("Transaction sent:", txids); } else { - console.error("Failed to send transaction") + console.error("Failed to send transaction"); } - } catch (error: any) { - console.log("error", `Chopping failed! ${error?.message}`) + } catch (error) { + console.log("error", `Chopping failed! ${error instanceof Error ? error.message : String(error)}`); } finally { - setIsLoadingSession(false) + setIsLoadingSession(false); } - }, [sessionWallet, nftState]) + }, [sessionWallet, nftState, playerDataPDA, transactionCounter]); const onChopMainWalletClick = useCallback(async () => { - if (!publicKey || !playerDataPDA) return + if (!publicKey || !playerDataPDA) return; - setIsLoadingMainWallet(true) - const nftAuthority = await PublicKey.findProgramAddress( - [Buffer.from("nft_authority")], - program.programId - ); + setIsLoadingMainWallet(true); + const nftAuthority = await PublicKey.findProgramAddress([Buffer.from("nft_authority")], program.programId); if (nftState == null) { window.alert("Load NFT state first"); @@ -94,11 +88,11 @@ const ChopTreeButton = () => { console.log("NFT state", nftState); let nft = null; - for (var i = 0; i < nftState.items.length; i++) { + for (let i = 0; i < nftState.items.length; i++) { try { const nftData = nftState.items[i]; - console.log(nftData.authorities[0].address + " == " + nftAuthority[0].toBase58()); - + console.log(`${nftData.authorities[0].address} == ${nftAuthority[0].toBase58()}`); + if (nftData.authorities[0].address === nftAuthority[0].toBase58()) { nft = nftData; } @@ -115,7 +109,6 @@ const ChopTreeButton = () => { return; } try { - console.log("NFTid", nft.id, "NFT authority", nft.authorities[0].address); const transaction = await program.methods .chopTree(GAME_DATA_SEED, transactionCounter) @@ -126,20 +119,20 @@ const ChopTreeButton = () => { sessionToken: null, nftAuthority: nftAuthority[0].toBase58(), mint: nft.id, - tokenProgram: TOKEN_2022_PROGRAM_ID + tokenProgram: TOKEN_2022_PROGRAM_ID, }) - .transaction() + .transaction(); const txSig = await sendTransaction(transaction, connection, { skipPreflight: true, - }) - console.log(`https://explorer.solana.com/tx/${txSig}?cluster=devnet`) - } catch (error: any) { - console.log("error", `Chopping failed! ${error?.message}`) + }); + console.log(`https://explorer.solana.com/tx/${txSig}?cluster=devnet`); + } catch (error) { + console.log("error", `Chopping failed! ${error instanceof Error ? error.message : String(error)}`); } finally { - setIsLoadingMainWallet(false) + setIsLoadingMainWallet(false); } - }, [publicKey, playerDataPDA, connection, nftState]) + }, [publicKey, playerDataPDA, connection, nftState, transactionCounter, sendTransaction]); return ( <> @@ -148,26 +141,18 @@ const ChopTreeButton = () => { Energy Icon {sessionWallet && sessionWallet.sessionToken != null && ( - )} - )} - ) -} + ); +}; -export default ChopTreeButton +export default ChopTreeButton; diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/DisplayGameState.tsx b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/DisplayGameState.tsx index f272d664e..86f60b377 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/DisplayGameState.tsx +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/DisplayGameState.tsx @@ -1,12 +1,12 @@ -import Image from "next/image" -import { HStack, VStack, Text } from "@chakra-ui/react" -import { useWallet } from "@solana/wallet-adapter-react" -import { useGameState } from "@/contexts/GameStateProvider" -import { TOTAL_WOOD_AVAILABLE } from "@/utils/anchor" +import { HStack, Text, VStack } from "@chakra-ui/react"; +import { useWallet } from "@solana/wallet-adapter-react"; +import Image from "next/image"; +import { useGameState } from "@/contexts/GameStateProvider"; +import { TOTAL_WOOD_AVAILABLE } from "@/utils/anchor"; const DisplayPlayerData = () => { - const { publicKey } = useWallet() - const { gameState, nextEnergyIn, totalWoodAvailable } = useGameState() + const { publicKey } = useWallet(); + const { gameState, nextEnergyIn, totalWoodAvailable } = useGameState(); return ( <> @@ -27,7 +27,7 @@ const DisplayPlayerData = () => { )} - ) -} + ); +}; -export default DisplayPlayerData +export default DisplayPlayerData; diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/DisplayNfts.tsx b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/DisplayNfts.tsx index 01483c94e..986d338d5 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/DisplayNfts.tsx +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/DisplayNfts.tsx @@ -1,7 +1,7 @@ -import Image from "next/image" -import { useWallet } from "@solana/wallet-adapter-react" -import { useNftState } from "@/contexts/NftProvider" +import { useWallet } from "@solana/wallet-adapter-react"; +import Image from "next/image"; import { useState } from "react"; +import { useNftState } from "@/contexts/NftProvider"; export class Nft { name: string; @@ -14,26 +14,25 @@ export class Nft { } const DisplayNfts = () => { - const { publicKey } = useWallet() - const { nftState: nftState } = useNftState() + const { publicKey } = useWallet(); + const { nftState } = useNftState(); const [showItems, setShowItems] = useState(false); const handleButtonClick = () => { setShowItems(!showItems); }; - var myNfts = new Array(); + const myNfts: Nft[] = []; if (nftState != null) { - for (var i = 0; i < nftState.items.length; i++) { + for (let i = 0; i < nftState.items.length; i++) { try { - const nftData = nftState.items[i]; - let nft = new Nft(); - + const nft = new Nft(); + nft.name = nftData.content.metadata.name; nft.url = nftData.content.links.image; - + myNfts.push(nft); } catch (error) { console.log(error); @@ -42,14 +41,16 @@ const DisplayNfts = () => { } function onNftClickedCallback(nft: Nft): void { - window.alert("Nft clicked: " + nft.name); + window.alert(`Nft clicked: ${nft.name}`); } return ( <> {nftState && publicKey && (
- + {showItems && (
{myNfts.map((nft) => ( @@ -67,7 +68,6 @@ const DisplayNfts = () => { ) : (
Error loading image
)} -
))} @@ -77,6 +77,6 @@ const DisplayNfts = () => { )} ); -} +}; -export default DisplayNfts +export default DisplayNfts; diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/InitPlayerButton.tsx b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/InitPlayerButton.tsx index 091308e54..47d2a1cc1 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/InitPlayerButton.tsx +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/InitPlayerButton.tsx @@ -1,21 +1,21 @@ -import { useCallback, useState } from "react" -import { Button } from "@chakra-ui/react" -import { SystemProgram } from "@solana/web3.js" -import { useConnection, useWallet } from "@solana/wallet-adapter-react" -import { useGameState } from "@/contexts/GameStateProvider" -import { GAME_DATA_SEED, gameDataPDA, program } from "@/utils/anchor" +import { Button } from "@chakra-ui/react"; +import { useConnection, useWallet } from "@solana/wallet-adapter-react"; +import { SystemProgram } from "@solana/web3.js"; +import { useCallback, useState } from "react"; +import { useGameState } from "@/contexts/GameStateProvider"; +import { GAME_DATA_SEED, gameDataPDA, program } from "@/utils/anchor"; const InitPlayerButton = () => { - const { publicKey, sendTransaction } = useWallet() - const { connection } = useConnection() - const [isLoading, setIsLoading] = useState(false) - const { gameState, playerDataPDA } = useGameState() + const { publicKey, sendTransaction } = useWallet(); + const { connection } = useConnection(); + const [isLoading, setIsLoading] = useState(false); + const { gameState, playerDataPDA } = useGameState(); // Init player button click handler const handleClick = useCallback(async () => { - if (!publicKey || !playerDataPDA) return + if (!publicKey || !playerDataPDA) return; - setIsLoading(true) + setIsLoading(true); try { const transaction = await program.methods @@ -26,19 +26,19 @@ const InitPlayerButton = () => { signer: publicKey, systemProgram: SystemProgram.programId, }) - .transaction() + .transaction(); const txSig = await sendTransaction(transaction, connection, { skipPreflight: true, - }) + }); - console.log(`https://explorer.solana.com/tx/${txSig}?cluster=devnet`) + console.log(`https://explorer.solana.com/tx/${txSig}?cluster=devnet`); } catch (error) { - console.log(error) + console.log(error); } finally { - setIsLoading(false) // set loading state back to false + setIsLoading(false); // set loading state back to false } - }, [publicKey, playerDataPDA, connection]) + }, [publicKey, playerDataPDA, connection, sendTransaction]); return ( <> @@ -48,7 +48,7 @@ const InitPlayerButton = () => { )} - ) -} + ); +}; -export default InitPlayerButton +export default InitPlayerButton; diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/MintNftButton.tsx b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/MintNftButton.tsx index 2590c697b..48115b136 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/MintNftButton.tsx +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/MintNftButton.tsx @@ -1,30 +1,26 @@ -import Image from "next/image" -import { useCallback, useState } from "react" -import { Button, HStack, VStack } from "@chakra-ui/react" -import { useConnection, useWallet } from "@solana/wallet-adapter-react" -import { useGameState } from "@/contexts/GameStateProvider" -import { program } from "@/utils/anchor" -import { Keypair, PublicKey, SystemProgram } from "@solana/web3.js" -import { web3 } from "@coral-xyz/anchor" -import { ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, getAssociatedTokenAddressSync } from "@solana/spl-token"; +import { Button, HStack, VStack } from "@chakra-ui/react"; +import { web3 } from "@coral-xyz/anchor"; +import { ASSOCIATED_TOKEN_PROGRAM_ID, getAssociatedTokenAddressSync, TOKEN_2022_PROGRAM_ID } from "@solana/spl-token"; +import { useConnection, useWallet } from "@solana/wallet-adapter-react"; +import { Keypair, PublicKey, SystemProgram } from "@solana/web3.js"; +import Image from "next/image"; +import { useCallback, useState } from "react"; +import { useGameState } from "@/contexts/GameStateProvider"; +import { program } from "@/utils/anchor"; const MintNftButton = () => { - const { publicKey, sendTransaction, wallet } = useWallet() - const { connection } = useConnection() - const { gameState, playerDataPDA } = useGameState() - const [isLoadingMainWallet, showSpinner] = useState(false) + const { publicKey, sendTransaction } = useWallet(); + const { connection } = useConnection(); + const { gameState, playerDataPDA } = useGameState(); + const [isLoadingMainWallet, showSpinner] = useState(false); const onMintNftClick = useCallback(async () => { - if (!publicKey || !playerDataPDA) return + if (!publicKey || !playerDataPDA) return; - showSpinner(true) + showSpinner(true); try { - - const nftAuthority = await PublicKey.findProgramAddress( - [Buffer.from("nft_authority")], - program.programId - ); + const nftAuthority = await PublicKey.findProgramAddress([Buffer.from("nft_authority")], program.programId); const mint = new Keypair(); @@ -52,19 +48,18 @@ const MintNftButton = () => { console.log("transaction", transaction); - const txSig = await sendTransaction(transaction, connection,{ + const txSig = await sendTransaction(transaction, connection, { signers: [mint], - skipPreflight: true - } ); + skipPreflight: true, + }); - console.log(`https://explorer.solana.com/tx/${txSig}?cluster=devnet`) - - } catch (error: any) { - console.log("error", `Minting failed! ${error?.message} ${error?.stack}`) + console.log(`https://explorer.solana.com/tx/${txSig}?cluster=devnet`); + } catch (error) { + console.log("error", `Minting failed! ${error instanceof Error ? error.message : String(error)}`); } finally { - showSpinner(false) + showSpinner(false); } - }, [publicKey, playerDataPDA, connection]) + }, [publicKey, playerDataPDA, connection, sendTransaction]); return ( <> @@ -72,18 +67,14 @@ const MintNftButton = () => { Energy Icon - )} - ) -} + ); +}; -export default MintNftButton +export default MintNftButton; diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/RequestAirdrop.tsx b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/RequestAirdrop.tsx index a6f8e77cc..da9b89e68 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/RequestAirdrop.tsx +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/RequestAirdrop.tsx @@ -1,37 +1,37 @@ -import { useCallback, useEffect, useState } from "react" -import { Button, Text } from "@chakra-ui/react" -import { LAMPORTS_PER_SOL } from "@solana/web3.js" -import { useConnection, useWallet } from "@solana/wallet-adapter-react" +import { Button, Text } from "@chakra-ui/react"; +import { useConnection, useWallet } from "@solana/wallet-adapter-react"; +import { LAMPORTS_PER_SOL } from "@solana/web3.js"; +import { useCallback, useEffect, useState } from "react"; const RequestAirdrop = () => { - const { publicKey } = useWallet() - const { connection } = useConnection() - const [balance, setBalance] = useState(0) - const [isLoading, setIsLoading] = useState(false) + const { publicKey } = useWallet(); + const { connection } = useConnection(); + const [balance, setBalance] = useState(0); + const [isLoading, setIsLoading] = useState(false); const getBalance = useCallback(async () => { - if (!publicKey) return - const balance = await connection.getBalance(publicKey, "confirmed") - setBalance(balance / LAMPORTS_PER_SOL) - }, [publicKey, connection]) + if (!publicKey) return; + const balance = await connection.getBalance(publicKey, "confirmed"); + setBalance(balance / LAMPORTS_PER_SOL); + }, [publicKey, connection]); const onClick = useCallback(async () => { - setIsLoading(true) - if (!publicKey) return + setIsLoading(true); + if (!publicKey) return; try { - const txSig = await connection.requestAirdrop(publicKey, LAMPORTS_PER_SOL) - await connection.confirmTransaction(txSig) - getBalance() - } catch (error: any) { - alert(error.message) + const txSig = await connection.requestAirdrop(publicKey, LAMPORTS_PER_SOL); + await connection.confirmTransaction(txSig); + getBalance(); + } catch (error) { + alert(error instanceof Error ? error.message : String(error)); } finally { - setIsLoading(false) + setIsLoading(false); } - }, [publicKey, connection, getBalance]) + }, [publicKey, connection, getBalance]); useEffect(() => { - getBalance() - }, [getBalance]) + getBalance(); + }, [getBalance]); return ( <> @@ -44,7 +44,7 @@ const RequestAirdrop = () => { Balance: {Number(balance).toFixed(3)} ))} - ) -} + ); +}; -export default RequestAirdrop +export default RequestAirdrop; diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/SessionKeyButton.tsx b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/SessionKeyButton.tsx index 7567e9efb..e3036c776 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/SessionKeyButton.tsx +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/SessionKeyButton.tsx @@ -1,65 +1,55 @@ -import { useState } from "react" -import { Button } from "@chakra-ui/react" -import { useWallet } from "@solana/wallet-adapter-react" -import { useSessionWallet } from "@magicblock-labs/gum-react-sdk" -import { useGameState } from "@/contexts/GameStateProvider" -import { program } from "@/utils/anchor" +import { Button } from "@chakra-ui/react"; +import { useSessionWallet } from "@magicblock-labs/gum-react-sdk"; +import { useWallet } from "@solana/wallet-adapter-react"; +import { useState } from "react"; +import { useGameState } from "@/contexts/GameStateProvider"; +import { program } from "@/utils/anchor"; const SessionKeyButton = () => { - const { publicKey } = useWallet() - const { gameState } = useGameState() - const sessionWallet = useSessionWallet() - const [isLoading, setIsLoading] = useState(false) + const { publicKey } = useWallet(); + const { gameState } = useGameState(); + const sessionWallet = useSessionWallet(); + const [isLoading, setIsLoading] = useState(false); const handleCreateSession = async () => { - setIsLoading(true) - const topUp = true - const expiryInMinutes = 600 + setIsLoading(true); + const topUp = true; + const expiryInMinutes = 600; try { - const session = await sessionWallet.createSession( - program.programId, - topUp, - expiryInMinutes - ) - console.log("Session created:", session) + const session = await sessionWallet.createSession(program.programId, topUp, expiryInMinutes); + console.log("Session created:", session); } catch (error) { - console.error("Failed to create session:", error) + console.error("Failed to create session:", error); } finally { - setIsLoading(false) + setIsLoading(false); } - } + }; const handleRevokeSession = async () => { - setIsLoading(true) + setIsLoading(true); try { - await sessionWallet.revokeSession() - console.log("Session revoked") + await sessionWallet.revokeSession(); + console.log("Session revoked"); } catch (error) { - console.error("Failed to revoke session:", error) + console.error("Failed to revoke session:", error); } finally { - setIsLoading(false) + setIsLoading(false); } - } + }; return ( <> {publicKey && gameState && ( )} - ) -} + ); +}; -export default SessionKeyButton +export default SessionKeyButton; diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/WalletMultiButton.tsx b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/WalletMultiButton.tsx index 8f2380015..d3cfefe14 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/WalletMultiButton.tsx +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/components/WalletMultiButton.tsx @@ -1,13 +1,12 @@ -import dynamic from "next/dynamic" +import dynamic from "next/dynamic"; export const WalletMultiButtonDynamic = dynamic( - async () => - (await import("@solana/wallet-adapter-react-ui")).WalletMultiButton, - { ssr: false } -) + async () => (await import("@solana/wallet-adapter-react-ui")).WalletMultiButton, + { ssr: false }, +); const WalletMultiButton = () => { - return -} + return ; +}; -export default WalletMultiButton +export default WalletMultiButton; diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/contexts/GameStateProvider.tsx b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/contexts/GameStateProvider.tsx index 4e9127870..182a752af 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/contexts/GameStateProvider.tsx +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/contexts/GameStateProvider.tsx @@ -1,128 +1,116 @@ -import { createContext, useContext, useEffect, useState } from "react" -import { PublicKey } from "@solana/web3.js" -import { useConnection, useWallet } from "@solana/wallet-adapter-react" +import { BN } from "@coral-xyz/anchor"; +import { useConnection, useWallet } from "@solana/wallet-adapter-react"; +import { PublicKey } from "@solana/web3.js"; +import { createContext, useContext, useEffect, useState } from "react"; import { - program, - PlayerData, + GAME_DATA_SEED, + type GameData, MAX_ENERGY, + type PlayerData, + program, TIME_TO_REFILL_ENERGY, - GameData, - GAME_DATA_SEED, -} from "@/utils/anchor" -import { BN } from "@coral-xyz/anchor" +} from "@/utils/anchor"; const GameStateContext = createContext<{ - playerDataPDA: PublicKey | null - gameState: PlayerData | null - nextEnergyIn: number - totalWoodAvailable: number | null + playerDataPDA: PublicKey | null; + gameState: PlayerData | null; + nextEnergyIn: number; + totalWoodAvailable: number | null; }>({ playerDataPDA: null, gameState: null, nextEnergyIn: 0, - totalWoodAvailable: 0 -}) - -export const useGameState = () => useContext(GameStateContext) - -export const GameStateProvider = ({ - children, -}: { - children: React.ReactNode -}) => { - const { publicKey } = useWallet() - const { connection } = useConnection() - - const [playerDataPDA, setPlayerData] = useState(null) - const [playerState, setPlayerState] = useState(null) - const [timePassed, setTimePassed] = useState([]) - const [nextEnergyIn, setEnergyNextIn] = useState(0) - const [gameDataPDA, setGameDataPDA] = useState(null) - const [gameData, setGameData] = useState(null) - const [totalWoodAvailable, setTotalWoodAvailable] = useState(0) + totalWoodAvailable: 0, +}); + +export const useGameState = () => useContext(GameStateContext); + +export const GameStateProvider = ({ children }: { children: React.ReactNode }) => { + const { publicKey } = useWallet(); + const { connection } = useConnection(); + + const [playerDataPDA, setPlayerData] = useState(null); + const [playerState, setPlayerState] = useState(null); + const [_timePassed, setTimePassed] = useState(0); + const [nextEnergyIn, setEnergyNextIn] = useState(0); + const [gameDataPDA, setGameDataPDA] = useState(null); + const [_gameData, setGameData] = useState(null); + const [totalWoodAvailable, setTotalWoodAvailable] = useState(0); useEffect(() => { - setPlayerState(null) + setPlayerState(null); if (!publicKey) { - return + return; } const [pda] = PublicKey.findProgramAddressSync( [Buffer.from("player", "utf8"), publicKey.toBuffer()], - program.programId - ) - setPlayerData(pda) + program.programId, + ); + setPlayerData(pda); program.account.playerData .fetch(pda) .then((data) => { - setPlayerState(data) - }) - .catch((error) => { - window.alert("No player data found, please init!") + setPlayerState(data); }) + .catch((_error) => { + window.alert("No player data found, please init!"); + }); connection.onAccountChange(pda, (account) => { - setPlayerState(program.coder.accounts.decode("playerData", account.data)) - }) - }, [publicKey]) + setPlayerState(program.coder.accounts.decode("playerData", account.data)); + }); + }, [publicKey, connection.onAccountChange]); useEffect(() => { - setGameData(null) + setGameData(null); if (!publicKey) { - return + return; } - const [pda] = PublicKey.findProgramAddressSync( - [Buffer.from(GAME_DATA_SEED, "utf8")], - program.programId - ) - setGameDataPDA(gameDataPDA) + const [pda] = PublicKey.findProgramAddressSync([Buffer.from(GAME_DATA_SEED, "utf8")], program.programId); + setGameDataPDA(gameDataPDA); program.account.gameData .fetch(pda) .then((data) => { - setGameData(data) + setGameData(data); setTotalWoodAvailable(data.totalWoodCollected.toNumber()); }) - .catch((error) => { - window.alert("No game data found, please init!") - }) + .catch((_error) => { + window.alert("No game data found, please init!"); + }); connection.onAccountChange(pda, (account) => { - const newGameData = program.coder.accounts.decode("gameData", account.data) + const newGameData = program.coder.accounts.decode("gameData", account.data); setGameData(newGameData); setTotalWoodAvailable(newGameData.totalWoodCollected.toNumber()); - }) - }, [publicKey]) - + }); + }, [publicKey, connection.onAccountChange, gameDataPDA]); useEffect(() => { const interval = setInterval(async () => { - if ( - playerState == null || - playerState.lastLogin == undefined || - playerState.energy.toNumber() >= MAX_ENERGY - ) { + if (playerState == null || playerState.lastLogin === undefined || playerState.energy.toNumber() >= MAX_ENERGY) { return; } - + const lastLoginTime = playerState.lastLogin.toNumber() * 1000; const currentTime = Date.now(); let timePassed = (currentTime - lastLoginTime) / 1000; - + while (timePassed >= TIME_TO_REFILL_ENERGY.toNumber() && playerState.energy.toNumber() < MAX_ENERGY) { playerState.energy = playerState.energy.add(new BN(1)); playerState.lastLogin = playerState.lastLogin.add(TIME_TO_REFILL_ENERGY); timePassed -= TIME_TO_REFILL_ENERGY.toNumber(); } - + setTimePassed(timePassed); - + const nextEnergyIn = Math.floor(TIME_TO_REFILL_ENERGY.toNumber() - timePassed); setEnergyNextIn(nextEnergyIn > 0 ? nextEnergyIn : 0); }, 1000); - return () => clearInterval(interval) - }, [playerState, timePassed, nextEnergyIn]) + return () => clearInterval(interval); + }, [playerState]); return ( {children} - ) -} + ); +}; diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/contexts/NftProvider.tsx b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/contexts/NftProvider.tsx index 8f115f789..376cdc018 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/contexts/NftProvider.tsx +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/contexts/NftProvider.tsx @@ -1,38 +1,35 @@ -import { createContext, useContext, useEffect, useState } from "react" -import { PublicKey } from "@solana/web3.js" -import { useWallet } from "@solana/wallet-adapter-react" -import { - CONNECTION, -} from "@/utils/anchor" +import { useWallet } from "@solana/wallet-adapter-react"; +import type { PublicKey } from "@solana/web3.js"; +import { createContext, useCallback, useContext, useEffect, useState } from "react"; +import { CONNECTION } from "@/utils/anchor"; + +interface DasNftItem { + id: string; + authorities: Array<{ address: string } | string>; + content: { + metadata: { name: string }; + links: { image: string }; + }; +} + +interface DasNftState { + items: DasNftItem[]; +} const NftContext = createContext<{ - nftState: any | null + nftState: DasNftState | null; }>({ nftState: null, -}) +}); -export const useNftState = () => useContext(NftContext) +export const useNftState = () => useContext(NftContext); -export const NftProvider = ({ - children, -}: { - children: React.ReactNode -}) => { - const { publicKey } = useWallet() +export const NftProvider = ({ children }: { children: React.ReactNode }) => { + const { publicKey } = useWallet(); - const [nftState, setNftState] = useState(null) - - useEffect( () => { - setNftState(null) - if (!publicKey) { - return - } - - getAssetsByOwner(publicKey); + const [nftState, setNftState] = useState(null); - }, [publicKey]); - - async function getAssetsByOwner(ownerAddress: PublicKey) { + const getAssetsByOwner = useCallback(async (ownerAddress: PublicKey) => { const sortBy = { sortBy: "created", sortDirection: "asc", @@ -47,12 +44,21 @@ export const NftProvider = ({ limit, page, before, - after + after, ); - setNftState(allAssetsOwned); + setNftState(allAssetsOwned as DasNftState); console.log(allAssetsOwned); - } + }, []); + + useEffect(() => { + setNftState(null); + if (!publicKey) { + return; + } + + getAssetsByOwner(publicKey); + }, [publicKey, getAssetsByOwner]); return ( {children} - ) -} + ); +}; diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/contexts/SessionProvider.tsx b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/contexts/SessionProvider.tsx index 619d442d5..57d8a2baf 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/contexts/SessionProvider.tsx +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/contexts/SessionProvider.tsx @@ -1,26 +1,18 @@ -import { SessionWalletProvider, useSessionKeyManager } from "@magicblock-labs/gum-react-sdk" +import { SessionWalletProvider, useSessionKeyManager } from "@magicblock-labs/gum-react-sdk"; -import { - AnchorWallet, - useAnchorWallet, - useConnection, -} from "@solana/wallet-adapter-react" +import { type AnchorWallet, useAnchorWallet, useConnection } from "@solana/wallet-adapter-react"; interface SessionProviderProps { - children: React.ReactNode + children: React.ReactNode; } const SessionProvider: React.FC = ({ children }) => { - const { connection } = useConnection() - const anchorWallet = useAnchorWallet() as AnchorWallet - const cluster = "devnet" // or "mainnet-beta", "testnet", "localnet" - const sessionWallet = useSessionKeyManager(anchorWallet, connection, cluster) + const { connection } = useConnection(); + const anchorWallet = useAnchorWallet() as AnchorWallet; + const cluster = "devnet"; // or "mainnet-beta", "testnet", "localnet" + const sessionWallet = useSessionKeyManager(anchorWallet, connection, cluster); - return ( - - {children} - - ) -} + return {children}; +}; -export default SessionProvider +export default SessionProvider; diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/contexts/WalletContextProvider.tsx b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/contexts/WalletContextProvider.tsx index 97a625de2..1b3e9cdc7 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/contexts/WalletContextProvider.tsx +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/contexts/WalletContextProvider.tsx @@ -1,28 +1,17 @@ -import { FC, ReactNode, useMemo } from "react" -import { WalletAdapterNetwork } from "@solana/wallet-adapter-base" -import { - ConnectionProvider, - WalletProvider, -} from "@solana/wallet-adapter-react" -import { WalletModalProvider } from "@solana/wallet-adapter-react-ui" -import { - PhantomWalletAdapter, - SolflareWalletAdapter, -} from "@solana/wallet-adapter-wallets" -import { clusterApiUrl } from "@solana/web3.js" -require("@solana/wallet-adapter-react-ui/styles.css") +import { WalletAdapterNetwork } from "@solana/wallet-adapter-base"; +import { ConnectionProvider, WalletProvider } from "@solana/wallet-adapter-react"; +import { WalletModalProvider } from "@solana/wallet-adapter-react-ui"; +import { PhantomWalletAdapter, SolflareWalletAdapter } from "@solana/wallet-adapter-wallets"; +import { clusterApiUrl } from "@solana/web3.js"; +import { type FC, type ReactNode, useMemo } from "react"; + +require("@solana/wallet-adapter-react-ui/styles.css"); const WalletContextProvider: FC<{ children: ReactNode }> = ({ children }) => { - const network = WalletAdapterNetwork.Devnet - const endpoint = useMemo(() => clusterApiUrl(network), [network]) + const network = WalletAdapterNetwork.Devnet; + const endpoint = useMemo(() => clusterApiUrl(network), []); - const wallets = useMemo( - () => [ - new PhantomWalletAdapter(), - new SolflareWalletAdapter(), - ], - [network] - ) + const wallets = useMemo(() => [new PhantomWalletAdapter(), new SolflareWalletAdapter()], []); return ( @@ -30,7 +19,7 @@ const WalletContextProvider: FC<{ children: ReactNode }> = ({ children }) => { {children} - ) -} + ); +}; -export default WalletContextProvider +export default WalletContextProvider; diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/idl/extension_nft.ts b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/idl/extension_nft.ts index b77acef1c..f31836532 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/idl/extension_nft.ts +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/idl/extension_nft.ts @@ -1,134 +1,134 @@ export type ExtensionNft = { - version: '0.1.0'; - name: 'extension_nft'; + version: "0.1.0"; + name: "extension_nft"; instructions: [ { - name: 'initPlayer'; + name: "initPlayer"; accounts: [ { - name: 'player'; + name: "player"; isMut: true; isSigner: false; }, { - name: 'gameData'; + name: "gameData"; isMut: true; isSigner: false; }, { - name: 'signer'; + name: "signer"; isMut: true; isSigner: true; }, { - name: 'systemProgram'; + name: "systemProgram"; isMut: false; isSigner: false; }, ]; args: [ { - name: 'levelSeed'; - type: 'string'; + name: "levelSeed"; + type: "string"; }, ]; }, { - name: 'chopTree'; + name: "chopTree"; accounts: [ { - name: 'sessionToken'; + name: "sessionToken"; isMut: false; isSigner: false; isOptional: true; }, { - name: 'player'; + name: "player"; isMut: true; isSigner: false; }, { - name: 'gameData'; + name: "gameData"; isMut: true; isSigner: false; }, { - name: 'signer'; + name: "signer"; isMut: true; isSigner: true; }, { - name: 'systemProgram'; + name: "systemProgram"; isMut: false; isSigner: false; }, { - name: 'mint'; + name: "mint"; isMut: true; isSigner: false; }, { - name: 'nftAuthority'; + name: "nftAuthority"; isMut: true; isSigner: false; }, { - name: 'tokenProgram'; + name: "tokenProgram"; isMut: false; isSigner: false; }, ]; args: [ { - name: 'levelSeed'; - type: 'string'; + name: "levelSeed"; + type: "string"; }, { - name: 'counter'; - type: 'u16'; + name: "counter"; + type: "u16"; }, ]; }, { - name: 'mintNft'; + name: "mintNft"; accounts: [ { - name: 'signer'; + name: "signer"; isMut: true; isSigner: true; }, { - name: 'systemProgram'; + name: "systemProgram"; isMut: false; isSigner: false; }, { - name: 'tokenProgram'; + name: "tokenProgram"; isMut: false; isSigner: false; }, { - name: 'tokenAccount'; + name: "tokenAccount"; isMut: true; isSigner: false; }, { - name: 'mint'; + name: "mint"; isMut: true; isSigner: true; }, { - name: 'rent'; + name: "rent"; isMut: false; isSigner: false; }, { - name: 'associatedTokenProgram'; + name: "associatedTokenProgram"; isMut: false; isSigner: false; }, { - name: 'nftAuthority'; + name: "nftAuthority"; isMut: true; isSigner: false; }, @@ -138,60 +138,60 @@ export type ExtensionNft = { ]; accounts: [ { - name: 'nftAuthority'; + name: "nftAuthority"; type: { - kind: 'struct'; + kind: "struct"; fields: []; }; }, { - name: 'gameData'; + name: "gameData"; type: { - kind: 'struct'; + kind: "struct"; fields: [ { - name: 'totalWoodCollected'; - type: 'u64'; + name: "totalWoodCollected"; + type: "u64"; }, ]; }; }, { - name: 'playerData'; + name: "playerData"; type: { - kind: 'struct'; + kind: "struct"; fields: [ { - name: 'authority'; - type: 'publicKey'; + name: "authority"; + type: "publicKey"; }, { - name: 'name'; - type: 'string'; + name: "name"; + type: "string"; }, { - name: 'level'; - type: 'u8'; + name: "level"; + type: "u8"; }, { - name: 'xp'; - type: 'u64'; + name: "xp"; + type: "u64"; }, { - name: 'wood'; - type: 'u64'; + name: "wood"; + type: "u64"; }, { - name: 'energy'; - type: 'u64'; + name: "energy"; + type: "u64"; }, { - name: 'lastLogin'; - type: 'i64'; + name: "lastLogin"; + type: "i64"; }, { - name: 'lastId'; - type: 'u16'; + name: "lastId"; + type: "u16"; }, ]; }; @@ -200,148 +200,148 @@ export type ExtensionNft = { errors: [ { code: 6000; - name: 'NotEnoughEnergy'; - msg: 'Not enough energy'; + name: "NotEnoughEnergy"; + msg: "Not enough energy"; }, { code: 6001; - name: 'WrongAuthority'; - msg: 'Wrong Authority'; + name: "WrongAuthority"; + msg: "Wrong Authority"; }, ]; }; export const IDL: ExtensionNft = { - version: '0.1.0', - name: 'extension_nft', + version: "0.1.0", + name: "extension_nft", instructions: [ { - name: 'initPlayer', + name: "initPlayer", accounts: [ { - name: 'player', + name: "player", isMut: true, isSigner: false, }, { - name: 'gameData', + name: "gameData", isMut: true, isSigner: false, }, { - name: 'signer', + name: "signer", isMut: true, isSigner: true, }, { - name: 'systemProgram', + name: "systemProgram", isMut: false, isSigner: false, }, ], args: [ { - name: 'levelSeed', - type: 'string', + name: "levelSeed", + type: "string", }, ], }, { - name: 'chopTree', + name: "chopTree", accounts: [ { - name: 'sessionToken', + name: "sessionToken", isMut: false, isSigner: false, isOptional: true, }, { - name: 'player', + name: "player", isMut: true, isSigner: false, }, { - name: 'gameData', + name: "gameData", isMut: true, isSigner: false, }, { - name: 'signer', + name: "signer", isMut: true, isSigner: true, }, { - name: 'systemProgram', + name: "systemProgram", isMut: false, isSigner: false, }, { - name: 'mint', + name: "mint", isMut: true, isSigner: false, }, { - name: 'nftAuthority', + name: "nftAuthority", isMut: true, isSigner: false, }, { - name: 'tokenProgram', + name: "tokenProgram", isMut: false, isSigner: false, }, ], args: [ { - name: 'levelSeed', - type: 'string', + name: "levelSeed", + type: "string", }, { - name: 'counter', - type: 'u16', + name: "counter", + type: "u16", }, ], }, { - name: 'mintNft', + name: "mintNft", accounts: [ { - name: 'signer', + name: "signer", isMut: true, isSigner: true, }, { - name: 'systemProgram', + name: "systemProgram", isMut: false, isSigner: false, }, { - name: 'tokenProgram', + name: "tokenProgram", isMut: false, isSigner: false, }, { - name: 'tokenAccount', + name: "tokenAccount", isMut: true, isSigner: false, }, { - name: 'mint', + name: "mint", isMut: true, isSigner: true, }, { - name: 'rent', + name: "rent", isMut: false, isSigner: false, }, { - name: 'associatedTokenProgram', + name: "associatedTokenProgram", isMut: false, isSigner: false, }, { - name: 'nftAuthority', + name: "nftAuthority", isMut: true, isSigner: false, }, @@ -351,60 +351,60 @@ export const IDL: ExtensionNft = { ], accounts: [ { - name: 'nftAuthority', + name: "nftAuthority", type: { - kind: 'struct', + kind: "struct", fields: [], }, }, { - name: 'gameData', + name: "gameData", type: { - kind: 'struct', + kind: "struct", fields: [ { - name: 'totalWoodCollected', - type: 'u64', + name: "totalWoodCollected", + type: "u64", }, ], }, }, { - name: 'playerData', + name: "playerData", type: { - kind: 'struct', + kind: "struct", fields: [ { - name: 'authority', - type: 'publicKey', + name: "authority", + type: "publicKey", }, { - name: 'name', - type: 'string', + name: "name", + type: "string", }, { - name: 'level', - type: 'u8', + name: "level", + type: "u8", }, { - name: 'xp', - type: 'u64', + name: "xp", + type: "u64", }, { - name: 'wood', - type: 'u64', + name: "wood", + type: "u64", }, { - name: 'energy', - type: 'u64', + name: "energy", + type: "u64", }, { - name: 'lastLogin', - type: 'i64', + name: "lastLogin", + type: "i64", }, { - name: 'lastId', - type: 'u16', + name: "lastId", + type: "u16", }, ], }, @@ -413,13 +413,13 @@ export const IDL: ExtensionNft = { errors: [ { code: 6000, - name: 'NotEnoughEnergy', - msg: 'Not enough energy', + name: "NotEnoughEnergy", + msg: "Not enough energy", }, { code: 6001, - name: 'WrongAuthority', - msg: 'Wrong Authority', + name: "WrongAuthority", + msg: "Wrong Authority", }, ], }; diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/next.config.js b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/next.config.js index f4fad9bea..9d6954c83 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/next.config.js +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/next.config.js @@ -6,8 +6,8 @@ const nextConfig = { images: { remotePatterns: [ { - protocol: 'https', - hostname: '**', + protocol: "https", + hostname: "**", }, ], }, diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/pages/_app.tsx b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/pages/_app.tsx index fd00cdf93..7bb118b2b 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/pages/_app.tsx +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/pages/_app.tsx @@ -1,22 +1,22 @@ -import { ChakraProvider } from "@chakra-ui/react" -import WalletContextProvider from "../contexts/WalletContextProvider" -import SessionProvider from "@/contexts/SessionProvider" -import { GameStateProvider } from "@/contexts/GameStateProvider" -import type { AppProps } from "next/app" -import { NftProvider } from "@/contexts/NftProvider" +import { ChakraProvider } from "@chakra-ui/react"; +import type { AppProps } from "next/app"; +import { GameStateProvider } from "@/contexts/GameStateProvider"; +import { NftProvider } from "@/contexts/NftProvider"; +import SessionProvider from "@/contexts/SessionProvider"; +import WalletContextProvider from "../contexts/WalletContextProvider"; export default function App({ Component, pageProps }: AppProps) { return ( - - - - + + + + - ) + ); } diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/pages/_document.tsx b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/pages/_document.tsx index 54e8bf3e2..ffc3f3ccc 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/pages/_document.tsx +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/pages/_document.tsx @@ -1,4 +1,4 @@ -import { Html, Head, Main, NextScript } from 'next/document' +import { Head, Html, Main, NextScript } from "next/document"; export default function Document() { return ( @@ -9,5 +9,5 @@ export default function Document() { - ) + ); } diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/pages/api/hello.ts b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/pages/api/hello.ts index 32a1340fe..e1b0dd0d2 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/pages/api/hello.ts +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/pages/api/hello.ts @@ -1,10 +1,10 @@ // Next.js API route support: https://nextjs.org/docs/api-routes/introduction -import type { NextApiRequest, NextApiResponse } from 'next'; +import type { NextApiRequest, NextApiResponse } from "next"; type Data = { name: string; }; export default function handler(_req: NextApiRequest, res: NextApiResponse) { - res.status(200).json({ name: 'John Doe' }); + res.status(200).json({ name: "John Doe" }); } diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/pages/index.tsx b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/pages/index.tsx index a578072d2..865c00100 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/pages/index.tsx +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/pages/index.tsx @@ -1,16 +1,16 @@ -import { Box, Flex, Heading, Spacer, VStack, Text } from "@chakra-ui/react" -import { useWallet } from "@solana/wallet-adapter-react" -import WalletMultiButton from "@/components/WalletMultiButton" -import DisplayGameState from "@/components/DisplayGameState" -import InitPlayerButton from "@/components/InitPlayerButton" -import SessionKeyButton from "@/components/SessionKeyButton" -import ChopTreeButton from "@/components/ChopTreeButton" -import RequestAirdrop from "@/components/RequestAirdrop" -import DisplayNfts from "@/components/DisplayNfts" -import MintNftButton from "@/components/MintNftButton" +import { Box, Flex, Heading, Spacer, Text, VStack } from "@chakra-ui/react"; +import { useWallet } from "@solana/wallet-adapter-react"; +import ChopTreeButton from "@/components/ChopTreeButton"; +import DisplayGameState from "@/components/DisplayGameState"; +import DisplayNfts from "@/components/DisplayNfts"; +import InitPlayerButton from "@/components/InitPlayerButton"; +import MintNftButton from "@/components/MintNftButton"; +import RequestAirdrop from "@/components/RequestAirdrop"; +import SessionKeyButton from "@/components/SessionKeyButton"; +import WalletMultiButton from "@/components/WalletMultiButton"; export default function Home() { - const { publicKey } = useWallet() + const { publicKey } = useWallet(); return ( @@ -30,5 +30,5 @@ export default function Home() { - ) + ); } diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/styles/Home.module.css b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/styles/Home.module.css index 9411a5e6f..25760859a 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/styles/Home.module.css +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/styles/Home.module.css @@ -51,7 +51,9 @@ border-radius: var(--border-radius); background: rgba(var(--card-rgb), 0); border: 1px solid rgba(var(--card-border-rgb), 0); - transition: background 200ms, border 200ms; + transition: + background 200ms, + border 200ms; } .card span { @@ -97,7 +99,7 @@ .center::before, .center::after { - content: ''; + content: ""; left: 50%; position: absolute; filter: blur(45px); @@ -178,11 +180,7 @@ border-radius: 0; border: none; border-bottom: 1px solid rgba(var(--callout-border-rgb), 0.25); - background: linear-gradient( - to bottom, - rgba(var(--background-start-rgb), 1), - rgba(var(--callout-rgb), 0.5) - ); + background: linear-gradient(to bottom, rgba(var(--background-start-rgb), 1), rgba(var(--callout-rgb), 0.5)); background-clip: padding-box; backdrop-filter: blur(24px); } @@ -193,11 +191,7 @@ inset: auto 0 0; padding: 2rem; height: 200px; - background: linear-gradient( - to bottom, - transparent 0%, - rgb(var(--background-end-rgb)) 40% - ); + background: linear-gradient(to bottom, transparent 0%, rgb(var(--background-end-rgb)) 40%); z-index: 1; } } diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/styles/globals.css b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/styles/globals.css index d4f491e15..bcc3a6c25 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/styles/globals.css +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/styles/globals.css @@ -1,9 +1,10 @@ :root { --max-width: 1100px; --border-radius: 12px; - --font-mono: ui-monospace, Menlo, Monaco, 'Cascadia Mono', 'Segoe UI Mono', - 'Roboto Mono', 'Oxygen Mono', 'Ubuntu Monospace', 'Source Code Pro', - 'Fira Mono', 'Droid Sans Mono', 'Courier New', monospace; + --font-mono: + ui-monospace, Menlo, Monaco, "Cascadia Mono", "Segoe UI Mono", + "Roboto Mono", "Oxygen Mono", "Ubuntu Monospace", "Source Code Pro", + "Fira Mono", "Droid Sans Mono", "Courier New", monospace; --foreground-rgb: 0, 0, 0; --background-start-rgb: 214, 219, 220; @@ -17,22 +18,11 @@ #0071ff33 160deg, transparent 360deg ); - --secondary-glow: radial-gradient( - rgba(255, 255, 255, 1), - rgba(255, 255, 255, 0) - ); + --secondary-glow: radial-gradient(rgba(255, 255, 255, 1), rgba(255, 255, 255, 0)); --tile-start-rgb: 239, 245, 249; --tile-end-rgb: 228, 232, 233; - --tile-border: conic-gradient( - #00000080, - #00000040, - #00000030, - #00000020, - #00000010, - #00000010, - #00000080 - ); + --tile-border: conic-gradient(#00000080, #00000040, #00000030, #00000020, #00000010, #00000010, #00000080); --callout-rgb: 238, 240, 241; --callout-border-rgb: 172, 175, 176; @@ -47,24 +37,11 @@ --background-end-rgb: 0, 0, 0; --primary-glow: radial-gradient(rgba(1, 65, 255, 0.4), rgba(1, 65, 255, 0)); - --secondary-glow: linear-gradient( - to bottom right, - rgba(1, 65, 255, 0), - rgba(1, 65, 255, 0), - rgba(1, 65, 255, 0.3) - ); + --secondary-glow: linear-gradient(to bottom right, rgba(1, 65, 255, 0), rgba(1, 65, 255, 0), rgba(1, 65, 255, 0.3)); --tile-start-rgb: 2, 13, 46; --tile-end-rgb: 2, 5, 19; - --tile-border: conic-gradient( - #ffffff80, - #ffffff40, - #ffffff30, - #ffffff20, - #ffffff10, - #ffffff10, - #ffffff80 - ); + --tile-border: conic-gradient(#ffffff80, #ffffff40, #ffffff30, #ffffff20, #ffffff10, #ffffff10, #ffffff80); --callout-rgb: 20, 20, 20; --callout-border-rgb: 108, 108, 108; @@ -87,12 +64,7 @@ body { body { color: rgb(var(--foreground-rgb)); - background: linear-gradient( - to bottom, - transparent, - rgb(var(--background-end-rgb)) - ) - rgb(var(--background-start-rgb)); + background: linear-gradient(to bottom, transparent, rgb(var(--background-end-rgb))) rgb(var(--background-start-rgb)); } a { diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/utils/anchor.ts b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/utils/anchor.ts index fe83416f4..8db5bcd23 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/utils/anchor.ts +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/utils/anchor.ts @@ -1,31 +1,34 @@ -import { BN, type IdlAccounts, Program } from '@anchor-lang/core'; -import { PublicKey } from '@solana/web3.js'; -import { type ExtensionNft, IDL } from '../idl/extension_nft'; -import { WrappedConnection } from './wrappedConnection'; - -export const CONNECTION = new WrappedConnection(process.env.NEXT_PUBLIC_RPC ? process.env.NEXT_PUBLIC_RPC : 'https://rpc.magicblock.app/devnet', { - wsEndpoint: process.env.NEXT_PUBLIC_WSS_RPC ? process.env.NEXT_PUBLIC_WSS_RPC : 'wss://rpc.magicblock.app/devnet', - commitment: 'confirmed', -}); +import { BN, type IdlAccounts, Program } from "@anchor-lang/core"; +import { PublicKey } from "@solana/web3.js"; +import { type ExtensionNft, IDL } from "../idl/extension_nft"; +import { WrappedConnection } from "./wrappedConnection"; + +export const CONNECTION = new WrappedConnection( + process.env.NEXT_PUBLIC_RPC ? process.env.NEXT_PUBLIC_RPC : "https://rpc.magicblock.app/devnet", + { + wsEndpoint: process.env.NEXT_PUBLIC_WSS_RPC ? process.env.NEXT_PUBLIC_WSS_RPC : "wss://rpc.magicblock.app/devnet", + commitment: "confirmed", + }, +); -export const METAPLEX_READAPI = 'https://devnet.helius-rpc.com/?api-key=78065db3-87fb-431c-8d43-fcd190212125'; +export const METAPLEX_READAPI = "https://devnet.helius-rpc.com/?api-key=78065db3-87fb-431c-8d43-fcd190212125"; // Here you can basically use what ever seed you want. For example one per level or city or whatever. -export const GAME_DATA_SEED = 'level_2'; +export const GAME_DATA_SEED = "level_2"; // ExtensionNft game program ID -const programId = new PublicKey('H31ofLpWqeAzF2Pg54HSPQGYifJad843tTJg8vCYVoh3'); +const programId = new PublicKey("H31ofLpWqeAzF2Pg54HSPQGYifJad843tTJg8vCYVoh3"); // Create the program interface using the idl, program ID, and provider export const program = new Program(IDL, programId, { connection: CONNECTION, }); -export const [gameDataPDA] = PublicKey.findProgramAddressSync([Buffer.from(GAME_DATA_SEED, 'utf8')], program.programId); +export const [gameDataPDA] = PublicKey.findProgramAddressSync([Buffer.from(GAME_DATA_SEED, "utf8")], program.programId); // Player Data Account Type from Idl -export type PlayerData = IdlAccounts['playerData']; -export type GameData = IdlAccounts['gameData']; +export type PlayerData = IdlAccounts["playerData"]; +export type GameData = IdlAccounts["gameData"]; // Constants for the game export const TIME_TO_REFILL_ENERGY: BN = new BN(60); diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/utils/wrappedConnection.ts b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/utils/wrappedConnection.ts index 2275dac50..a57b111e9 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/utils/wrappedConnection.ts +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/app/utils/wrappedConnection.ts @@ -1,14 +1,19 @@ -import { Connection } from '@solana/web3.js'; -import axios from 'axios'; -import { METAPLEX_READAPI } from './anchor'; +import { Connection } from "@solana/web3.js"; +import axios from "axios"; +import { METAPLEX_READAPI } from "./anchor"; + +interface SortBy { + sortBy: string; + sortDirection: string; +} export class WrappedConnection extends Connection { - async getAsset(assetId: any): Promise { + async getAsset(assetId: string): Promise { try { const response = await axios.post(process.env.NEXT_PUBLIC_RPC ? process.env.NEXT_PUBLIC_RPC : METAPLEX_READAPI, { - jsonrpc: '2.0', - method: 'getAsset', - id: 'compression-example', + jsonrpc: "2.0", + method: "getAsset", + id: "compression-example", params: [assetId], }); return response.data.result; @@ -17,12 +22,12 @@ export class WrappedConnection extends Connection { } } - async getAssetProof(assetId: any): Promise { + async getAssetProof(assetId: string): Promise { try { const response = await axios.post(process.env.NEXT_PUBLIC_RPC ? process.env.NEXT_PUBLIC_RPC : METAPLEX_READAPI, { - jsonrpc: '2.0', - method: 'getAssetProof', - id: 'compression-example', + jsonrpc: "2.0", + method: "getAssetProof", + id: "compression-example", params: [assetId], }); return response.data.result; @@ -31,12 +36,19 @@ export class WrappedConnection extends Connection { } } - async getAssetsByOwner(assetId: string, sortBy: any, limit: number, page: number, before: string, after: string): Promise { + async getAssetsByOwner( + assetId: string, + sortBy: SortBy, + limit: number, + page: number, + before: string, + after: string, + ): Promise { try { const response = await axios.post(process.env.NEXT_PUBLIC_RPC ? process.env.NEXT_PUBLIC_RPC : METAPLEX_READAPI, { - jsonrpc: '2.0', - method: 'getAssetsByOwner', - id: 'rpd-op-123', + jsonrpc: "2.0", + method: "getAssetsByOwner", + id: "rpd-op-123", params: [assetId, sortBy, limit, page, before, after], }); //console.log("getAssetsByOwner: " + JSON.stringify(response.data)); @@ -46,12 +58,19 @@ export class WrappedConnection extends Connection { } } - async getAssetsByCreator(assetId: string, sortBy: any, limit: number, page: number, _before: string, _after: string): Promise { + async getAssetsByCreator( + assetId: string, + sortBy: SortBy, + limit: number, + page: number, + _before: string, + _after: string, + ): Promise { try { const response = await axios.post(process.env.NEXT_PUBLIC_RPC ? process.env.NEXT_PUBLIC_RPC : METAPLEX_READAPI, { - jsonrpc: '2.0', - method: 'getAssetsByCreator', - id: 'compression-example', + jsonrpc: "2.0", + method: "getAssetsByCreator", + id: "compression-example", params: [assetId, true, sortBy, limit, page, null, null], }); @@ -61,12 +80,19 @@ export class WrappedConnection extends Connection { } } - async getAssetsByAuthority(assetId: string, sortBy: any, limit: number, page: number, before: string, after: string): Promise { + async getAssetsByAuthority( + assetId: string, + sortBy: SortBy, + limit: number, + page: number, + before: string, + after: string, + ): Promise { try { const response = await axios.post(process.env.NEXT_PUBLIC_RPC ? process.env.NEXT_PUBLIC_RPC : METAPLEX_READAPI, { - jsonrpc: '2.0', - method: 'getAssetsByAuthority', - id: 'compression-example', + jsonrpc: "2.0", + method: "getAssetsByAuthority", + id: "compression-example", params: [assetId, sortBy, limit, page, before, after], }); return response.data.result; @@ -78,19 +104,19 @@ export class WrappedConnection extends Connection { async getAssetsByGroup( groupKey: string, groupValue: string, - sortBy: any, + sortBy: SortBy, limit: number, page: number, before: string, after: string, - ): Promise { + ): Promise { try { const events = []; const response = await axios.post(process.env.NEXT_PUBLIC_RPC ? process.env.NEXT_PUBLIC_RPC : METAPLEX_READAPI, { - jsonrpc: '2.0', - method: 'getAssetsByGroup', - id: 'rpd-op-123', + jsonrpc: "2.0", + method: "getAssetsByGroup", + id: "rpd-op-123", params: [groupKey, groupValue, sortBy, limit, page, before, after], }); events.push(...response.data.result.items); @@ -105,19 +131,19 @@ export class WrappedConnection extends Connection { async getAllAssetsByGroup( groupKey: string, groupValue: string, - sortBy: any, + sortBy: SortBy, limit: number, startPage: number, before: string, after: string, - ): Promise { + ): Promise { let page = startPage; try { const events = []; let response = await axios.post(process.env.NEXT_PUBLIC_RPC ? process.env.NEXT_PUBLIC_RPC : METAPLEX_READAPI, { - jsonrpc: '2.0', - method: 'getAssetsByGroup', - id: 'rpd-op-123', + jsonrpc: "2.0", + method: "getAssetsByGroup", + id: "rpd-op-123", params: [groupKey, groupValue, sortBy, limit, page, before, after], }); @@ -128,9 +154,9 @@ export class WrappedConnection extends Connection { page += 1; response = await axios.post(process.env.NEXT_PUBLIC_RPC ? process.env.NEXT_PUBLIC_RPC : METAPLEX_READAPI, { - jsonrpc: '2.0', - method: 'getAssetsByGroup', - id: 'rpd-op-123', + jsonrpc: "2.0", + method: "getAssetsByGroup", + id: "rpd-op-123", params: [groupKey, groupValue, sortBy, limit, page, before, after], }); diff --git a/tokens/token-2022/nft-meta-data-pointer/anchor-example/unity/ExtensionNft/Assets/TextMesh Pro/Sprites/EmojiOne.json b/tokens/token-2022/nft-meta-data-pointer/anchor-example/unity/ExtensionNft/Assets/TextMesh Pro/Sprites/EmojiOne.json index 2b5e1e6a6..53663458b 100644 --- a/tokens/token-2022/nft-meta-data-pointer/anchor-example/unity/ExtensionNft/Assets/TextMesh Pro/Sprites/EmojiOne.json +++ b/tokens/token-2022/nft-meta-data-pointer/anchor-example/unity/ExtensionNft/Assets/TextMesh Pro/Sprites/EmojiOne.json @@ -1,157 +1,157 @@ { - "frames": [ - { - "filename": "1f60a.png", - "frame": { "x": 0, "y": 0, "w": 128, "h": 128 }, - "rotated": false, - "trimmed": false, - "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, - "sourceSize": { "w": 128, "h": 128 }, - "pivot": { "x": 0.5, "y": 0.5 } - }, - { - "filename": "1f60b.png", - "frame": { "x": 128, "y": 0, "w": 128, "h": 128 }, - "rotated": false, - "trimmed": false, - "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, - "sourceSize": { "w": 128, "h": 128 }, - "pivot": { "x": 0.5, "y": 0.5 } - }, - { - "filename": "1f60d.png", - "frame": { "x": 256, "y": 0, "w": 128, "h": 128 }, - "rotated": false, - "trimmed": false, - "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, - "sourceSize": { "w": 128, "h": 128 }, - "pivot": { "x": 0.5, "y": 0.5 } - }, - { - "filename": "1f60e.png", - "frame": { "x": 384, "y": 0, "w": 128, "h": 128 }, - "rotated": false, - "trimmed": false, - "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, - "sourceSize": { "w": 128, "h": 128 }, - "pivot": { "x": 0.5, "y": 0.5 } - }, - { - "filename": "1f600.png", - "frame": { "x": 0, "y": 128, "w": 128, "h": 128 }, - "rotated": false, - "trimmed": false, - "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, - "sourceSize": { "w": 128, "h": 128 }, - "pivot": { "x": 0.5, "y": 0.5 } - }, - { - "filename": "1f601.png", - "frame": { "x": 128, "y": 128, "w": 128, "h": 128 }, - "rotated": false, - "trimmed": false, - "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, - "sourceSize": { "w": 128, "h": 128 }, - "pivot": { "x": 0.5, "y": 0.5 } - }, - { - "filename": "1f602.png", - "frame": { "x": 256, "y": 128, "w": 128, "h": 128 }, - "rotated": false, - "trimmed": false, - "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, - "sourceSize": { "w": 128, "h": 128 }, - "pivot": { "x": 0.5, "y": 0.5 } - }, - { - "filename": "1f603.png", - "frame": { "x": 384, "y": 128, "w": 128, "h": 128 }, - "rotated": false, - "trimmed": false, - "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, - "sourceSize": { "w": 128, "h": 128 }, - "pivot": { "x": 0.5, "y": 0.5 } - }, - { - "filename": "1f604.png", - "frame": { "x": 0, "y": 256, "w": 128, "h": 128 }, - "rotated": false, - "trimmed": false, - "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, - "sourceSize": { "w": 128, "h": 128 }, - "pivot": { "x": 0.5, "y": 0.5 } - }, - { - "filename": "1f605.png", - "frame": { "x": 128, "y": 256, "w": 128, "h": 128 }, - "rotated": false, - "trimmed": false, - "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, - "sourceSize": { "w": 128, "h": 128 }, - "pivot": { "x": 0.5, "y": 0.5 } - }, - { - "filename": "1f606.png", - "frame": { "x": 256, "y": 256, "w": 128, "h": 128 }, - "rotated": false, - "trimmed": false, - "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, - "sourceSize": { "w": 128, "h": 128 }, - "pivot": { "x": 0.5, "y": 0.5 } - }, - { - "filename": "1f609.png", - "frame": { "x": 384, "y": 256, "w": 128, "h": 128 }, - "rotated": false, - "trimmed": false, - "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, - "sourceSize": { "w": 128, "h": 128 }, - "pivot": { "x": 0.5, "y": 0.5 } - }, - { - "filename": "1f618.png", - "frame": { "x": 0, "y": 384, "w": 128, "h": 128 }, - "rotated": false, - "trimmed": false, - "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, - "sourceSize": { "w": 128, "h": 128 }, - "pivot": { "x": 0.5, "y": 0.5 } - }, - { - "filename": "1f923.png", - "frame": { "x": 128, "y": 384, "w": 128, "h": 128 }, - "rotated": false, - "trimmed": false, - "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, - "sourceSize": { "w": 128, "h": 128 }, - "pivot": { "x": 0.5, "y": 0.5 } - }, - { - "filename": "263a.png", - "frame": { "x": 256, "y": 384, "w": 128, "h": 128 }, - "rotated": false, - "trimmed": false, - "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, - "sourceSize": { "w": 128, "h": 128 }, - "pivot": { "x": 0.5, "y": 0.5 } - }, - { - "filename": "2639.png", - "frame": { "x": 384, "y": 384, "w": 128, "h": 128 }, - "rotated": false, - "trimmed": false, - "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, - "sourceSize": { "w": 128, "h": 128 }, - "pivot": { "x": 0.5, "y": 0.5 } - } - ], - "meta": { - "app": "http://www.codeandweb.com/texturepacker", - "version": "1.0", - "image": "EmojiOne.png", - "format": "RGBA8888", - "size": { "w": 512, "h": 512 }, - "scale": "1", - "smartupdate": "$TexturePacker:SmartUpdate:196a26a2e149d875b91ffc8fa3581e76:fc928c7e275404b7e0649307410475cb:424723c3774975ddb2053fd5c4b85f6e$" - } + "frames": [ + { + "filename": "1f60a.png", + "frame": { "x": 0, "y": 0, "w": 128, "h": 128 }, + "rotated": false, + "trimmed": false, + "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, + "sourceSize": { "w": 128, "h": 128 }, + "pivot": { "x": 0.5, "y": 0.5 } + }, + { + "filename": "1f60b.png", + "frame": { "x": 128, "y": 0, "w": 128, "h": 128 }, + "rotated": false, + "trimmed": false, + "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, + "sourceSize": { "w": 128, "h": 128 }, + "pivot": { "x": 0.5, "y": 0.5 } + }, + { + "filename": "1f60d.png", + "frame": { "x": 256, "y": 0, "w": 128, "h": 128 }, + "rotated": false, + "trimmed": false, + "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, + "sourceSize": { "w": 128, "h": 128 }, + "pivot": { "x": 0.5, "y": 0.5 } + }, + { + "filename": "1f60e.png", + "frame": { "x": 384, "y": 0, "w": 128, "h": 128 }, + "rotated": false, + "trimmed": false, + "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, + "sourceSize": { "w": 128, "h": 128 }, + "pivot": { "x": 0.5, "y": 0.5 } + }, + { + "filename": "1f600.png", + "frame": { "x": 0, "y": 128, "w": 128, "h": 128 }, + "rotated": false, + "trimmed": false, + "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, + "sourceSize": { "w": 128, "h": 128 }, + "pivot": { "x": 0.5, "y": 0.5 } + }, + { + "filename": "1f601.png", + "frame": { "x": 128, "y": 128, "w": 128, "h": 128 }, + "rotated": false, + "trimmed": false, + "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, + "sourceSize": { "w": 128, "h": 128 }, + "pivot": { "x": 0.5, "y": 0.5 } + }, + { + "filename": "1f602.png", + "frame": { "x": 256, "y": 128, "w": 128, "h": 128 }, + "rotated": false, + "trimmed": false, + "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, + "sourceSize": { "w": 128, "h": 128 }, + "pivot": { "x": 0.5, "y": 0.5 } + }, + { + "filename": "1f603.png", + "frame": { "x": 384, "y": 128, "w": 128, "h": 128 }, + "rotated": false, + "trimmed": false, + "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, + "sourceSize": { "w": 128, "h": 128 }, + "pivot": { "x": 0.5, "y": 0.5 } + }, + { + "filename": "1f604.png", + "frame": { "x": 0, "y": 256, "w": 128, "h": 128 }, + "rotated": false, + "trimmed": false, + "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, + "sourceSize": { "w": 128, "h": 128 }, + "pivot": { "x": 0.5, "y": 0.5 } + }, + { + "filename": "1f605.png", + "frame": { "x": 128, "y": 256, "w": 128, "h": 128 }, + "rotated": false, + "trimmed": false, + "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, + "sourceSize": { "w": 128, "h": 128 }, + "pivot": { "x": 0.5, "y": 0.5 } + }, + { + "filename": "1f606.png", + "frame": { "x": 256, "y": 256, "w": 128, "h": 128 }, + "rotated": false, + "trimmed": false, + "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, + "sourceSize": { "w": 128, "h": 128 }, + "pivot": { "x": 0.5, "y": 0.5 } + }, + { + "filename": "1f609.png", + "frame": { "x": 384, "y": 256, "w": 128, "h": 128 }, + "rotated": false, + "trimmed": false, + "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, + "sourceSize": { "w": 128, "h": 128 }, + "pivot": { "x": 0.5, "y": 0.5 } + }, + { + "filename": "1f618.png", + "frame": { "x": 0, "y": 384, "w": 128, "h": 128 }, + "rotated": false, + "trimmed": false, + "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, + "sourceSize": { "w": 128, "h": 128 }, + "pivot": { "x": 0.5, "y": 0.5 } + }, + { + "filename": "1f923.png", + "frame": { "x": 128, "y": 384, "w": 128, "h": 128 }, + "rotated": false, + "trimmed": false, + "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, + "sourceSize": { "w": 128, "h": 128 }, + "pivot": { "x": 0.5, "y": 0.5 } + }, + { + "filename": "263a.png", + "frame": { "x": 256, "y": 384, "w": 128, "h": 128 }, + "rotated": false, + "trimmed": false, + "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, + "sourceSize": { "w": 128, "h": 128 }, + "pivot": { "x": 0.5, "y": 0.5 } + }, + { + "filename": "2639.png", + "frame": { "x": 384, "y": 384, "w": 128, "h": 128 }, + "rotated": false, + "trimmed": false, + "spriteSourceSize": { "x": 0, "y": 0, "w": 128, "h": 128 }, + "sourceSize": { "w": 128, "h": 128 }, + "pivot": { "x": 0.5, "y": 0.5 } + } + ], + "meta": { + "app": "http://www.codeandweb.com/texturepacker", + "version": "1.0", + "image": "EmojiOne.png", + "format": "RGBA8888", + "size": { "w": 512, "h": 512 }, + "scale": "1", + "smartupdate": "$TexturePacker:SmartUpdate:196a26a2e149d875b91ffc8fa3581e76:fc928c7e275404b7e0649307410475cb:424723c3774975ddb2053fd5c4b85f6e$" + } } diff --git a/tokens/token-2022/non-transferable/anchor/migrations/deploy.ts b/tokens/token-2022/non-transferable/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/tokens/token-2022/non-transferable/anchor/migrations/deploy.ts +++ b/tokens/token-2022/non-transferable/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/token-2022/non-transferable/anchor/package.json b/tokens/token-2022/non-transferable/anchor/package.json index f800607c4..0ab4611da 100644 --- a/tokens/token-2022/non-transferable/anchor/package.json +++ b/tokens/token-2022/non-transferable/anchor/package.json @@ -1,21 +1,21 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.4.6" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.4.6" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-2022/non-transferable/anchor/tests/non-transferable.ts b/tokens/token-2022/non-transferable/anchor/tests/non-transferable.ts index 112a9eb13..414c651d2 100644 --- a/tokens/token-2022/non-transferable/anchor/tests/non-transferable.ts +++ b/tokens/token-2022/non-transferable/anchor/tests/non-transferable.ts @@ -1,9 +1,15 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; -import { ASSOCIATED_TOKEN_PROGRAM_ID, getOrCreateAssociatedTokenAccount, mintTo, TOKEN_2022_PROGRAM_ID, transfer } from '@solana/spl-token'; -import type { NonTransferable } from '../target/types/non_transferable'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; +import { + ASSOCIATED_TOKEN_PROGRAM_ID, + getOrCreateAssociatedTokenAccount, + mintTo, + TOKEN_2022_PROGRAM_ID, + transfer, +} from "@solana/spl-token"; +import type { NonTransferable } from "../target/types/non_transferable"; -describe('non-transferable', () => { +describe("non-transferable", () => { const provider = anchor.AnchorProvider.env(); const connection = provider.connection; const wallet = provider.wallet as anchor.Wallet; @@ -14,16 +20,16 @@ describe('non-transferable', () => { const mintKeypair = new anchor.web3.Keypair(); const recipient = new anchor.web3.Keypair(); - it('Create Mint with NonTransferable extension', async () => { + it("Create Mint with NonTransferable extension", async () => { const transactionSignature = await program.methods .initialize() .accounts({ mintAccount: mintKeypair.publicKey }) .signers([mintKeypair]) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); - it('Attempt Token Transfer', async () => { + it("Attempt Token Transfer", async () => { const amount = 1; const sourceTokenAccount = await getOrCreateAssociatedTokenAccount( @@ -76,7 +82,7 @@ describe('non-transferable', () => { TOKEN_2022_PROGRAM_ID, // Token Extension Program ID ); } catch (error) { - console.log('\nExpect Error:', error.logs); + console.log("\nExpect Error:", error.logs); } }); }); diff --git a/tokens/token-2022/non-transferable/native/tests/test.ts b/tokens/token-2022/non-transferable/native/tests/test.ts index 8b67b66b2..c9c0fc870 100644 --- a/tokens/token-2022/non-transferable/native/tests/test.ts +++ b/tokens/token-2022/non-transferable/native/tests/test.ts @@ -1,25 +1,31 @@ -import { Buffer } from 'node:buffer'; -import { describe, test } from 'node:test'; -import { TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; -import { Keypair, PublicKey, SYSVAR_RENT_PUBKEY, SystemProgram, Transaction, TransactionInstruction } from '@solana/web3.js'; -import * as borsh from 'borsh'; -import { assert } from 'chai'; -import { start } from 'solana-bankrun'; - - -const CreateTokenArgsSchema = { struct: { token_decimals: 'u8' } }; +import { Buffer } from "node:buffer"; +import { describe, test } from "node:test"; +import { TOKEN_2022_PROGRAM_ID } from "@solana/spl-token"; +import { + Keypair, + PublicKey, + SYSVAR_RENT_PUBKEY, + SystemProgram, + Transaction, + TransactionInstruction, +} from "@solana/web3.js"; +import * as borsh from "borsh"; +import { assert } from "chai"; +import { start } from "solana-bankrun"; + +const CreateTokenArgsSchema = { struct: { token_decimals: "u8" } }; function borshSerialize(schema: borsh.Schema, data: object): Buffer { return Buffer.from(borsh.serialize(schema, data)); } -describe('Create Token', async () => { +describe("Create Token", async () => { const PROGRAM_ID = PublicKey.unique(); - const context = await start([{ name: 'token_2022_non_transferable_program', programId: PROGRAM_ID }], []); + const context = await start([{ name: "token_2022_non_transferable_program", programId: PROGRAM_ID }], []); const client = context.banksClient; const payer = context.payer; - test('Create a Token-22 SPL-Token !', async () => { + test("Create a Token-22 SPL-Token !", async () => { const blockhash = context.lastBlockhash; const mintKeypair: Keypair = Keypair.generate(); @@ -47,6 +53,6 @@ describe('Create Token', async () => { const transaction = await client.processTransaction(tx); assert(transaction.logMessages[0].startsWith(`Program ${PROGRAM_ID}`)); - console.log('Token Mint Address: ', mintKeypair.publicKey.toBase58()); + console.log("Token Mint Address: ", mintKeypair.publicKey.toBase58()); }); }); diff --git a/tokens/token-2022/permanent-delegate/anchor/migrations/deploy.ts b/tokens/token-2022/permanent-delegate/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/tokens/token-2022/permanent-delegate/anchor/migrations/deploy.ts +++ b/tokens/token-2022/permanent-delegate/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/token-2022/permanent-delegate/anchor/package.json b/tokens/token-2022/permanent-delegate/anchor/package.json index f800607c4..0ab4611da 100644 --- a/tokens/token-2022/permanent-delegate/anchor/package.json +++ b/tokens/token-2022/permanent-delegate/anchor/package.json @@ -1,21 +1,21 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.4.6" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.4.6" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-2022/permanent-delegate/anchor/tests/permanent-delegate.ts b/tokens/token-2022/permanent-delegate/anchor/tests/permanent-delegate.ts index 0c9da2467..38d77576a 100644 --- a/tokens/token-2022/permanent-delegate/anchor/tests/permanent-delegate.ts +++ b/tokens/token-2022/permanent-delegate/anchor/tests/permanent-delegate.ts @@ -1,9 +1,9 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; -import { burnChecked, createAccount, getAccount, mintTo, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; -import type { PermanentDelegate } from '../target/types/permanent_delegate'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; +import { burnChecked, createAccount, getAccount, mintTo, TOKEN_2022_PROGRAM_ID } from "@solana/spl-token"; +import type { PermanentDelegate } from "../target/types/permanent_delegate"; -describe('permanent-delegate', () => { +describe("permanent-delegate", () => { const provider = anchor.AnchorProvider.env(); const connection = provider.connection; const wallet = provider.wallet as anchor.Wallet; @@ -13,16 +13,16 @@ describe('permanent-delegate', () => { const mintKeypair = new anchor.web3.Keypair(); - it('Create Mint with Permanent Delegate', async () => { + it("Create Mint with Permanent Delegate", async () => { const transactionSignature = await program.methods .initialize() .accounts({ mintAccount: mintKeypair.publicKey }) .signers([mintKeypair]) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); - it('Create Token Account, Mint Tokens, and burn with Permanent Delegate', async () => { + it("Create Token Account, Mint Tokens, and burn with Permanent Delegate", async () => { const amount = 100; // Random keypair to use as owner of Token Account @@ -66,9 +66,9 @@ describe('permanent-delegate', () => { undefined, // Confirmation options TOKEN_2022_PROGRAM_ID, // Token Extension Program ID ); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); const tokenAccount = await getAccount(connection, sourceTokenAccount, null, TOKEN_2022_PROGRAM_ID); - console.log('Token Account Balance:', Number(tokenAccount.amount)); + console.log("Token Account Balance:", Number(tokenAccount.amount)); }); }); diff --git a/tokens/token-2022/transfer-fee/anchor/migrations/deploy.ts b/tokens/token-2022/transfer-fee/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/tokens/token-2022/transfer-fee/anchor/migrations/deploy.ts +++ b/tokens/token-2022/transfer-fee/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/token-2022/transfer-fee/anchor/package.json b/tokens/token-2022/transfer-fee/anchor/package.json index f800607c4..0ab4611da 100644 --- a/tokens/token-2022/transfer-fee/anchor/package.json +++ b/tokens/token-2022/transfer-fee/anchor/package.json @@ -1,21 +1,21 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.4.6" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.4.6" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-2022/transfer-fee/anchor/tests/transfer-fee.ts b/tokens/token-2022/transfer-fee/anchor/tests/transfer-fee.ts index e717fb53a..78726bc74 100644 --- a/tokens/token-2022/transfer-fee/anchor/tests/transfer-fee.ts +++ b/tokens/token-2022/transfer-fee/anchor/tests/transfer-fee.ts @@ -1,10 +1,15 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; -import { ASSOCIATED_PROGRAM_ID } from '@anchor-lang/core/dist/cjs/utils/token'; -import { getAssociatedTokenAddressSync, getOrCreateAssociatedTokenAccount, mintTo, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; -import type { TransferFee } from '../target/types/transfer_fee'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; +import { ASSOCIATED_PROGRAM_ID } from "@anchor-lang/core/dist/cjs/utils/token"; +import { + getAssociatedTokenAddressSync, + getOrCreateAssociatedTokenAccount, + mintTo, + TOKEN_2022_PROGRAM_ID, +} from "@solana/spl-token"; +import type { TransferFee } from "../target/types/transfer_fee"; -describe('transfer-fee', () => { +describe("transfer-fee", () => { const provider = anchor.AnchorProvider.env(); const connection = provider.connection; const wallet = provider.wallet as anchor.Wallet; @@ -15,11 +20,21 @@ describe('transfer-fee', () => { const mintKeypair = new anchor.web3.Keypair(); const recipient = new anchor.web3.Keypair(); - const senderTokenAccountAddress = getAssociatedTokenAddressSync(mintKeypair.publicKey, wallet.publicKey, false, TOKEN_2022_PROGRAM_ID); + const senderTokenAccountAddress = getAssociatedTokenAddressSync( + mintKeypair.publicKey, + wallet.publicKey, + false, + TOKEN_2022_PROGRAM_ID, + ); - const recipientTokenAccountAddress = getAssociatedTokenAddressSync(mintKeypair.publicKey, recipient.publicKey, false, TOKEN_2022_PROGRAM_ID); + const recipientTokenAccountAddress = getAssociatedTokenAddressSync( + mintKeypair.publicKey, + recipient.publicKey, + false, + TOKEN_2022_PROGRAM_ID, + ); - it('Create Mint with Transfer Fee', async () => { + it("Create Mint with Transfer Fee", async () => { const transferFeeBasisPoints = 100; const maximumFee = 1; @@ -28,10 +43,10 @@ describe('transfer-fee', () => { .accounts({ mintAccount: mintKeypair.publicKey }) .signers([mintKeypair]) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); - it('Mint Tokens', async () => { + it("Mint Tokens", async () => { await getOrCreateAssociatedTokenAccount( connection, wallet.payer, @@ -44,10 +59,20 @@ describe('transfer-fee', () => { ASSOCIATED_PROGRAM_ID, ); - await mintTo(connection, wallet.payer, mintKeypair.publicKey, senderTokenAccountAddress, wallet.payer, 300, [], null, TOKEN_2022_PROGRAM_ID); + await mintTo( + connection, + wallet.payer, + mintKeypair.publicKey, + senderTokenAccountAddress, + wallet.payer, + 300, + [], + null, + TOKEN_2022_PROGRAM_ID, + ); }); - it('Transfer', async () => { + it("Transfer", async () => { const transactionSignature = await program.methods .transfer(new anchor.BN(100)) .accounts({ @@ -58,10 +83,10 @@ describe('transfer-fee', () => { recipientTokenAccount: recipientTokenAccountAddress, }) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); - it('Transfer Again, fee limit by maximumFee', async () => { + it("Transfer Again, fee limit by maximumFee", async () => { const transactionSignature = await program.methods .transfer(new anchor.BN(200)) .accounts({ @@ -72,10 +97,10 @@ describe('transfer-fee', () => { recipientTokenAccount: recipientTokenAccountAddress, }) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); - it('Harvest Transfer Fees to Mint Account', async () => { + it("Harvest Transfer Fees to Mint Account", async () => { const transactionSignature = await program.methods .harvest() .accounts({ mintAccount: mintKeypair.publicKey }) @@ -87,10 +112,10 @@ describe('transfer-fee', () => { }, ]) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); - it('Withdraw Transfer Fees from Mint Account', async () => { + it("Withdraw Transfer Fees from Mint Account", async () => { const transactionSignature = await program.methods .withdraw() .accounts({ @@ -98,10 +123,10 @@ describe('transfer-fee', () => { tokenAccount: senderTokenAccountAddress, }) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); - it('Update Transfer Fee', async () => { + it("Update Transfer Fee", async () => { const transferFeeBasisPoints = 0; const maximumFee = 0; @@ -109,6 +134,6 @@ describe('transfer-fee', () => { .updateFee(transferFeeBasisPoints, new anchor.BN(maximumFee)) .accounts({ mintAccount: mintKeypair.publicKey }) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); }); diff --git a/tokens/token-2022/transfer-fee/native/tests/test.ts b/tokens/token-2022/transfer-fee/native/tests/test.ts index c0f846883..e6cde2528 100644 --- a/tokens/token-2022/transfer-fee/native/tests/test.ts +++ b/tokens/token-2022/transfer-fee/native/tests/test.ts @@ -1,25 +1,31 @@ -import { Buffer } from 'node:buffer'; -import { describe, test } from 'node:test'; -import { TOKEN_2022_PROGRAM_ID } from '@solana/spl-token'; -import { Keypair, PublicKey, SYSVAR_RENT_PUBKEY, SystemProgram, Transaction, TransactionInstruction } from '@solana/web3.js'; -import * as borsh from 'borsh'; -import { assert } from 'chai'; -import { start } from 'solana-bankrun'; - - -const CreateTokenArgsSchema = { struct: { token_decimals: 'u8' } }; +import { Buffer } from "node:buffer"; +import { describe, test } from "node:test"; +import { TOKEN_2022_PROGRAM_ID } from "@solana/spl-token"; +import { + Keypair, + PublicKey, + SYSVAR_RENT_PUBKEY, + SystemProgram, + Transaction, + TransactionInstruction, +} from "@solana/web3.js"; +import * as borsh from "borsh"; +import { assert } from "chai"; +import { start } from "solana-bankrun"; + +const CreateTokenArgsSchema = { struct: { token_decimals: "u8" } }; function borshSerialize(schema: borsh.Schema, data: object): Buffer { return Buffer.from(borsh.serialize(schema, data)); } -describe('Create Token', async () => { +describe("Create Token", async () => { const PROGRAM_ID = PublicKey.unique(); - const context = await start([{ name: 'token_2022_transfer_fees_program', programId: PROGRAM_ID }], []); + const context = await start([{ name: "token_2022_transfer_fees_program", programId: PROGRAM_ID }], []); const client = context.banksClient; const payer = context.payer; - test('Create a Token-22 SPL-Token !', async () => { + test("Create a Token-22 SPL-Token !", async () => { const blockhash = context.lastBlockhash; const mintKeypair: Keypair = Keypair.generate(); @@ -47,6 +53,6 @@ describe('Create Token', async () => { const transaction = await client.processTransaction(tx); assert(transaction.logMessages[0].startsWith(`Program ${PROGRAM_ID}`)); - console.log('Token Mint Address: ', mintKeypair.publicKey.toBase58()); + console.log("Token Mint Address: ", mintKeypair.publicKey.toBase58()); }); }); diff --git a/tokens/token-2022/transfer-hook/account-data-as-seed/anchor/migrations/deploy.ts b/tokens/token-2022/transfer-hook/account-data-as-seed/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/tokens/token-2022/transfer-hook/account-data-as-seed/anchor/migrations/deploy.ts +++ b/tokens/token-2022/transfer-hook/account-data-as-seed/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/token-2022/transfer-hook/account-data-as-seed/anchor/package.json b/tokens/token-2022/transfer-hook/account-data-as-seed/anchor/package.json index 3c254f5f9..c4ab86214 100644 --- a/tokens/token-2022/transfer-hook/account-data-as-seed/anchor/package.json +++ b/tokens/token-2022/transfer-hook/account-data-as-seed/anchor/package.json @@ -1,24 +1,24 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.4.0", - "@solana/web3.js": "^1.98.4" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/chai-as-promised": "^7.1.8", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "chai-as-promised": "^7.1.2", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.4.0", + "@solana/web3.js": "^1.98.4" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/chai-as-promised": "^7.1.8", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "chai-as-promised": "^7.1.2", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-2022/transfer-hook/account-data-as-seed/anchor/tests/transfer-hook.ts b/tokens/token-2022/transfer-hook/account-data-as-seed/anchor/tests/transfer-hook.ts index cac2820fe..b13374d8c 100644 --- a/tokens/token-2022/transfer-hook/account-data-as-seed/anchor/tests/transfer-hook.ts +++ b/tokens/token-2022/transfer-hook/account-data-as-seed/anchor/tests/transfer-hook.ts @@ -1,5 +1,5 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; import { ASSOCIATED_TOKEN_PROGRAM_ID, createAssociatedTokenAccountInstruction, @@ -11,16 +11,23 @@ import { getAssociatedTokenAddressSync, getMintLen, TOKEN_2022_PROGRAM_ID, -} from '@solana/spl-token'; -import { Keypair, PublicKey, SendTransactionError, SystemProgram, sendAndConfirmTransaction, Transaction } from '@solana/web3.js'; -import { BN } from 'bn.js'; -import chai, { expect } from 'chai'; -import chaiAsPromised from 'chai-as-promised'; -import type { TransferHook } from '../target/types/transfer_hook'; +} from "@solana/spl-token"; +import { + Keypair, + PublicKey, + SendTransactionError, + SystemProgram, + sendAndConfirmTransaction, + Transaction, +} from "@solana/web3.js"; +import { BN } from "bn.js"; +import chai, { expect } from "chai"; +import chaiAsPromised from "chai-as-promised"; +import type { TransferHook } from "../target/types/transfer_hook"; chai.use(chaiAsPromised); -describe('transfer-hook', () => { +describe("transfer-hook", () => { // Configure the client to use the local cluster. const provider = anchor.AnchorProvider.env(); anchor.setProvider(provider); @@ -55,13 +62,16 @@ describe('transfer-hook', () => { // ExtraAccountMetaList address // Store extra accounts required by the custom transfer hook instruction const [extraAccountMetaListPDA] = PublicKey.findProgramAddressSync( - [Buffer.from('extra-account-metas'), mint.publicKey.toBuffer()], + [Buffer.from("extra-account-metas"), mint.publicKey.toBuffer()], program.programId, ); - const [counterPDA] = PublicKey.findProgramAddressSync([Buffer.from('counter'), wallet.publicKey.toBuffer()], program.programId); + const [counterPDA] = PublicKey.findProgramAddressSync( + [Buffer.from("counter"), wallet.publicKey.toBuffer()], + program.programId, + ); - it('Create Mint Account with Transfer Hook Extension', async () => { + it("Create Mint Account with Transfer Hook Extension", async () => { const extensions = [ExtensionType.TransferHook]; const mintLen = getMintLen(extensions); const lamports = await provider.connection.getMinimumBalanceForRentExemption(mintLen); @@ -85,12 +95,12 @@ describe('transfer-hook', () => { const txSig = await sendAndConfirmTransaction(provider.connection, transaction, [wallet.payer, mint], { skipPreflight: true, - commitment: 'finalized', + commitment: "finalized", }); const txDetails = await program.provider.connection.getTransaction(txSig, { maxSupportedTransactionVersion: 0, - commitment: 'confirmed', + commitment: "confirmed", }); console.log(txDetails.meta.logMessages); @@ -99,7 +109,7 @@ describe('transfer-hook', () => { // Create the two token accounts for the transfer-hook enabled mint // Fund the sender token account with 100 tokens - it('Create Token Accounts and Mint Tokens', async () => { + it("Create Token Accounts and Mint Tokens", async () => { // 100 tokens const amount = 100 * 10 ** decimals; @@ -129,7 +139,7 @@ describe('transfer-hook', () => { }); // Account to store extra accounts required by the transfer hook instruction - it('Create ExtraAccountMetaList Account', async () => { + it("Create ExtraAccountMetaList Account", async () => { const initializeExtraAccountMetaListInstruction = await program.methods .initializeExtraAccountMetaList() .accounts({ @@ -139,11 +149,14 @@ describe('transfer-hook', () => { const transaction = new Transaction().add(initializeExtraAccountMetaListInstruction); - const txSig = await sendAndConfirmTransaction(provider.connection, transaction, [wallet.payer], { skipPreflight: true, commitment: 'confirmed' }); - console.log('Transaction Signature:', txSig); + const txSig = await sendAndConfirmTransaction(provider.connection, transaction, [wallet.payer], { + skipPreflight: true, + commitment: "confirmed", + }); + console.log("Transaction Signature:", txSig); }); - it('Transfer Hook with Extra Account Meta', async () => { + it("Transfer Hook with Extra Account Meta", async () => { // 1 tokens const amount = 1 * 10 ** decimals; const amountBigInt = BigInt(amount); @@ -157,7 +170,7 @@ describe('transfer-hook', () => { amountBigInt, decimals, [], - 'confirmed', + "confirmed", TOKEN_2022_PROGRAM_ID, ); @@ -168,10 +181,10 @@ describe('transfer-hook', () => { const transaction = new Transaction().add(transferInstructionWithHelper); const txSig = await sendAndConfirmTransaction(connection, transaction, [wallet.payer], { skipPreflight: true }); - console.log('Transfer Signature:', txSig); + console.log("Transfer Signature:", txSig); }); - it('Try call transfer hook without transfer', async () => { + it("Try call transfer hook without transfer", async () => { const transferHookIx = await program.methods .transferHook(new BN(1)) .accounts({ diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/anchor/src/abl-token-exports.ts b/tokens/token-2022/transfer-hook/allow-block-list-token/anchor/src/abl-token-exports.ts index 6d4b27af6..9e147ff51 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/anchor/src/abl-token-exports.ts +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/anchor/src/abl-token-exports.ts @@ -1,8 +1,8 @@ // Here we export some useful types and functions for interacting with the Anchor program. -import { AnchorProvider, Program } from '@anchor-lang/core'; -import { Cluster, PublicKey } from '@solana/web3.js'; -import ABLTokenIDL from '../target/idl/abl_token.json'; -import type { AblToken } from '../target/types/abl_token'; +import { type AnchorProvider, Program } from "@anchor-lang/core"; +import { type Cluster, PublicKey } from "@solana/web3.js"; +import ABLTokenIDL from "../target/idl/abl_token.json"; +import type { AblToken } from "../target/types/abl_token"; // Re-export the generated IDL and type export { ABLTokenIDL }; @@ -12,16 +12,22 @@ export const ABL_TOKEN_PROGRAM_ID = new PublicKey(ABLTokenIDL.address); // This is a helper function to get the Basic Anchor program. export function getABLTokenProgram(provider: AnchorProvider, address?: PublicKey): Program { - return new Program({ ...ABLTokenIDL, address: address ? address.toBase58() : ABLTokenIDL.address } as AblToken, provider); + return new Program( + { + ...ABLTokenIDL, + address: address ? address.toBase58() : ABLTokenIDL.address, + } as AblToken, + provider, + ); } // This is a helper function to get the program ID for the Basic program depending on the cluster. export function getABLTokenProgramId(cluster: Cluster) { switch (cluster) { - case 'devnet': - case 'testnet': + case "devnet": + case "testnet": // This is the program ID for the Basic program on devnet and testnet. - return new PublicKey('6z68wfurCMYkZG51s1Et9BJEd9nJGUusjHXNt4dGbNNF'); + return new PublicKey("6z68wfurCMYkZG51s1Et9BJEd9nJGUusjHXNt4dGbNNF"); default: return ABL_TOKEN_PROGRAM_ID; } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/anchor/src/index.ts b/tokens/token-2022/transfer-hook/allow-block-list-token/anchor/src/index.ts index 04fdd85fb..d7552798e 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/anchor/src/index.ts +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/anchor/src/index.ts @@ -1 +1 @@ -export * from './abl-token-exports'; +export * from "./abl-token-exports"; diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/anchor/tests/basic.test.ts b/tokens/token-2022/transfer-hook/allow-block-list-token/anchor/tests/basic.test.ts index c024a5251..b4c288f90 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/anchor/tests/basic.test.ts +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/anchor/tests/basic.test.ts @@ -1,14 +1,14 @@ -import * as anchor from '@anchor-lang/core'; -import { Program } from '@anchor-lang/core'; -import { AblToken } from '../target/types/abl_token'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; +import type { AblToken } from "../target/types/abl_token"; -describe('abl-token', () => { +describe("abl-token", () => { // Configure the client to use the local cluster. anchor.setProvider(anchor.AnchorProvider.env()); const _program = anchor.workspace.ABLToken as Program; - it('should run the program', async () => { + it("should run the program", async () => { // Add your test here. }); }); diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/eslint.config.mjs b/tokens/token-2022/transfer-hook/allow-block-list-token/eslint.config.mjs index 835e40116..6bcf64707 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/eslint.config.mjs +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/eslint.config.mjs @@ -1,6 +1,6 @@ -import { dirname } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { FlatCompat } from '@eslint/eslintrc'; +import { dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { FlatCompat } from "@eslint/eslintrc"; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); @@ -9,6 +9,6 @@ const compat = new FlatCompat({ baseDirectory: __dirname, }); -const eslintConfig = [...compat.extends('next/core-web-vitals', 'next/typescript')]; +const eslintConfig = [...compat.extends("next/core-web-vitals", "next/typescript")]; export default eslintConfig; diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/next.config.ts b/tokens/token-2022/transfer-hook/allow-block-list-token/next.config.ts index 5e891cf00..e9ffa3083 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/next.config.ts +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/next.config.ts @@ -1,4 +1,4 @@ -import type { NextConfig } from 'next'; +import type { NextConfig } from "next"; const nextConfig: NextConfig = { /* config options here */ diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/package.json b/tokens/token-2022/transfer-hook/allow-block-list-token/package.json index e6885b10e..8a66c6c9a 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/package.json +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/package.json @@ -1,58 +1,58 @@ { - "name": "legacy-next-tailwind-basic", - "version": "0.0.0", - "private": true, - "scripts": { - "anchor": "cd anchor && anchor", - "anchor-build": "cd anchor && anchor build", - "anchor-localnet": "cd anchor && anchor localnet", - "anchor-test": "cd anchor && anchor test", - "build": "next build", - "ci": "npm run build && npm run lint && npm run format:check", - "dev": "next dev --turbopack", - "format": "prettier --write .", - "format:check": "prettier --check .", - "lint": "next lint", - "start": "next start" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@radix-ui/react-dialog": "^1.1.14", - "@radix-ui/react-dropdown-menu": "^2.1.15", - "@radix-ui/react-label": "^2.1.7", - "@radix-ui/react-slot": "^1.2.3", - "@solana/spl-token": "0.4.13", - "@solana/wallet-adapter-base": "0.9.27", - "@solana/wallet-adapter-react": "0.15.39", - "@solana/wallet-adapter-react-ui": "0.9.39", - "@solana/web3.js": "^1.98.4", - "@tanstack/react-query": "^5.82.0", - "class-variance-authority": "^0.7.1", - "clsx": "^2.1.1", - "jotai": "^2.12.5", - "lucide-react": "^0.525.0", - "next": "15.3.5", - "next-themes": "^0.4.6", - "react": "^19.1.0", - "react-dom": "^19.1.0", - "sonner": "^2.0.6", - "tailwind-merge": "^3.3.1", - "tw-animate-css": "^1.3.5" - }, - "devDependencies": { - "@eslint/eslintrc": "^3.3.1", - "@tailwindcss/postcss": "^4.1.4", - "@types/bn.js": "^5.1.6", - "@types/jest": "^29.5.14", - "@types/node": "^22.15.3", - "@types/react": "^19.1.2", - "@types/react-dom": "^19.1.2", - "eslint": "^9.25.1", - "eslint-config-next": "15.3.1", - "jest": "^29.7.0", - "prettier": "^3.5.3", - "tailwindcss": "^4.1.4", - "ts-jest": "^29.3.2", - "typescript": "^5.8.3" - } + "name": "legacy-next-tailwind-basic", + "version": "0.0.0", + "private": true, + "scripts": { + "anchor": "cd anchor && anchor", + "anchor-build": "cd anchor && anchor build", + "anchor-localnet": "cd anchor && anchor localnet", + "anchor-test": "cd anchor && anchor test", + "build": "next build", + "ci": "npm run build && npm run lint && npm run format:check", + "dev": "next dev --turbopack", + "format": "prettier --write .", + "format:check": "prettier --check .", + "lint": "next lint", + "start": "next start" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@radix-ui/react-dialog": "^1.1.14", + "@radix-ui/react-dropdown-menu": "^2.1.15", + "@radix-ui/react-label": "^2.1.7", + "@radix-ui/react-slot": "^1.2.3", + "@solana/spl-token": "0.4.13", + "@solana/wallet-adapter-base": "0.9.27", + "@solana/wallet-adapter-react": "0.15.39", + "@solana/wallet-adapter-react-ui": "0.9.39", + "@solana/web3.js": "^1.98.4", + "@tanstack/react-query": "^5.82.0", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "jotai": "^2.12.5", + "lucide-react": "^0.525.0", + "next": "15.3.5", + "next-themes": "^0.4.6", + "react": "^19.1.0", + "react-dom": "^19.1.0", + "sonner": "^2.0.6", + "tailwind-merge": "^3.3.1", + "tw-animate-css": "^1.3.5" + }, + "devDependencies": { + "@eslint/eslintrc": "^3.3.1", + "@tailwindcss/postcss": "^4.1.4", + "@types/bn.js": "^5.1.6", + "@types/jest": "^29.5.14", + "@types/node": "^22.15.3", + "@types/react": "^19.1.2", + "@types/react-dom": "^19.1.2", + "eslint": "^9.25.1", + "eslint-config-next": "15.3.1", + "jest": "^29.7.0", + "prettier": "^3.5.3", + "tailwindcss": "^4.1.4", + "ts-jest": "^29.3.2", + "typescript": "^5.8.3" + } } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/postcss.config.mjs b/tokens/token-2022/transfer-hook/allow-block-list-token/postcss.config.mjs index ba720fe55..c7bcb4b1e 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/postcss.config.mjs +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/postcss.config.mjs @@ -1,5 +1,5 @@ const config = { - plugins: ['@tailwindcss/postcss'], + plugins: ["@tailwindcss/postcss"], }; export default config; diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/account/[address]/page.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/account/[address]/page.tsx index 5bb6688e9..0f46f881f 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/account/[address]/page.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/account/[address]/page.tsx @@ -1,5 +1,5 @@ -import AccountDetailFeature from '@/components/account/account-detail-feature' +import AccountDetailFeature from "@/components/account/account-detail-feature"; export default function Page() { - return + return ; } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/account/page.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/account/page.tsx index 1b0e27684..cf7d07d31 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/account/page.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/account/page.tsx @@ -1,5 +1,5 @@ -import AccountListFeature from '@/components/account/account-list-feature' +import AccountListFeature from "@/components/account/account-list-feature"; export default function Page() { - return + return ; } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/config/page.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/config/page.tsx index e1cde08f1..15749c63c 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/config/page.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/config/page.tsx @@ -1,6 +1,5 @@ - -import AblTokenConfig from '@/components/abl-token/abl-token-config' +import AblTokenConfig from "@/components/abl-token/abl-token-config"; export default function Page() { - return + return ; } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/create-token/page.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/create-token/page.tsx index 39c705292..93a0c913e 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/create-token/page.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/create-token/page.tsx @@ -1,5 +1,5 @@ -import AblTokenFeature from '@/components/abl-token/abl-token-feature' +import AblTokenFeature from "@/components/abl-token/abl-token-feature"; export default function Page() { - return + return ; } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/globals.css b/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/globals.css index 2edb31d83..00bfb4477 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/globals.css +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/globals.css @@ -1,5 +1,5 @@ -@import 'tailwindcss'; -@import 'tw-animate-css'; +@import "tailwindcss"; +@import "tw-animate-css"; @custom-variant dark (&:is(.dark *)); @@ -121,7 +121,7 @@ } .wallet-adapter-button-trigger { - height: auto !important; + height: auto; @apply !border !bg-background !shadow-xs hover:!bg-accent !text-accent-foreground hover:!text-accent-foreground dark:!bg-input/30 !border-input/10 dark:!border-input dark:hover:!bg-input/50; @apply !px-2 !py-[6px] !rounded-md !text-sm !font-semibold !shadow-sm !transition-all; } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/layout.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/layout.tsx index 6cfdc1d13..7cc19d2be 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/layout.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/layout.tsx @@ -1,22 +1,22 @@ -import type { Metadata } from 'next' -import './globals.css' -import { AppProviders } from '@/components/app-providers' -import { AppLayout } from '@/components/app-layout' -import React from 'react' +import type { Metadata } from "next"; +import "./globals.css"; +import type React from "react"; +import { AppLayout } from "@/components/app-layout"; +import { AppProviders } from "@/components/app-providers"; export const metadata: Metadata = { - title: 'ABL Token', - description: 'ABL Token', -} + title: "ABL Token", + description: "ABL Token", +}; const links: { label: string; path: string }[] = [ // More links... - { label: 'Home', path: '/' }, - { label: 'Account', path: '/account' }, - { label: 'Config', path: '/config' }, - { label: 'Create New Token', path: '/create-token' }, - { label: 'Manage Token', path: '/manage-token' }, -] + { label: "Home", path: "/" }, + { label: "Account", path: "/account" }, + { label: "Config", path: "/config" }, + { label: "Create New Token", path: "/create-token" }, + { label: "Manage Token", path: "/manage-token" }, +]; export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) { return ( @@ -27,15 +27,15 @@ export default function RootLayout({ children }: Readonly<{ children: React.Reac - ) + ); } // Patch BigInt so we can log it using JSON.stringify without any errors declare global { interface BigInt { - toJSON(): string + toJSON(): string; } } BigInt.prototype.toJSON = function () { - return this.toString() -} + return this.toString(); +}; diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/manage-token/[address]/page.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/manage-token/[address]/page.tsx index 7a5c53e12..b7cd18e03 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/manage-token/[address]/page.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/manage-token/[address]/page.tsx @@ -1,5 +1,5 @@ -import AblTokenManageTokenDetail from '@/components/abl-token/abl-token-manage-token-detail' +import AblTokenManageTokenDetail from "@/components/abl-token/abl-token-manage-token-detail"; export default function Page() { - return + return ; } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/manage-token/page.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/manage-token/page.tsx index 175476840..8c33d78e8 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/manage-token/page.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/manage-token/page.tsx @@ -1,5 +1,5 @@ -import AblTokenManageToken from '@/components/abl-token/abl-token-manage-token' +import AblTokenManageToken from "@/components/abl-token/abl-token-manage-token"; export default function Page() { - return + return ; } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/page.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/page.tsx index b0e9cd11b..a7d176adc 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/page.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/app/page.tsx @@ -1,5 +1,5 @@ -import { DashboardFeature } from '@/components/dashboard/dashboard-feature' +import { DashboardFeature } from "@/components/dashboard/dashboard-feature"; export default function Home() { - return + return ; } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-config.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-config.tsx index 57a42b9fd..6cfd261e2 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-config.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-config.tsx @@ -1,18 +1,18 @@ -'use client' +"use client"; -import { useWallet } from '@solana/wallet-adapter-react' -import { ExplorerLink } from '../cluster/cluster-ui' -import { WalletButton } from '../solana/solana-provider' -import { useAblTokenProgram } from './abl-token-data-access' -import { AppHero } from '../app-hero' -import { ellipsify } from '@/lib/utils' -import { Button } from '@/components/ui/button' -import React from 'react' -import { PublicKey } from '@solana/web3.js' +import { useWallet } from "@solana/wallet-adapter-react"; +import { PublicKey } from "@solana/web3.js"; +import React from "react"; +import { Button } from "@/components/ui/button"; +import { ellipsify } from "@/lib/utils"; +import { AppHero } from "../app-hero"; +import { ExplorerLink } from "../cluster/cluster-ui"; +import { WalletButton } from "../solana/solana-provider"; +import { useAblTokenProgram } from "./abl-token-data-access"; export default function AblTokenConfig() { - const { publicKey } = useWallet() - const { programId, getConfig, getAbWallets } = useAblTokenProgram() + const { publicKey } = useWallet(); + const { programId, getConfig, getAbWallets } = useAblTokenProgram(); const config = getConfig.data; let abWallets = getAbWallets.data; @@ -20,11 +20,11 @@ export default function AblTokenConfig() { const handleWalletListUpdate = React.useCallback(async () => { await getAbWallets.refetch(); abWallets = getAbWallets.data; - }, []) + }, [getAbWallets.refetch, getAbWallets.data]); return publicKey ? (
- +

@@ -56,13 +56,12 @@ export default function AblTokenConfig() {
- ) + ); } - export function AblTokenConfigCreate() { - const { initConfig, getConfig } = useAblTokenProgram() - const { publicKey } = useWallet() + const { initConfig, getConfig } = useAblTokenProgram(); + const { publicKey } = useWallet(); const handleCreate = async () => { if (!publicKey) return; @@ -71,7 +70,7 @@ export function AblTokenConfigCreate() { // Refresh the config list getConfig.refetch(); } catch (err) { - console.error('Failed to create config:', err); + console.error("Failed to create config:", err); } }; @@ -81,17 +80,23 @@ export function AblTokenConfigCreate() {

Initialize the ABL Token configuration. This will set up the necessary accounts for managing allow/block lists.

- ); } -export function AblTokenConfigList({ abWallets }: { abWallets: {publicKey: PublicKey, account: {wallet: PublicKey, allowed: boolean}}[] | undefined }) { +export function AblTokenConfigList({ + abWallets, +}: { + abWallets: + | { + publicKey: PublicKey; + account: { wallet: PublicKey; allowed: boolean }; + }[] + | undefined; +}) { return (

ABL Token Config List

@@ -109,8 +114,8 @@ export function AblTokenConfigList({ abWallets }: { abWallets: {publicKey: Publi {wallet.account.wallet.toString()} - - {wallet.account.allowed ? 'Allowed' : 'Blocked'} + + {wallet.account.allowed ? "Allowed" : "Blocked"} @@ -127,139 +132,139 @@ export function AblTokenConfigList({ abWallets }: { abWallets: {publicKey: Publi interface WalletChange { address: string; - mode: 'allow' | 'block' | 'remove'; - status?: 'pending' | 'success' | 'error'; + mode: "allow" | "block" | "remove"; + status?: "pending" | "success" | "error"; error?: string; } export function AblTokenConfigListChange({ onWalletListUpdate }: { onWalletListUpdate: () => void }) { - const { getAbWallets, processBatchWallets } = useAblTokenProgram() - const [isEditing, setIsEditing] = React.useState(false) - const [walletChanges, setWalletChanges] = React.useState([]) - const [isProcessing, setIsProcessing] = React.useState(false) + const { getAbWallets, processBatchWallets } = useAblTokenProgram(); + const [isEditing, setIsEditing] = React.useState(false); + const [walletChanges, setWalletChanges] = React.useState([]); + const [isProcessing, setIsProcessing] = React.useState(false); const existingWallets = React.useMemo(() => { - const wallets = getAbWallets.data || [] - return new Map(wallets.map(w => [w.account.wallet.toString(), w.account.allowed])) - }, [getAbWallets.data]) + const wallets = getAbWallets.data || []; + return new Map(wallets.map((w) => [w.account.wallet.toString(), w.account.allowed])); + }, [getAbWallets.data]); const handleDragOver = (e: React.DragEvent) => { - e.preventDefault() - } + e.preventDefault(); + }; const handleDrop = async (e: React.DragEvent) => { - e.preventDefault() - const file = e.dataTransfer.files[0] - if (file && file.type === 'text/csv') { - const text = await file.text() - const rows = text.split('\n') - + e.preventDefault(); + const file = e.dataTransfer.files[0]; + if (file && file.type === "text/csv") { + const text = await file.text(); + const rows = text.split("\n"); + // Create a Set of existing wallet addresses for deduplication const existingAddresses = new Set([ ...Array.from(existingWallets.keys()), - ...walletChanges.map(w => w.address) - ]) - + ...walletChanges.map((w) => w.address), + ]); + const parsed: WalletChange[] = rows - .filter(row => row.trim()) - .map(row => { - const [address, mode] = row.split(',').map(field => field.trim()) + .filter((row) => row.trim()) + .map((row) => { + const [address, mode] = row.split(",").map((field) => field.trim()); return { address, - mode: mode.toLowerCase() as 'allow' | 'block' | 'remove' - } + mode: mode.toLowerCase() as "allow" | "block" | "remove", + }; }) - .filter(entry => { + .filter((entry) => { try { - new PublicKey(entry.address) - return ['allow', 'block', 'remove'].includes(entry.mode) + new PublicKey(entry.address); + return ["allow", "block", "remove"].includes(entry.mode); } catch { - return false + return false; } }) - .filter(entry => { + .filter((entry) => { // Only allow 'remove' for existing wallets - if (entry.mode === 'remove') { - return existingWallets.has(entry.address) + if (entry.mode === "remove") { + return existingWallets.has(entry.address); } - return true + return true; }) // Deduplicate entries, keeping the last occurrence of each address .reduce((acc, entry) => { - const existingIndex = acc.findIndex(w => w.address === entry.address) + const existingIndex = acc.findIndex((w) => w.address === entry.address); if (existingIndex >= 0) { - acc[existingIndex] = entry + acc[existingIndex] = entry; } else { - acc.push(entry) + acc.push(entry); } - return acc + return acc; }, [] as WalletChange[]) // Filter out entries that already exist in the current state - .filter(entry => !existingAddresses.has(entry.address)) + .filter((entry) => !existingAddresses.has(entry.address)); if (parsed.length > 0) { - setWalletChanges(prev => [...prev, ...parsed]) - setIsEditing(true) + setWalletChanges((prev) => [...prev, ...parsed]); + setIsEditing(true); } } - } + }; const handleAddWallet = () => { - setWalletChanges(prev => [...prev, { address: '', mode: 'allow' }]) - setIsEditing(true) - } + setWalletChanges((prev) => [...prev, { address: "", mode: "allow" }]); + setIsEditing(true); + }; const handleUpdateWallet = (index: number, field: keyof WalletChange, value: string) => { - setWalletChanges(prev => prev.map((wallet, i) => - i === index ? { ...wallet, [field]: value } : wallet - )) - } + setWalletChanges((prev) => prev.map((wallet, i) => (i === index ? { ...wallet, [field]: value } : wallet))); + }; const handleRemoveWallet = (index: number) => { - setWalletChanges(prev => prev.filter((_, i) => i !== index)) - } + setWalletChanges((prev) => prev.filter((_, i) => i !== index)); + }; const processWallets = async () => { - setIsProcessing(true) - const batchSize = 10 - const batches = [] - + setIsProcessing(true); + const batchSize = 10; + const batches = []; + for (let i = 0; i < walletChanges.length; i += batchSize) { - batches.push(walletChanges.slice(i, i + batchSize)) + batches.push(walletChanges.slice(i, i + batchSize)); } for (const batch of batches) { try { await processBatchWallets.mutateAsync({ - wallets: batch.map(w => ({ + wallets: batch.map((w) => ({ wallet: new PublicKey(w.address), - mode: w.mode - })) - }) - + mode: w.mode, + })), + }); + // Mark batch as successful - setWalletChanges(prev => prev.map(wallet => - batch.some(b => b.address === wallet.address) - ? { ...wallet, status: 'success' } - : wallet - )) + setWalletChanges((prev) => + prev.map((wallet) => + batch.some((b) => b.address === wallet.address) ? { ...wallet, status: "success" } : wallet, + ), + ); } catch (error: unknown) { - const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred' + const errorMessage = error instanceof Error ? error.message : "Unknown error occurred"; // Mark batch as failed - setWalletChanges(prev => prev.map(wallet => - batch.some(b => b.address === wallet.address) - ? { ...wallet, status: 'error', error: errorMessage } - : wallet - )) + setWalletChanges((prev) => + prev.map((wallet) => + batch.some((b) => b.address === wallet.address) + ? { ...wallet, status: "error", error: errorMessage } + : wallet, + ), + ); } } // Refresh wallet list and clear successful changes - await getAbWallets.refetch() - setWalletChanges(prev => prev.filter(w => w.status !== 'success')) - setIsProcessing(false) + await getAbWallets.refetch(); + setWalletChanges((prev) => prev.filter((w) => w.status !== "success")); + setIsProcessing(false); // Notify parent component to update the wallet list - onWalletListUpdate() - } + onWalletListUpdate(); + }; return (
@@ -270,17 +275,15 @@ export function AblTokenConfigListChange({ onWalletListUpdate }: { onWalletListU Add Wallet {isEditing && ( - )}
-
Mode can be: allow, block, or remove (remove only works for existing wallets)

-
+ {walletChanges.length > 0 && (
@@ -304,13 +307,13 @@ export function AblTokenConfigListChange({ onWalletListUpdate }: { onWalletListU {walletChanges.map((wallet, index) => ( - + handleUpdateWallet(index, 'address', e.target.value)} + onChange={(e) => handleUpdateWallet(index, "address", e.target.value)} placeholder="Wallet address" disabled={isProcessing} /> @@ -319,30 +322,26 @@ export function AblTokenConfigListChange({ onWalletListUpdate }: { onWalletListU - {wallet.status === 'success' && ( - - )} - {wallet.status === 'error' && ( - + {wallet.status === "success" && } + {wallet.status === "error" && ( + + ✗ + )} - @@ -353,5 +352,5 @@ export function AblTokenConfigListChange({ onWalletListUpdate }: { onWalletListU
)} - ) -} \ No newline at end of file + ); +} diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-data-access.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-data-access.tsx index 3b1194a3e..505550dac 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-data-access.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-data-access.tsx @@ -1,290 +1,281 @@ -'use client' - -import { getABLTokenProgram, getABLTokenProgramId } from '@project/anchor' -import { useConnection } from '@solana/wallet-adapter-react' -import { Cluster, Keypair, PublicKey, Transaction } from '@solana/web3.js' -import { useMutation, useQuery } from '@tanstack/react-query' -import { useMemo } from 'react' -import { useCluster } from '../cluster/cluster-data-access' -import { useAnchorProvider } from '../solana/solana-provider' -import { useTransactionToast } from '../use-transaction-toast' -import { toast } from 'sonner' -import { BN } from '@anchor-lang/core' -import { createAssociatedTokenAccountIdempotentInstruction, createMintToCheckedInstruction, getAssociatedTokenAddressSync, getMint, getPermanentDelegate, getTokenMetadata, getTransferHook, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token' +"use client"; + +import type { BN } from "@anchor-lang/core"; +import { getABLTokenProgram, getABLTokenProgramId } from "@project/anchor"; +import { + createAssociatedTokenAccountIdempotentInstruction, + createMintToCheckedInstruction, + getAssociatedTokenAddressSync, + getMint, + getPermanentDelegate, + getTokenMetadata, + getTransferHook, + TOKEN_2022_PROGRAM_ID, +} from "@solana/spl-token"; +import { useConnection } from "@solana/wallet-adapter-react"; +import { type Cluster, Keypair, PublicKey, Transaction } from "@solana/web3.js"; +import { useMutation, useQuery } from "@tanstack/react-query"; +import { useMemo } from "react"; +import { toast } from "sonner"; +import { useCluster } from "../cluster/cluster-data-access"; +import { useAnchorProvider } from "../solana/solana-provider"; +import { useTransactionToast } from "../use-transaction-toast"; export function useHasTransferHookEnabled(mint: PublicKey) { - const { connection } = useConnection() - const { cluster } = useCluster() - const programId = useMemo(() => getABLTokenProgramId(cluster.network as Cluster), [cluster]) + const { connection } = useConnection(); + const { cluster } = useCluster(); + const programId = useMemo(() => getABLTokenProgramId(cluster.network as Cluster), [cluster]); return useQuery({ - queryKey: ['has-transfer-hook', { cluster }], + queryKey: ["has-transfer-hook", { cluster }], queryFn: async () => { - const mintInfo = await getMint( - connection, - mint, - "confirmed", - TOKEN_2022_PROGRAM_ID, - ); + const mintInfo = await getMint(connection, mint, "confirmed", TOKEN_2022_PROGRAM_ID); const transferHook = getTransferHook(mintInfo); return transferHook !== null && programId.equals(transferHook.programId); }, - }) + }); } export function useGetToken(mint: PublicKey) { - const { connection } = useConnection() - const { cluster } = useCluster() - const programId = useMemo(() => getABLTokenProgramId(cluster.network as Cluster), [cluster]) + const { connection } = useConnection(); + const { cluster } = useCluster(); + const programId = useMemo(() => getABLTokenProgramId(cluster.network as Cluster), [cluster]); return useQuery({ - queryKey: ['get-token', { endpoint: connection.rpcEndpoint, mint }], - queryFn: async () => { - const mintInfo = await getMint( - connection, - mint, - "confirmed", - TOKEN_2022_PROGRAM_ID, - ); - - const metadata = await getTokenMetadata( - connection, - mint, - "confirmed", - TOKEN_2022_PROGRAM_ID, - ); + queryKey: ["get-token", { endpoint: connection.rpcEndpoint, mint }], + queryFn: async () => { + const mintInfo = await getMint(connection, mint, "confirmed", TOKEN_2022_PROGRAM_ID); - const mode = metadata?.additionalMetadata.find((metadata) => metadata[0] === "AB")?.[1] || null; - const threshold = metadata?.additionalMetadata.find((metadata) => metadata[0] === "threshold")?.[1] || null; + const metadata = await getTokenMetadata(connection, mint, "confirmed", TOKEN_2022_PROGRAM_ID); - const permanentDelegate = await getPermanentDelegate(mintInfo); + const mode = metadata?.additionalMetadata.find((metadata) => metadata[0] === "AB")?.[1] || null; + const threshold = metadata?.additionalMetadata.find((metadata) => metadata[0] === "threshold")?.[1] || null; - const transferHook = getTransferHook(mintInfo); + const permanentDelegate = await getPermanentDelegate(mintInfo); - const isTransferHookEnabled = transferHook !== null; - const isTransferHookSet = transferHook?.programId?.equals(programId) || false; - const transferHookProgramId = transferHook?.programId || null; + const transferHook = getTransferHook(mintInfo); - return { - name: metadata?.name, - symbol: metadata?.symbol, - uri: metadata?.uri, - decimals: mintInfo.decimals, - supply: mintInfo.supply, - mintAuthority: mintInfo.mintAuthority, - freezeAuthority: mintInfo.freezeAuthority, - permanentDelegate: permanentDelegate?.delegate ?? null, - isTransferHookEnabled, - isTransferHookSet, - transferHookProgramId, - mode, - threshold, - } - }, -}) + const isTransferHookEnabled = transferHook !== null; + const isTransferHookSet = transferHook?.programId?.equals(programId) || false; + const transferHookProgramId = transferHook?.programId || null; + + return { + name: metadata?.name, + symbol: metadata?.symbol, + uri: metadata?.uri, + decimals: mintInfo.decimals, + supply: mintInfo.supply, + mintAuthority: mintInfo.mintAuthority, + freezeAuthority: mintInfo.freezeAuthority, + permanentDelegate: permanentDelegate?.delegate ?? null, + isTransferHookEnabled, + isTransferHookSet, + transferHookProgramId, + mode, + threshold, + }; + }, + }); } - export function useAblTokenProgram() { - const { connection } = useConnection() - const { cluster } = useCluster() - const transactionToast = useTransactionToast() - const provider = useAnchorProvider() - const programId = useMemo(() => getABLTokenProgramId(cluster.network as Cluster), [cluster]) - const program = useMemo(() => getABLTokenProgram(provider, programId), [provider, programId]) + const { connection } = useConnection(); + const { cluster } = useCluster(); + const transactionToast = useTransactionToast(); + const provider = useAnchorProvider(); + const programId = useMemo(() => getABLTokenProgramId(cluster.network as Cluster), [cluster]); + const program = useMemo(() => getABLTokenProgram(provider, programId), [provider, programId]); const getProgramAccount = useQuery({ - queryKey: ['get-program-account', { cluster }], + queryKey: ["get-program-account", { cluster }], queryFn: () => connection.getParsedAccountInfo(programId), - }) + }); const initToken = useMutation({ - mutationKey: ['abl-token', 'init-token', { cluster }], + mutationKey: ["abl-token", "init-token", { cluster }], mutationFn: (args: { - mintAuthority: PublicKey, - freezeAuthority: PublicKey, - permanentDelegate: PublicKey, - transferHookAuthority: PublicKey, - mode: string, - threshold: BN, - name: string, - symbol: string, - uri: string, - decimals: number, + mintAuthority: PublicKey; + freezeAuthority: PublicKey; + permanentDelegate: PublicKey; + transferHookAuthority: PublicKey; + mode: string; + threshold: BN; + name: string; + symbol: string; + uri: string; + decimals: number; }) => { - const modeEnum = args.mode === 'allow' ? { allow: {} } : args.mode === 'block' ? { block: {}} : { mixed: {}}; + const modeEnum = args.mode === "allow" ? { allow: {} } : args.mode === "block" ? { block: {} } : { mixed: {} }; const mint = Keypair.generate(); - return program.methods.initMint({ - decimals: args.decimals, - mintAuthority: args.mintAuthority, - freezeAuthority: args.freezeAuthority, - permanentDelegate: args.permanentDelegate, - transferHookAuthority: args.mintAuthority, - mode: modeEnum, - threshold: args.threshold, - name: args.name, - symbol: args.symbol, - uri: args.uri, - }).accounts({ - mint: mint.publicKey, - }).signers([mint]).rpc().then((signature) => ({ signature, mintAddress: mint.publicKey })) + return program.methods + .initMint({ + decimals: args.decimals, + mintAuthority: args.mintAuthority, + freezeAuthority: args.freezeAuthority, + permanentDelegate: args.permanentDelegate, + transferHookAuthority: args.mintAuthority, + mode: modeEnum, + threshold: args.threshold, + name: args.name, + symbol: args.symbol, + uri: args.uri, + }) + .accounts({ + mint: mint.publicKey, + }) + .signers([mint]) + .rpc() + .then((signature) => ({ signature, mintAddress: mint.publicKey })); }, onSuccess: ({ signature, mintAddress }) => { - transactionToast(signature) - window.location.href = `/manage-token/${mintAddress.toString()}` + transactionToast(signature); + window.location.href = `/manage-token/${mintAddress.toString()}`; }, - onError: () => toast.error('Failed to initialize token'), - }) + onError: () => toast.error("Failed to initialize token"), + }); const attachToExistingToken = useMutation({ - mutationKey: ['abl-token', 'attach-to-existing-token', { cluster }], - mutationFn: (args: { - mint: PublicKey, - }) => { - return program.methods.attachToMint().accounts({ - mint: args.mint, - }).rpc() + mutationKey: ["abl-token", "attach-to-existing-token", { cluster }], + mutationFn: (args: { mint: PublicKey }) => { + return program.methods + .attachToMint() + .accounts({ + mint: args.mint, + }) + .rpc(); }, onSuccess: (signature) => { - transactionToast(signature) + transactionToast(signature); }, - onError: () => toast.error('Failed to initialize token'), - }) + onError: () => toast.error("Failed to initialize token"), + }); const changeMode = useMutation({ - mutationKey: ['abl-token', 'change-mode', { cluster }], - mutationFn: (args: { - mode: string, - threshold: BN, - mint: PublicKey, - }) => { - const modeEnum = args.mode === 'Allow' ? { allow: {} } : args.mode === 'Block' ? { block: {}} : { mixed: {}} - return program.methods.changeMode({ - mode: modeEnum, - threshold: args.threshold, - }).accounts({ - mint: args.mint, - }).rpc() + mutationKey: ["abl-token", "change-mode", { cluster }], + mutationFn: (args: { mode: string; threshold: BN; mint: PublicKey }) => { + const modeEnum = args.mode === "Allow" ? { allow: {} } : args.mode === "Block" ? { block: {} } : { mixed: {} }; + return program.methods + .changeMode({ + mode: modeEnum, + threshold: args.threshold, + }) + .accounts({ + mint: args.mint, + }) + .rpc(); }, onSuccess: (signature) => { - transactionToast(signature) + transactionToast(signature); }, - onError: () => toast.error('Failed to run program'), - }) + onError: () => toast.error("Failed to run program"), + }); const initWallet = useMutation({ - mutationKey: ['abl-token', 'change-mode', { cluster }], - mutationFn: (args: { - wallet: PublicKey, - allowed: boolean, - }) => { - return program.methods.initWallet({ - allowed: args.allowed, - }).accounts({ - wallet: args.wallet, - }).rpc() + mutationKey: ["abl-token", "change-mode", { cluster }], + mutationFn: (args: { wallet: PublicKey; allowed: boolean }) => { + return program.methods + .initWallet({ + allowed: args.allowed, + }) + .accounts({ + wallet: args.wallet, + }) + .rpc(); }, onSuccess: (signature) => { - transactionToast(signature) + transactionToast(signature); }, - onError: () => toast.error('Failed to run program'), - }) + onError: () => toast.error("Failed to run program"), + }); const processBatchWallets = useMutation({ - mutationKey: ['abl-token', 'process-batch-wallets', { cluster }], - mutationFn: async (args: { - wallets: {wallet: PublicKey, mode: "allow" | "block" | "remove"}[], - }) => { - const instructions = await Promise.all(args.wallets.map((wallet) => { - if (wallet.mode === "remove") { - const [abWalletPda] = PublicKey.findProgramAddressSync( - [ - Buffer.from('ab_wallet'), - wallet.wallet.toBuffer(), - ], - program.programId - ); - return program.methods.removeWallet().accounts({ - abWallet: abWalletPda, - }).instruction() - } - return program.methods.initWallet({ - allowed: wallet.mode === "allow", - }).accounts({ - wallet: wallet.wallet, - }).instruction() - })); - + mutationKey: ["abl-token", "process-batch-wallets", { cluster }], + mutationFn: async (args: { wallets: { wallet: PublicKey; mode: "allow" | "block" | "remove" }[] }) => { + const instructions = await Promise.all( + args.wallets.map((wallet) => { + if (wallet.mode === "remove") { + const [abWalletPda] = PublicKey.findProgramAddressSync( + [Buffer.from("ab_wallet"), wallet.wallet.toBuffer()], + program.programId, + ); + return program.methods + .removeWallet() + .accounts({ + abWallet: abWalletPda, + }) + .instruction(); + } + return program.methods + .initWallet({ + allowed: wallet.mode === "allow", + }) + .accounts({ + wallet: wallet.wallet, + }) + .instruction(); + }), + ); + const transaction = new Transaction(); transaction.add(...instructions); transaction.feePayer = provider.wallet.publicKey; transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash; //transaction.sign(provider.wallet); - const signedTx = await provider.wallet.signTransaction(transaction); + const signedTx = await provider.wallet.signTransaction(transaction); return connection.sendRawTransaction(signedTx.serialize()); - }, onSuccess: (signature) => { - transactionToast(signature) + transactionToast(signature); }, - onError: () => toast.error('Failed to run program'), - }) - + onError: () => toast.error("Failed to run program"), + }); const removeWallet = useMutation({ - mutationKey: ['abl-token', 'change-mode', { cluster }], - mutationFn: (args: { - wallet: PublicKey, - }) => { + mutationKey: ["abl-token", "change-mode", { cluster }], + mutationFn: (args: { wallet: PublicKey }) => { const [abWalletPda] = PublicKey.findProgramAddressSync( - [ - Buffer.from('ab_wallet'), - args.wallet.toBuffer(), - ], - program.programId + [Buffer.from("ab_wallet"), args.wallet.toBuffer()], + program.programId, ); - return program.methods.removeWallet().accounts({ - abWallet: abWalletPda, - }).rpc() + return program.methods + .removeWallet() + .accounts({ + abWallet: abWalletPda, + }) + .rpc(); }, onSuccess: (signature) => { - transactionToast(signature) + transactionToast(signature); }, - onError: () => toast.error('Failed to run program'), - }) - + onError: () => toast.error("Failed to run program"), + }); const initConfig = useMutation({ - mutationKey: ['abl-token', 'init-config', { cluster }], + mutationKey: ["abl-token", "init-config", { cluster }], mutationFn: () => { - return program.methods.initConfig().rpc() + return program.methods.initConfig().rpc(); }, - }) + }); const getConfig = useQuery({ - queryKey: ['get-config', { cluster }], + queryKey: ["get-config", { cluster }], queryFn: () => { - const [configPda] = PublicKey.findProgramAddressSync( - [Buffer.from('config')], - program.programId - ); - return program.account.config.fetch(configPda) + const [configPda] = PublicKey.findProgramAddressSync([Buffer.from("config")], program.programId); + return program.account.config.fetch(configPda); }, - }) - + }); + const getAbWallets = useQuery({ - queryKey: ['get-ab-wallets', { cluster }], + queryKey: ["get-ab-wallets", { cluster }], queryFn: () => { - return program.account.abWallet.all() + return program.account.abWallet.all(); }, - }) - + }); - -/* + /* const getBalance = useQuery({ queryKey: ['get-balance', { cluster }], queryFn: () => { @@ -293,35 +284,39 @@ export function useAblTokenProgram() { })*/ const mintTo = useMutation({ - mutationKey: ['abl-token', 'mint-to', { cluster }], - mutationFn: async (args: { - mint: PublicKey, - amount: BN, - recipient: PublicKey, - }) => { - const mintInfo = await getMint( - connection, + mutationKey: ["abl-token", "mint-to", { cluster }], + mutationFn: async (args: { mint: PublicKey; amount: BN; recipient: PublicKey }) => { + const mintInfo = await getMint(connection, args.mint, "confirmed", TOKEN_2022_PROGRAM_ID); + const ata = getAssociatedTokenAddressSync(args.mint, args.recipient, true, TOKEN_2022_PROGRAM_ID); + + const ix = createAssociatedTokenAccountIdempotentInstruction( + provider.publicKey, + ata, + args.recipient, args.mint, - "confirmed", TOKEN_2022_PROGRAM_ID, ); - const ata = getAssociatedTokenAddressSync(args.mint, args.recipient, true, TOKEN_2022_PROGRAM_ID); - - const ix = createAssociatedTokenAccountIdempotentInstruction(provider.publicKey, ata, args.recipient, args.mint, TOKEN_2022_PROGRAM_ID); - const ix2 = createMintToCheckedInstruction(args.mint, ata, provider.publicKey, args.amount.toNumber(), mintInfo.decimals, undefined, TOKEN_2022_PROGRAM_ID); + const ix2 = createMintToCheckedInstruction( + args.mint, + ata, + provider.publicKey, + args.amount.toNumber(), + mintInfo.decimals, + undefined, + TOKEN_2022_PROGRAM_ID, + ); const tx = new Transaction(); tx.add(ix, ix2); tx.feePayer = provider.wallet.publicKey; tx.recentBlockhash = (await connection.getLatestBlockhash()).blockhash; - const signedTx = await provider.wallet.signTransaction(tx); - return connection.sendRawTransaction(signedTx.serialize()) + const signedTx = await provider.wallet.signTransaction(tx); + return connection.sendRawTransaction(signedTx.serialize()); }, onSuccess: (signature) => { - transactionToast(signature) + transactionToast(signature); }, - onError: () => toast.error('Failed to run program'), - }) - + onError: () => toast.error("Failed to run program"), + }); return { program, @@ -337,6 +332,5 @@ export function useAblTokenProgram() { processBatchWallets, mintTo, attachToExistingToken, - } + }; } - diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-feature.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-feature.tsx index f49c2f906..201a66a28 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-feature.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-feature.tsx @@ -1,16 +1,16 @@ -'use client' +"use client"; -import { useWallet } from '@solana/wallet-adapter-react' -import { ExplorerLink } from '../cluster/cluster-ui' -import { WalletButton } from '../solana/solana-provider' -import { useAblTokenProgram } from './abl-token-data-access' -import { AblTokenCreate, AblTokenProgram } from './abl-token-ui' -import { AppHero } from '../app-hero' -import { ellipsify } from '@/lib/utils' +import { useWallet } from "@solana/wallet-adapter-react"; +import { ellipsify } from "@/lib/utils"; +import { AppHero } from "../app-hero"; +import { ExplorerLink } from "../cluster/cluster-ui"; +import { WalletButton } from "../solana/solana-provider"; +import { useAblTokenProgram } from "./abl-token-data-access"; +import { AblTokenCreate, AblTokenProgram } from "./abl-token-ui"; export default function AblTokenFeature() { - const { publicKey } = useWallet() - const { programId } = useAblTokenProgram() + const { publicKey } = useWallet(); + const { programId } = useAblTokenProgram(); return publicKey ? (
@@ -30,5 +30,5 @@ export default function AblTokenFeature() {
- ) + ); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-manage-token-detail.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-manage-token-detail.tsx index 22e811a7d..051b98773 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-manage-token-detail.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-manage-token-detail.tsx @@ -1,13 +1,13 @@ -'use client' +"use client"; -import { useWallet } from '@solana/wallet-adapter-react' -import { WalletButton } from '../solana/solana-provider' -import { useParams } from 'next/navigation' -import React from 'react' -import { useAblTokenProgram, useGetToken } from './abl-token-data-access' -import { PublicKey } from '@solana/web3.js' -import { BN } from '@anchor-lang/core' -import { Button } from '@/components/ui/button' +import { BN } from "@anchor-lang/core"; +import { useWallet } from "@solana/wallet-adapter-react"; +import { PublicKey } from "@solana/web3.js"; +import { useParams } from "next/navigation"; +import React from "react"; +import { Button } from "@/components/ui/button"; +import { WalletButton } from "../solana/solana-provider"; +import { useAblTokenProgram, useGetToken } from "./abl-token-data-access"; interface TokenInfo { address: string; @@ -27,7 +27,7 @@ interface TokenInfo { } function TokenInfo({ tokenAddress }: { tokenAddress: string }) { - const { attachToExistingToken } = useAblTokenProgram() + const { attachToExistingToken } = useAblTokenProgram(); const tokenInfo = useGetToken(new PublicKey(tokenAddress)); return (
@@ -43,16 +43,25 @@ function TokenInfo({ tokenAddress }: { tokenAddress: string }) {
Mint Authority: {tokenInfo.data?.mintAuthority?.toString()}
Freeze Authority: {tokenInfo.data?.freezeAuthority?.toString()}
Permanent Delegate: {tokenInfo.data?.permanentDelegate?.toString()}
-
+

ABL Token

Mode: {tokenInfo.data?.mode}
Threshold: {tokenInfo.data?.threshold?.toString()}
- {tokenInfo.data?.isTransferHookEnabled ? (tokenInfo.data?.isTransferHookSet ? ( -
TxHook: Enabled and Set ✅
+ {tokenInfo.data?.isTransferHookEnabled ? ( + tokenInfo.data?.isTransferHookSet ? ( +
TxHook: Enabled and Set ✅
+ ) : ( +
+ TxHook: Enabled.{" "} + +
+ ) ) : ( -
TxHook: Enabled.
- )) : (
TxHook: Not enabled ❌
)}
@@ -61,15 +70,15 @@ function TokenInfo({ tokenAddress }: { tokenAddress: string }) {

No token information available.

)}
- ) + ); } function TokenManagement({ tokenInfo }: { tokenInfo: TokenInfo }) { - const { publicKey } = useWallet() - const { changeMode, mintTo } = useAblTokenProgram() - const [mode, setMode] = React.useState<'Allow' | 'Block' | 'Mixed'>(tokenInfo.mode as 'Allow' | 'Block' | 'Mixed') - const [threshold, setThreshold] = React.useState(tokenInfo.threshold ?? undefined) - const [destinationWallet, setDestinationWallet] = React.useState('') + const { publicKey } = useWallet(); + const { changeMode, mintTo } = useAblTokenProgram(); + const [mode, setMode] = React.useState<"Allow" | "Block" | "Mixed">(tokenInfo.mode as "Allow" | "Block" | "Mixed"); + const [threshold, setThreshold] = React.useState(tokenInfo.threshold ?? undefined); + const [destinationWallet, setDestinationWallet] = React.useState(""); const handleApplyChanges = async () => { if (!publicKey || !tokenInfo) return; @@ -81,11 +90,11 @@ function TokenManagement({ tokenInfo }: { tokenInfo: TokenInfo }) { mint: new PublicKey(tokenInfo.address), }); } catch (err) { - console.error('Failed to apply changes:', err); + console.error("Failed to apply changes:", err); } }; - const [mintAmount, setMintAmount] = React.useState('0') + const [mintAmount, setMintAmount] = React.useState("0"); const handleMint = async () => { if (!publicKey || !tokenInfo) return; @@ -96,9 +105,9 @@ function TokenManagement({ tokenInfo }: { tokenInfo: TokenInfo }) { amount: new BN(mintAmount), recipient: publicKey, }); - console.log('Minted successfully'); + console.log("Minted successfully"); } catch (err) { - console.error('Failed to mint tokens:', err); + console.error("Failed to mint tokens:", err); } }; @@ -109,56 +118,64 @@ function TokenManagement({ tokenInfo }: { tokenInfo: TokenInfo }) {
{tokenInfo.isTransferHookSet && (
- +

Mode

- {mode === 'Mixed' && ( -
- - setThreshold(e.target.value)} - min="0" - /> -
+ {mode === "Mixed" && ( +
+ + setThreshold(e.target.value)} + min="0" + /> +
)}
-
-
)}
@@ -167,12 +184,15 @@ function TokenManagement({ tokenInfo }: { tokenInfo: TokenInfo }) {

Mint New Tokens

- + setDestinationWallet(e.target.value)} + onChange={(e) => setDestinationWallet(e.target.value)} placeholder="Enter destination wallet address" />
@@ -181,25 +201,23 @@ function TokenManagement({ tokenInfo }: { tokenInfo: TokenInfo }) { type="number" className="w-full p-2 border rounded" value={mintAmount} - onChange={e => setMintAmount(e.target.value)} + onChange={(e) => setMintAmount(e.target.value)} min="0" placeholder="Amount to mint" /> - +
- ) + ); } export default function ManageTokenDetail() { - const { publicKey } = useWallet() - const params = useParams() - const tokenAddress = params?.address as string + const { publicKey } = useWallet(); + const params = useParams(); + const tokenAddress = params?.address as string; const tokenQuery = useGetToken(new PublicKey(tokenAddress)); const tokenInfo = React.useMemo(() => { @@ -218,7 +236,7 @@ export default function ManageTokenDetail() { - ) + ); } return ( @@ -230,10 +248,9 @@ export default function ManageTokenDetail() { ) : ( <> - {tokenInfo && } - + {tokenInfo && } )} - ) + ); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-manage-token-input.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-manage-token-input.tsx index 1f5a1695c..dd046f99a 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-manage-token-input.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-manage-token-input.tsx @@ -1,22 +1,21 @@ -'use client' +"use client"; -import { useWallet } from '@solana/wallet-adapter-react' -import { WalletButton } from '../solana/solana-provider' - -import { redirect } from 'next/navigation' -import React from 'react' -import { Button } from '@/components/ui/button' +import { useWallet } from "@solana/wallet-adapter-react"; +import { redirect } from "next/navigation"; +import React from "react"; +import { Button } from "@/components/ui/button"; +import { WalletButton } from "../solana/solana-provider"; export default function ManageTokenInput() { - const { publicKey } = useWallet() - const [tokenAddress, setTokenAddress] = React.useState('') + const { publicKey } = useWallet(); + const [tokenAddress, setTokenAddress] = React.useState(""); const handleSubmit = (e: React.FormEvent) => { - e.preventDefault() + e.preventDefault(); if (tokenAddress) { - redirect(`/manage-token/${tokenAddress.toString()}`) + redirect(`/manage-token/${tokenAddress.toString()}`); } - } + }; if (!publicKey) { return ( @@ -25,7 +24,7 @@ export default function ManageTokenInput() { - ) + ); } return ( @@ -39,17 +38,15 @@ export default function ManageTokenInput() { type="text" className="w-full p-2 border rounded" value={tokenAddress} - onChange={e => setTokenAddress(e.target.value)} + onChange={(e) => setTokenAddress(e.target.value)} placeholder="Enter token address" required /> - + - ) + ); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-manage-token.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-manage-token.tsx index feab86b70..8ada87843 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-manage-token.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-manage-token.tsx @@ -1,11 +1,11 @@ -'use client' +"use client"; -import { useWallet } from '@solana/wallet-adapter-react' -import { WalletButton } from '../solana/solana-provider' -import { AppHero } from '../app-hero' -import ManageTokenInput from './abl-token-manage-token-input' +import { useWallet } from "@solana/wallet-adapter-react"; +import { AppHero } from "../app-hero"; +import { WalletButton } from "../solana/solana-provider"; +import ManageTokenInput from "./abl-token-manage-token-input"; export default function AblTokenFeature() { - const { publicKey } = useWallet() + const { publicKey } = useWallet(); return publicKey ? (
@@ -21,5 +21,5 @@ export default function AblTokenFeature() {
- ) + ); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-new-token.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-new-token.tsx index ed0bb438e..9a489a1d7 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-new-token.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-new-token.tsx @@ -1,16 +1,16 @@ -'use client' +"use client"; -import { useWallet } from '@solana/wallet-adapter-react' -import { ExplorerLink } from '../cluster/cluster-ui' -import { WalletButton } from '../solana/solana-provider' -import { useAblTokenProgram } from './abl-token-data-access' -import { AblTokenCreate } from './abl-token-ui' -import { AppHero } from '../app-hero' -import { ellipsify } from '@/lib/utils' +import { useWallet } from "@solana/wallet-adapter-react"; +import { ellipsify } from "@/lib/utils"; +import { AppHero } from "../app-hero"; +import { ExplorerLink } from "../cluster/cluster-ui"; +import { WalletButton } from "../solana/solana-provider"; +import { useAblTokenProgram } from "./abl-token-data-access"; +import { AblTokenCreate } from "./abl-token-ui"; export default function AblTokenFeature() { - const { publicKey } = useWallet() - const { programId } = useAblTokenProgram() + const { publicKey } = useWallet(); + const { programId } = useAblTokenProgram(); return publicKey ? (
@@ -29,5 +29,5 @@ export default function AblTokenFeature() {
- ) + ); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-ui.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-ui.tsx index 6c0b7ff7b..8293a3892 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-ui.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/abl-token/abl-token-ui.tsx @@ -1,34 +1,33 @@ -'use client' +"use client"; -import { PublicKey } from '@solana/web3.js' -import { useAblTokenProgram } from './abl-token-data-access' -import { Button } from '@/components/ui/button' -import { BN } from '@anchor-lang/core' -import React from 'react' -import { useWallet } from '@solana/wallet-adapter-react' +import { BN } from "@anchor-lang/core"; +import { useWallet } from "@solana/wallet-adapter-react"; +import { PublicKey } from "@solana/web3.js"; +import React from "react"; +import { Button } from "@/components/ui/button"; +import { useAblTokenProgram } from "./abl-token-data-access"; export function AblTokenCreate() { - - const { publicKey } = useWallet() - const { initToken } = useAblTokenProgram() - const [mode, setMode] = React.useState<'allow' | 'block' | 'threshold'>('allow') - const [threshold, setThreshold] = React.useState('100000') + const { publicKey } = useWallet(); + const { initToken } = useAblTokenProgram(); + const [mode, setMode] = React.useState<"allow" | "block" | "threshold">("allow"); + const [threshold, setThreshold] = React.useState("100000"); const [formData, setFormData] = React.useState({ - mintAuthority: publicKey ? publicKey.toString() : '', - freezeAuthority: publicKey ? publicKey.toString() : '', - permanentDelegate: publicKey ? publicKey.toString() : '', - transferHookAuthority: publicKey ? publicKey.toString() : '', - name: '', - symbol: '', - uri: '', - decimals: '6' - }) + mintAuthority: publicKey ? publicKey.toString() : "", + freezeAuthority: publicKey ? publicKey.toString() : "", + permanentDelegate: publicKey ? publicKey.toString() : "", + transferHookAuthority: publicKey ? publicKey.toString() : "", + name: "", + symbol: "", + uri: "", + decimals: "6", + }); const handleSubmit = (e: React.FormEvent) => { - e.preventDefault() + e.preventDefault(); try { initToken.mutateAsync({ - decimals: parseInt(formData.decimals), + decimals: parseInt(formData.decimals, 10), mintAuthority: new PublicKey(formData.mintAuthority), freezeAuthority: new PublicKey(formData.freezeAuthority), permanentDelegate: new PublicKey(formData.permanentDelegate), @@ -37,12 +36,12 @@ export function AblTokenCreate() { threshold: new BN(threshold), name: formData.name, symbol: formData.symbol, - uri: formData.uri - }) + uri: formData.uri, + }); } catch (err) { - console.error('Invalid form data:', err) + console.error("Invalid form data:", err); } - } + }; return (
@@ -53,7 +52,7 @@ export function AblTokenCreate() { type="text" className="w-full p-2 border rounded" value={formData.mintAuthority} - onChange={e => setFormData({...formData, mintAuthority: e.target.value})} + onChange={(e) => setFormData({ ...formData, mintAuthority: e.target.value })} required /> @@ -64,7 +63,7 @@ export function AblTokenCreate() { type="text" className="w-full p-2 border rounded" value={formData.freezeAuthority} - onChange={e => setFormData({...formData, freezeAuthority: e.target.value})} + onChange={(e) => setFormData({ ...formData, freezeAuthority: e.target.value })} required /> @@ -75,7 +74,7 @@ export function AblTokenCreate() { type="text" className="w-full p-2 border rounded" value={formData.permanentDelegate} - onChange={e => setFormData({...formData, permanentDelegate: e.target.value})} + onChange={(e) => setFormData({ ...formData, permanentDelegate: e.target.value })} required /> @@ -86,7 +85,12 @@ export function AblTokenCreate() { type="text" className="w-full p-2 border rounded" value={formData.transferHookAuthority} - onChange={e => setFormData({...formData, transferHookAuthority: e.target.value})} + onChange={(e) => + setFormData({ + ...formData, + transferHookAuthority: e.target.value, + }) + } required /> @@ -97,7 +101,7 @@ export function AblTokenCreate() { type="text" className="w-full p-2 border rounded" value={formData.name} - onChange={e => setFormData({...formData, name: e.target.value})} + onChange={(e) => setFormData({ ...formData, name: e.target.value })} required /> @@ -108,7 +112,7 @@ export function AblTokenCreate() { type="text" className="w-full p-2 border rounded" value={formData.symbol} - onChange={e => setFormData({...formData, symbol: e.target.value})} + onChange={(e) => setFormData({ ...formData, symbol: e.target.value })} required /> @@ -119,7 +123,7 @@ export function AblTokenCreate() { type="text" className="w-full p-2 border rounded" value={formData.uri} - onChange={e => setFormData({...formData, uri: e.target.value})} + onChange={(e) => setFormData({ ...formData, uri: e.target.value })} required /> @@ -130,7 +134,7 @@ export function AblTokenCreate() { type="number" className="w-full p-2 border rounded" value={formData.decimals} - onChange={e => setFormData({...formData, decimals: e.target.value})} + onChange={(e) => setFormData({ ...formData, decimals: e.target.value })} required min="0" max="9" @@ -138,43 +142,29 @@ export function AblTokenCreate() {
- +

Mode*

- {mode === 'threshold' && ( + {mode === "threshold" && ( @@ -182,35 +172,35 @@ export function AblTokenCreate() {
- ) + ); } export function AblTokenProgram() { - const { getProgramAccount } = useAblTokenProgram() + const { getProgramAccount } = useAblTokenProgram(); if (getProgramAccount.isLoading) { - return + return ; } if (!getProgramAccount.data?.value) { return (
Program account not found. Make sure you have deployed the program and are on the correct cluster.
- ) + ); } return ( -
+
{JSON.stringify(getProgramAccount.data.value, null, 2)}
- ) + ); } interface WalletEntry { address: string; - mode: 'allow' | 'block'; + mode: "allow" | "block"; } export function AblTokenWalletTable() { @@ -224,24 +214,24 @@ export function AblTokenWalletTable() { e.preventDefault(); const file = e.dataTransfer.files[0]; - if (file && file.type === 'text/csv') { + if (file && file.type === "text/csv") { const text = await file.text(); - const rows = text.split('\n'); - + const rows = text.split("\n"); + const parsed: WalletEntry[] = rows - .filter(row => row.trim()) // Skip empty rows - .map(row => { - const [address, mode] = row.split(',').map(field => field.trim()); + .filter((row) => row.trim()) // Skip empty rows + .map((row) => { + const [address, mode] = row.split(",").map((field) => field.trim()); return { address, - mode: mode.toLowerCase() as 'allow' | 'block' + mode: mode.toLowerCase() as "allow" | "block", }; }) - .filter(entry => { + .filter((entry) => { // Basic validation try { new PublicKey(entry.address); - return ['allow', 'block'].includes(entry.mode); + return ["allow", "block"].includes(entry.mode); } catch { return false; } @@ -253,13 +243,14 @@ export function AblTokenWalletTable() { return (
-
Drop CSV file here (address,mode) -
+ {wallets.length > 0 && (
@@ -271,11 +262,11 @@ export function AblTokenWalletTable() { - {wallets.map((wallet, index) => ( - + {wallets.map((wallet) => ( + {wallet.address} - + {wallet.mode} diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/account/account-data-access.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/account/account-data-access.tsx index 2d67047b8..bec06323a 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/account/account-data-access.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/account/account-data-access.tsx @@ -1,77 +1,101 @@ -'use client' +"use client"; -import { createAssociatedTokenAccountIdempotentInstruction, createTransferCheckedInstruction, getAssociatedTokenAddressSync, getExtraAccountMetaAddress, getMint, getTransferHook, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from '@solana/spl-token' -import { useConnection, useWallet } from '@solana/wallet-adapter-react' +import { Buffer } from "node:buffer"; import { - Connection, + createAssociatedTokenAccountIdempotentInstruction, + createTransferCheckedInstruction, + getAssociatedTokenAddressSync, + getExtraAccountMetaAddress, + getMint, + getTransferHook, + TOKEN_2022_PROGRAM_ID, + TOKEN_PROGRAM_ID, +} from "@solana/spl-token"; +import { useConnection, useWallet } from "@solana/wallet-adapter-react"; +import { + type Connection, LAMPORTS_PER_SOL, PublicKey, SystemProgram, Transaction, TransactionMessage, - TransactionSignature, + type TransactionSignature, VersionedTransaction, -} from '@solana/web3.js' -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { useTransactionErrorToast, useTransactionToast } from '../use-transaction-toast' -import { useAnchorProvider } from '../solana/solana-provider' -import { Buffer } from "buffer" +} from "@solana/web3.js"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useAnchorProvider } from "../solana/solana-provider"; +import { useTransactionErrorToast, useTransactionToast } from "../use-transaction-toast"; export function useGetBalance({ address }: { address: PublicKey }) { - const { connection } = useConnection() + const { connection } = useConnection(); return useQuery({ - queryKey: ['get-balance', { endpoint: connection.rpcEndpoint, address }], + queryKey: ["get-balance", { endpoint: connection.rpcEndpoint, address }], queryFn: () => connection.getBalance(address), - }) + }); } export function useGetSignatures({ address }: { address: PublicKey }) { - const { connection } = useConnection() + const { connection } = useConnection(); return useQuery({ - queryKey: ['get-signatures', { endpoint: connection.rpcEndpoint, address }], + queryKey: ["get-signatures", { endpoint: connection.rpcEndpoint, address }], queryFn: () => connection.getSignaturesForAddress(address), - }) + }); } export function useSendTokens() { - const { connection } = useConnection() - const { publicKey } = useWallet() - const transactionToast = useTransactionToast() - const provider = useAnchorProvider() - const transactionErrorToast = useTransactionErrorToast() + const { connection } = useConnection(); + const { publicKey } = useWallet(); + const transactionToast = useTransactionToast(); + const provider = useAnchorProvider(); + const transactionErrorToast = useTransactionErrorToast(); return useMutation({ - mutationFn: async (args: { - mint: PublicKey, - destination: PublicKey, - amount: number, - }) => { - if (!publicKey) throw new Error('No public key found'); + mutationFn: async (args: { mint: PublicKey; destination: PublicKey; amount: number }) => { + if (!publicKey) throw new Error("No public key found"); const { mint, destination, amount } = args; - const mintInfo = await getMint(connection, mint, 'confirmed', TOKEN_2022_PROGRAM_ID); + const mintInfo = await getMint(connection, mint, "confirmed", TOKEN_2022_PROGRAM_ID); const ataDestination = getAssociatedTokenAddressSync(mint, destination, true, TOKEN_2022_PROGRAM_ID); const ataSource = getAssociatedTokenAddressSync(mint, publicKey, true, TOKEN_2022_PROGRAM_ID); - const ix = createAssociatedTokenAccountIdempotentInstruction(publicKey, ataDestination, destination, mint, TOKEN_2022_PROGRAM_ID); + const ix = createAssociatedTokenAccountIdempotentInstruction( + publicKey, + ataDestination, + destination, + mint, + TOKEN_2022_PROGRAM_ID, + ); const bi = BigInt(amount); const decimals = mintInfo.decimals; - const ix3 = await createTransferCheckedInstruction(ataSource, mint, ataDestination, publicKey, bi, decimals, undefined, TOKEN_2022_PROGRAM_ID); + const ix3 = await createTransferCheckedInstruction( + ataSource, + mint, + ataDestination, + publicKey, + bi, + decimals, + undefined, + TOKEN_2022_PROGRAM_ID, + ); const transferHook = getTransferHook(mintInfo); - if (!transferHook) throw new Error('bad token'); + if (!transferHook) throw new Error("bad token"); const extraMetas = getExtraAccountMetaAddress(mint, transferHook.programId); - const seeds = [Buffer.from('ab_wallet'), destination.toBuffer()]; + const seeds = [Buffer.from("ab_wallet"), destination.toBuffer()]; const abWallet = PublicKey.findProgramAddressSync(seeds, transferHook.programId)[0]; ix3.keys.push({ pubkey: abWallet, isSigner: false, isWritable: false }); - ix3.keys.push({ pubkey: transferHook.programId, isSigner: false, isWritable: false }); + ix3.keys.push({ + pubkey: transferHook.programId, + isSigner: false, + isWritable: false, + }); ix3.keys.push({ pubkey: extraMetas, isSigner: false, isWritable: false }); - - const validateStateAccount = await connection.getAccountInfo(extraMetas, 'confirmed'); - if (!validateStateAccount) throw new Error('validate-state-account not found'); + + const validateStateAccount = await connection.getAccountInfo(extraMetas, "confirmed"); + if (!validateStateAccount) throw new Error("validate-state-account not found"); const transaction = new Transaction(); transaction.add(ix, ix3); @@ -83,17 +107,19 @@ export function useSendTokens() { return connection.sendRawTransaction(signedTx.serialize()); }, onSuccess: (signature) => { - transactionToast(signature) + transactionToast(signature); + }, + onError: (error) => { + transactionErrorToast(error, connection); }, - onError: (error) => { transactionErrorToast(error, connection) }, - }) + }); } export function useGetTokenAccounts({ address }: { address: PublicKey }) { - const { connection } = useConnection() + const { connection } = useConnection(); return useQuery({ - queryKey: ['get-token-accounts', { endpoint: connection.rpcEndpoint, address }], + queryKey: ["get-token-accounts", { endpoint: connection.rpcEndpoint, address }], queryFn: async () => { const [tokenAccounts, token2022Accounts] = await Promise.all([ connection.getParsedTokenAccountsByOwner(address, { @@ -102,96 +128,96 @@ export function useGetTokenAccounts({ address }: { address: PublicKey }) { connection.getParsedTokenAccountsByOwner(address, { programId: TOKEN_2022_PROGRAM_ID, }), - ]) - return [...tokenAccounts.value, ...token2022Accounts.value] + ]); + return [...tokenAccounts.value, ...token2022Accounts.value]; }, - }) + }); } export function useTransferSol({ address }: { address: PublicKey }) { - const { connection } = useConnection() + const { connection } = useConnection(); // const transactionToast = useTransactionToast() - const wallet = useWallet() - const client = useQueryClient() + const wallet = useWallet(); + const client = useQueryClient(); return useMutation({ - mutationKey: ['transfer-sol', { endpoint: connection.rpcEndpoint, address }], + mutationKey: ["transfer-sol", { endpoint: connection.rpcEndpoint, address }], mutationFn: async (input: { destination: PublicKey; amount: number }) => { - let signature: TransactionSignature = '' + let signature: TransactionSignature = ""; try { const { transaction, latestBlockhash } = await createTransaction({ publicKey: address, destination: input.destination, amount: input.amount, connection, - }) + }); // Send transaction and await for signature - signature = await wallet.sendTransaction(transaction, connection) + signature = await wallet.sendTransaction(transaction, connection); // Send transaction and await for signature - await connection.confirmTransaction({ signature, ...latestBlockhash }, 'confirmed') + await connection.confirmTransaction({ signature, ...latestBlockhash }, "confirmed"); - console.log(signature) - return signature + console.log(signature); + return signature; } catch (error: unknown) { - console.log('error', `Transaction failed! ${error}`, signature) + console.log("error", `Transaction failed! ${error}`, signature); - return + return; } }, onSuccess: (signature) => { if (signature) { // TODO: Add back Toast // transactionToast(signature) - console.log('Transaction sent', signature) + console.log("Transaction sent", signature); } return Promise.all([ client.invalidateQueries({ - queryKey: ['get-balance', { endpoint: connection.rpcEndpoint, address }], + queryKey: ["get-balance", { endpoint: connection.rpcEndpoint, address }], }), client.invalidateQueries({ - queryKey: ['get-signatures', { endpoint: connection.rpcEndpoint, address }], + queryKey: ["get-signatures", { endpoint: connection.rpcEndpoint, address }], }), - ]) + ]); }, onError: (error) => { // TODO: Add Toast - console.error(`Transaction failed! ${error}`) + console.error(`Transaction failed! ${error}`); }, - }) + }); } export function useRequestAirdrop({ address }: { address: PublicKey }) { - const { connection } = useConnection() + const { connection } = useConnection(); // const transactionToast = useTransactionToast() - const client = useQueryClient() + const client = useQueryClient(); return useMutation({ - mutationKey: ['airdrop', { endpoint: connection.rpcEndpoint, address }], + mutationKey: ["airdrop", { endpoint: connection.rpcEndpoint, address }], mutationFn: async (amount: number = 1) => { const [latestBlockhash, signature] = await Promise.all([ connection.getLatestBlockhash(), connection.requestAirdrop(address, amount * LAMPORTS_PER_SOL), - ]) + ]); - await connection.confirmTransaction({ signature, ...latestBlockhash }, 'confirmed') - return signature + await connection.confirmTransaction({ signature, ...latestBlockhash }, "confirmed"); + return signature; }, onSuccess: (signature) => { // TODO: Add back Toast // transactionToast(signature) - console.log('Airdrop sent', signature) + console.log("Airdrop sent", signature); return Promise.all([ client.invalidateQueries({ - queryKey: ['get-balance', { endpoint: connection.rpcEndpoint, address }], + queryKey: ["get-balance", { endpoint: connection.rpcEndpoint, address }], }), client.invalidateQueries({ - queryKey: ['get-signatures', { endpoint: connection.rpcEndpoint, address }], + queryKey: ["get-signatures", { endpoint: connection.rpcEndpoint, address }], }), - ]) + ]); }, - }) + }); } async function createTransaction({ @@ -200,16 +226,16 @@ async function createTransaction({ amount, connection, }: { - publicKey: PublicKey - destination: PublicKey - amount: number - connection: Connection + publicKey: PublicKey; + destination: PublicKey; + amount: number; + connection: Connection; }): Promise<{ - transaction: VersionedTransaction - latestBlockhash: { blockhash: string; lastValidBlockHeight: number } + transaction: VersionedTransaction; + latestBlockhash: { blockhash: string; lastValidBlockHeight: number }; }> { // Get the latest blockhash to use in our transaction - const latestBlockhash = await connection.getLatestBlockhash() + const latestBlockhash = await connection.getLatestBlockhash(); // Create instructions to send, in this case a simple transfer const instructions = [ @@ -218,20 +244,20 @@ async function createTransaction({ toPubkey: destination, lamports: amount * LAMPORTS_PER_SOL, }), - ] + ]; // Create a new TransactionMessage with version and compile it to legacy const messageLegacy = new TransactionMessage({ payerKey: publicKey, recentBlockhash: latestBlockhash.blockhash, instructions, - }).compileToLegacyMessage() + }).compileToLegacyMessage(); // Create a new VersionedTransaction which supports legacy and v0 - const transaction = new VersionedTransaction(messageLegacy) + const transaction = new VersionedTransaction(messageLegacy); return { transaction, latestBlockhash, - } + }; } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/account/account-detail-feature.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/account/account-detail-feature.tsx index 4aa2efc7b..4e186d8cf 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/account/account-detail-feature.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/account/account-detail-feature.tsx @@ -1,27 +1,27 @@ -'use client' +"use client"; -import { PublicKey } from '@solana/web3.js' -import { useMemo } from 'react' -import { useParams } from 'next/navigation' -import { ExplorerLink } from '../cluster/cluster-ui' -import { AccountBalance, AccountButtons, AccountTokens, AccountTransactions } from './account-ui' -import { AppHero } from '../app-hero' -import { ellipsify } from '@/lib/utils' +import { PublicKey } from "@solana/web3.js"; +import { useParams } from "next/navigation"; +import { useMemo } from "react"; +import { ellipsify } from "@/lib/utils"; +import { AppHero } from "../app-hero"; +import { ExplorerLink } from "../cluster/cluster-ui"; +import { AccountBalance, AccountButtons, AccountTokens, AccountTransactions } from "./account-ui"; export default function AccountDetailFeature() { - const params = useParams() + const params = useParams(); const address = useMemo(() => { if (!params.address) { - return + return; } try { - return new PublicKey(params.address) + return new PublicKey(params.address); } catch (e) { - console.log(`Invalid public key`, e) + console.log(`Invalid public key`, e); } - }, [params]) + }, [params]); if (!address) { - return
Error loading account
+ return
Error loading account
; } return ( @@ -43,5 +43,5 @@ export default function AccountDetailFeature() {
- ) + ); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/account/account-list-feature.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/account/account-list-feature.tsx index 4ccb10390..b7559c0c9 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/account/account-list-feature.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/account/account-list-feature.tsx @@ -1,15 +1,14 @@ -'use client' +"use client"; -import { useWallet } from '@solana/wallet-adapter-react' -import { WalletButton } from '../solana/solana-provider' - -import { redirect } from 'next/navigation' +import { useWallet } from "@solana/wallet-adapter-react"; +import { redirect } from "next/navigation"; +import { WalletButton } from "../solana/solana-provider"; export default function AccountListFeature() { - const { publicKey } = useWallet() + const { publicKey } = useWallet(); if (publicKey) { - return redirect(`/account/${publicKey.toString()}`) + return redirect(`/account/${publicKey.toString()}`); } return ( @@ -18,5 +17,5 @@ export default function AccountListFeature() {
- ) + ); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/account/account-ui.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/account/account-ui.tsx index 5b972960e..fa19f8dc6 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/account/account-ui.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/account/account-ui.tsx @@ -1,13 +1,19 @@ -'use client' +"use client"; -import { useWallet } from '@solana/wallet-adapter-react' -import { LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js' -import { RefreshCw } from 'lucide-react' -import { useQueryClient } from '@tanstack/react-query' -import { useMemo, useState } from 'react' - -import { useCluster } from '../cluster/cluster-data-access' -import { ExplorerLink } from '../cluster/cluster-ui' +import { useWallet } from "@solana/wallet-adapter-react"; +import { LAMPORTS_PER_SOL, PublicKey } from "@solana/web3.js"; +import { useQueryClient } from "@tanstack/react-query"; +import { RefreshCw } from "lucide-react"; +import { useMemo, useState } from "react"; +import { AppAlert } from "@/components/app-alert"; +import { AppModal } from "@/components/app-modal"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; +import { ellipsify } from "@/lib/utils"; +import { useCluster } from "../cluster/cluster-data-access"; +import { ExplorerLink } from "../cluster/cluster-ui"; import { useGetBalance, useGetSignatures, @@ -15,40 +21,33 @@ import { useRequestAirdrop, useSendTokens, useTransferSol, -} from './account-data-access' -import { ellipsify } from '@/lib/utils' -import { Button } from '@/components/ui/button' -import { AppAlert } from '@/components/app-alert' -import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table' -import { AppModal } from '@/components/app-modal' -import { Input } from '@/components/ui/input' -import { Label } from '@/components/ui/label' +} from "./account-data-access"; export function AccountBalance({ address }: { address: PublicKey }) { - const query = useGetBalance({ address }) + const query = useGetBalance({ address }); return ( -

query.refetch()}> - {query.data ? : '...'} SOL -

- ) + + ); } export function AccountChecker() { - const { publicKey } = useWallet() + const { publicKey } = useWallet(); if (!publicKey) { - return null + return null; } - return + return ; } export function AccountBalanceCheck({ address }: { address: PublicKey }) { - const { cluster } = useCluster() - const mutation = useRequestAirdrop({ address }) - const query = useGetBalance({ address }) + const { cluster } = useCluster(); + const mutation = useRequestAirdrop({ address }); + const query = useGetBalance({ address }); if (query.isLoading) { - return null + return null; } if (query.isError || !query.data) { return ( @@ -61,33 +60,33 @@ export function AccountBalanceCheck({ address }: { address: PublicKey }) { > You are connected to {cluster.name} but your account is not found on this cluster. - ) + ); } - return null + return null; } export function AccountButtons({ address }: { address: PublicKey }) { - const { cluster } = useCluster() + const { cluster } = useCluster(); return (
- {cluster.network?.includes('mainnet') ? null : } + {cluster.network?.includes("mainnet") ? null : }
- ) + ); } export function AccountTokens({ address }: { address: PublicKey }) { - const [showAll, setShowAll] = useState(false) - const query = useGetTokenAccounts({ address }) - const client = useQueryClient() - const sendTokens = useSendTokens() + const [showAll, setShowAll] = useState(false); + const query = useGetTokenAccounts({ address }); + const client = useQueryClient(); + const sendTokens = useSendTokens(); const items = useMemo(() => { - if (showAll) return query.data - return query.data?.slice(0, 5) - }, [query.data, showAll]) + if (showAll) return query.data; + return query.data?.slice(0, 5); + }, [query.data, showAll]); return (
@@ -101,10 +100,10 @@ export function AccountTokens({ address }: { address: PublicKey }) { + }} + > + Send + @@ -181,7 +184,7 @@ export function AccountTokens({ address }: { address: PublicKey }) { @@ -192,17 +195,17 @@ export function AccountTokens({ address }: { address: PublicKey }) {
)} - ) + ); } export function AccountTransactions({ address }: { address: PublicKey }) { - const query = useGetSignatures({ address }) - const [showAll, setShowAll] = useState(false) + const query = useGetSignatures({ address }); + const [showAll, setShowAll] = useState(false); const items = useMemo(() => { - if (showAll) return query.data - return query.data?.slice(0, 5) - }, [query.data, showAll]) + if (showAll) return query.data; + return query.data?.slice(0, 5); + }, [query.data, showAll]); return (
@@ -258,7 +261,7 @@ export function AccountTransactions({ address }: { address: PublicKey }) { @@ -269,11 +272,11 @@ export function AccountTransactions({ address }: { address: PublicKey }) {
)} - ) + ); } function BalanceSol({ balance }: { balance: number }) { - return {Math.round((balance / LAMPORTS_PER_SOL) * 100000) / 100000} + return {Math.round((balance / LAMPORTS_PER_SOL) * 100000) / 100000}; } function ModalReceive({ address }: { address: PublicKey }) { @@ -282,12 +285,12 @@ function ModalReceive({ address }: { address: PublicKey }) {

Receive assets by sending them to your public key:

{address.toString()} - ) + ); } function ModalAirdrop({ address }: { address: PublicKey }) { - const mutation = useRequestAirdrop({ address }) - const [amount, setAmount] = useState('2') + const mutation = useRequestAirdrop({ address }); + const [amount, setAmount] = useState("2"); return ( - ) + ); } function ModalSend({ address }: { address: PublicKey }) { - const wallet = useWallet() - const mutation = useTransferSol({ address }) - const [destination, setDestination] = useState('') - const [amount, setAmount] = useState('1') + const wallet = useWallet(); + const mutation = useTransferSol({ address }); + const [destination, setDestination] = useState(""); + const [amount, setAmount] = useState("1"); if (!address || !wallet.sendTransaction) { - return
Wallet not connected
+ return
Wallet not connected
; } return ( @@ -330,7 +333,7 @@ function ModalSend({ address }: { address: PublicKey }) { mutation.mutateAsync({ destination: new PublicKey(destination), amount: parseFloat(amount), - }) + }); }} > @@ -354,5 +357,5 @@ function ModalSend({ address }: { address: PublicKey }) { value={amount} /> - ) + ); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-alert.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-alert.tsx index 008d7aaa6..d55b71a70 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-alert.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-alert.tsx @@ -1,6 +1,6 @@ -import { AlertCircle } from 'lucide-react' -import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert' -import { ReactNode } from 'react' +import { AlertCircle } from "lucide-react"; +import type { ReactNode } from "react"; +import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; export function AppAlert({ action, children }: { action: ReactNode; children: ReactNode }) { return ( @@ -9,5 +9,5 @@ export function AppAlert({ action, children }: { action: ReactNode; children: Re {children} {action} - ) + ); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-footer.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-footer.tsx index f871f95a9..783a2b653 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-footer.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-footer.tsx @@ -1,9 +1,7 @@ -import React from 'react' - export function AppFooter() { return (
- Generated by{' '} + Generated by{" "}
- ) + ); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-header.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-header.tsx index 1a3fa9e9f..44008df65 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-header.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-header.tsx @@ -1,19 +1,19 @@ -'use client' -import { usePathname } from 'next/navigation' -import { useState } from 'react' -import Link from 'next/link' -import { Button } from '@/components/ui/button' -import { Menu, X } from 'lucide-react' -import { ThemeSelect } from '@/components/theme-select' -import { ClusterUiSelect } from './cluster/cluster-ui' -import { WalletButton } from '@/components/solana/solana-provider' +"use client"; +import { Menu, X } from "lucide-react"; +import Link from "next/link"; +import { usePathname } from "next/navigation"; +import { useState } from "react"; +import { WalletButton } from "@/components/solana/solana-provider"; +import { ThemeSelect } from "@/components/theme-select"; +import { Button } from "@/components/ui/button"; +import { ClusterUiSelect } from "./cluster/cluster-ui"; export function AppHeader({ links = [] }: { links: { label: string; path: string }[] }) { - const pathname = usePathname() - const [showMenu, setShowMenu] = useState(false) + const pathname = usePathname(); + const [showMenu, setShowMenu] = useState(false); function isActive(path: string) { - return path === '/' ? pathname === '/' : pathname.startsWith(path) + return path === "/" ? pathname === "/" : pathname.startsWith(path); } return ( @@ -28,7 +28,7 @@ export function AppHeader({ links = [] }: { links: { label: string; path: string {links.map(({ label, path }) => (
  • {label} @@ -56,7 +56,7 @@ export function AppHeader({ links = [] }: { links: { label: string; path: string {links.map(({ label, path }) => (
  • setShowMenu(false)} > @@ -75,5 +75,5 @@ export function AppHeader({ links = [] }: { links: { label: string; path: string )} - ) + ); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-hero.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-hero.tsx index 3e0b2946a..cbcc2eafa 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-hero.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-hero.tsx @@ -1,23 +1,23 @@ -import React from 'react' +import type React from "react"; export function AppHero({ children, subtitle, title, }: { - children?: React.ReactNode - subtitle?: React.ReactNode - title?: React.ReactNode + children?: React.ReactNode; + subtitle?: React.ReactNode; + title?: React.ReactNode; }) { return (
    - {typeof title === 'string' ?

    {title}

    : title} - {typeof subtitle === 'string' ?

    {subtitle}

    : subtitle} + {typeof title === "string" ?

    {title}

    : title} + {typeof subtitle === "string" ?

    {subtitle}

    : subtitle} {children}
    - ) + ); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-layout.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-layout.tsx index 194008682..f6fde56be 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-layout.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-layout.tsx @@ -1,19 +1,19 @@ -'use client' +"use client"; -import { ThemeProvider } from './theme-provider' -import { Toaster } from './ui/sonner' -import { AppHeader } from '@/components/app-header' -import React from 'react' -import { AppFooter } from '@/components/app-footer' -import { ClusterChecker } from '@/components/cluster/cluster-ui' -import { AccountChecker } from '@/components/account/account-ui' +import type React from "react"; +import { AccountChecker } from "@/components/account/account-ui"; +import { AppFooter } from "@/components/app-footer"; +import { AppHeader } from "@/components/app-header"; +import { ClusterChecker } from "@/components/cluster/cluster-ui"; +import { ThemeProvider } from "./theme-provider"; +import { Toaster } from "./ui/sonner"; export function AppLayout({ children, links, }: { - children: React.ReactNode - links: { label: string; path: string }[] + children: React.ReactNode; + links: { label: string; path: string }[]; }) { return ( @@ -29,5 +29,5 @@ export function AppLayout({ - ) + ); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-modal.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-modal.tsx index a302cd725..93ff4e474 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-modal.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-modal.tsx @@ -1,6 +1,6 @@ -import { Button } from '@/components/ui/button' -import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog' -import { ReactNode } from 'react' +import type { ReactNode } from "react"; +import { Button } from "@/components/ui/button"; +import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"; export function AppModal({ children, @@ -9,11 +9,11 @@ export function AppModal({ submitDisabled, submitLabel, }: { - children: ReactNode - title: string - submit?: () => void - submitDisabled?: boolean - submitLabel?: string + children: ReactNode; + title: string; + submit?: () => void; + submitDisabled?: boolean; + submitLabel?: string; }) { return ( @@ -28,11 +28,11 @@ export function AppModal({ {submit ? ( ) : null} - ) + ); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-providers.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-providers.tsx index a359b6541..c5a0e26da 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-providers.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/app-providers.tsx @@ -1,10 +1,10 @@ -'use client' +"use client"; -import { ThemeProvider } from '@/components/theme-provider' -import { ReactQueryProvider } from './react-query-provider' -import { ClusterProvider } from '@/components/cluster/cluster-data-access' -import { SolanaProvider } from '@/components/solana/solana-provider' -import React from 'react' +import type React from "react"; +import { ClusterProvider } from "@/components/cluster/cluster-data-access"; +import { SolanaProvider } from "@/components/solana/solana-provider"; +import { ThemeProvider } from "@/components/theme-provider"; +import { ReactQueryProvider } from "./react-query-provider"; export function AppProviders({ children }: Readonly<{ children: React.ReactNode }>) { return ( @@ -15,5 +15,5 @@ export function AppProviders({ children }: Readonly<{ children: React.ReactNode - ) + ); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/cluster/cluster-data-access.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/cluster/cluster-data-access.tsx index 5a8d772b9..359fd3616 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/cluster/cluster-data-access.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/cluster/cluster-data-access.tsx @@ -1,22 +1,22 @@ -'use client' +"use client"; -import { clusterApiUrl, Connection } from '@solana/web3.js' -import { atom, useAtomValue, useSetAtom } from 'jotai' -import { atomWithStorage } from 'jotai/utils' -import { createContext, ReactNode, useContext } from 'react' +import { Connection, clusterApiUrl } from "@solana/web3.js"; +import { atom, useAtomValue, useSetAtom } from "jotai"; +import { atomWithStorage } from "jotai/utils"; +import { createContext, type ReactNode, useContext } from "react"; export interface SolanaCluster { - name: string - endpoint: string - network?: ClusterNetwork - active?: boolean + name: string; + endpoint: string; + network?: ClusterNetwork; + active?: boolean; } export enum ClusterNetwork { - Mainnet = 'mainnet-beta', - Testnet = 'testnet', - Devnet = 'devnet', - Custom = 'custom', + Mainnet = "mainnet-beta", + Testnet = "testnet", + Devnet = "devnet", + Custom = "custom", } // By default, we don't configure the mainnet-beta cluster @@ -24,94 +24,94 @@ export enum ClusterNetwork { // To use the mainnet-beta cluster, provide a custom endpoint export const defaultClusters: SolanaCluster[] = [ { - name: 'devnet', - endpoint: clusterApiUrl('devnet'), + name: "devnet", + endpoint: clusterApiUrl("devnet"), network: ClusterNetwork.Devnet, }, - { name: 'local', endpoint: 'http://localhost:8899' }, + { name: "local", endpoint: "http://localhost:8899" }, { - name: 'testnet', - endpoint: clusterApiUrl('testnet'), + name: "testnet", + endpoint: clusterApiUrl("testnet"), network: ClusterNetwork.Testnet, }, -] +]; -const clusterAtom = atomWithStorage('solana-cluster', defaultClusters[0]) -const clustersAtom = atomWithStorage('solana-clusters', defaultClusters) +const clusterAtom = atomWithStorage("solana-cluster", defaultClusters[0]); +const clustersAtom = atomWithStorage("solana-clusters", defaultClusters); const activeClustersAtom = atom((get) => { - const clusters = get(clustersAtom) - const cluster = get(clusterAtom) + const clusters = get(clustersAtom); + const cluster = get(clusterAtom); return clusters.map((item) => ({ ...item, active: item.name === cluster.name, - })) -}) + })); +}); const activeClusterAtom = atom((get) => { - const clusters = get(activeClustersAtom) + const clusters = get(activeClustersAtom); - return clusters.find((item) => item.active) || clusters[0] -}) + return clusters.find((item) => item.active) || clusters[0]; +}); export interface ClusterProviderContext { - cluster: SolanaCluster - clusters: SolanaCluster[] - addCluster: (cluster: SolanaCluster) => void - deleteCluster: (cluster: SolanaCluster) => void - setCluster: (cluster: SolanaCluster) => void + cluster: SolanaCluster; + clusters: SolanaCluster[]; + addCluster: (cluster: SolanaCluster) => void; + deleteCluster: (cluster: SolanaCluster) => void; + setCluster: (cluster: SolanaCluster) => void; - getExplorerUrl(path: string): string + getExplorerUrl(path: string): string; } -const Context = createContext({} as ClusterProviderContext) +const Context = createContext({} as ClusterProviderContext); export function ClusterProvider({ children }: { children: ReactNode }) { - const cluster = useAtomValue(activeClusterAtom) - const clusters = useAtomValue(activeClustersAtom) - const setCluster = useSetAtom(clusterAtom) - const setClusters = useSetAtom(clustersAtom) + const cluster = useAtomValue(activeClusterAtom); + const clusters = useAtomValue(activeClustersAtom); + const setCluster = useSetAtom(clusterAtom); + const setClusters = useSetAtom(clustersAtom); const value: ClusterProviderContext = { cluster, clusters: clusters.sort((a, b) => (a.name > b.name ? 1 : -1)), addCluster: (cluster: SolanaCluster) => { try { - new Connection(cluster.endpoint) - setClusters([...clusters, cluster]) + new Connection(cluster.endpoint); + setClusters([...clusters, cluster]); } catch (err) { - console.error(`${err}`) + console.error(`${err}`); } }, deleteCluster: (cluster: SolanaCluster) => { - setClusters(clusters.filter((item) => item.name !== cluster.name)) + setClusters(clusters.filter((item) => item.name !== cluster.name)); }, setCluster: (cluster: SolanaCluster) => setCluster(cluster), getExplorerUrl: (path: string) => `https://explorer.solana.com/${path}${getClusterUrlParam(cluster)}`, - } - return {children} + }; + return {children}; } export function useCluster() { - return useContext(Context) + return useContext(Context); } function getClusterUrlParam(cluster: SolanaCluster): string { - let suffix = '' + let suffix = ""; switch (cluster.network) { case ClusterNetwork.Devnet: - suffix = 'devnet' - break + suffix = "devnet"; + break; case ClusterNetwork.Mainnet: - suffix = '' - break + suffix = ""; + break; case ClusterNetwork.Testnet: - suffix = 'testnet' - break + suffix = "testnet"; + break; default: - suffix = `custom&customUrl=${encodeURIComponent(cluster.endpoint)}` - break + suffix = `custom&customUrl=${encodeURIComponent(cluster.endpoint)}`; + break; } - return suffix.length ? `?cluster=${suffix}` : '' + return suffix.length ? `?cluster=${suffix}` : ""; } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/cluster/cluster-ui.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/cluster/cluster-ui.tsx index 66ac4ce05..99e1ac5b4 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/cluster/cluster-ui.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/cluster/cluster-ui.tsx @@ -1,18 +1,21 @@ -'use client' +"use client"; -import { useConnection } from '@solana/wallet-adapter-react' +import { useConnection } from "@solana/wallet-adapter-react"; -import { useQuery } from '@tanstack/react-query' -import * as React from 'react' -import { ReactNode } from 'react' - -import { useCluster } from './cluster-data-access' -import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu' -import { Button } from '@/components/ui/button' -import { AppAlert } from '@/components/app-alert' +import { useQuery } from "@tanstack/react-query"; +import type { ReactNode } from "react"; +import { AppAlert } from "@/components/app-alert"; +import { Button } from "@/components/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { useCluster } from "./cluster-data-access"; export function ExplorerLink({ path, label, className }: { path: string; label: string; className?: string }) { - const { getExplorerUrl } = useCluster() + const { getExplorerUrl } = useCluster(); return (
    {label} - ) + ); } export function ClusterChecker({ children }: { children: ReactNode }) { - const { cluster } = useCluster() - const { connection } = useConnection() + const { cluster } = useCluster(); + const { connection } = useConnection(); const query = useQuery({ - queryKey: ['version', { cluster, endpoint: connection.rpcEndpoint }], + queryKey: ["version", { cluster, endpoint: connection.rpcEndpoint }], queryFn: () => connection.getVersion(), retry: 1, - }) + }); if (query.isLoading) { - return null + return null; } if (query.isError || !query.data) { return ( @@ -48,13 +51,13 @@ export function ClusterChecker({ children }: { children: ReactNode }) { > Error connecting to cluster {cluster.name}. - ) + ); } - return children + return children; } export function ClusterUiSelect() { - const { clusters, setCluster, cluster } = useCluster() + const { clusters, setCluster, cluster } = useCluster(); return ( @@ -68,5 +71,5 @@ export function ClusterUiSelect() { ))} - ) + ); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/dashboard/dashboard-feature.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/dashboard/dashboard-feature.tsx index f6ddf48c2..77d01c47f 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/dashboard/dashboard-feature.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/dashboard/dashboard-feature.tsx @@ -1,12 +1,15 @@ -import { AppHero } from '@/components/app-hero' +import { AppHero } from "@/components/app-hero"; const links: { label: string; href: string }[] = [ - { label: 'Solana Docs', href: 'https://docs.solana.com/' }, - { label: 'Solana Faucet', href: 'https://faucet.solana.com/' }, - { label: 'Solana Cookbook', href: 'https://solana.com/developers/cookbook/' }, - { label: 'Solana Stack Overflow', href: 'https://solana.stackexchange.com/' }, - { label: 'Solana Developers GitHub', href: 'https://github.com/solana-developers/' }, -] + { label: "Solana Docs", href: "https://docs.solana.com/" }, + { label: "Solana Faucet", href: "https://faucet.solana.com/" }, + { label: "Solana Cookbook", href: "https://solana.com/developers/cookbook/" }, + { label: "Solana Stack Overflow", href: "https://solana.stackexchange.com/" }, + { + label: "Solana Developers GitHub", + href: "https://github.com/solana-developers/", + }, +]; export function DashboardFeature() { return ( @@ -15,8 +18,8 @@ export function DashboardFeature() {

    Here are some helpful links to get you started.

    - {links.map((link, index) => ( -
    + {links.map((link) => ( +
    - ) + ); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/react-query-provider.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/react-query-provider.tsx index 2d4523ce6..6c3ca0bf6 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/react-query-provider.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/react-query-provider.tsx @@ -1,7 +1,7 @@ // Taken from https://tanstack.com/query/5/docs/framework/react/guides/advanced-ssr -'use client' +"use client"; -import { isServer, QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { isServer, QueryClient, QueryClientProvider } from "@tanstack/react-query"; function makeQueryClient() { return new QueryClient({ @@ -10,22 +10,22 @@ function makeQueryClient() { staleTime: 60 * 1000, }, }, - }) + }); } -let browserQueryClient: QueryClient | undefined = undefined +let browserQueryClient: QueryClient | undefined; function getQueryClient() { if (isServer) { - return makeQueryClient() + return makeQueryClient(); } else { - if (!browserQueryClient) browserQueryClient = makeQueryClient() - return browserQueryClient + if (!browserQueryClient) browserQueryClient = makeQueryClient(); + return browserQueryClient; } } export function ReactQueryProvider({ children }: { children: React.ReactNode }) { - const queryClient = getQueryClient() + const queryClient = getQueryClient(); - return {children} + return {children}; } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/solana/solana-provider.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/solana/solana-provider.tsx index 43e29b2ba..993f29778 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/solana/solana-provider.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/solana/solana-provider.tsx @@ -1,30 +1,30 @@ -'use client' +"use client"; -import { WalletError } from '@solana/wallet-adapter-base' +import type { WalletError } from "@solana/wallet-adapter-base"; import { - AnchorWallet, + type AnchorWallet, ConnectionProvider, useConnection, useWallet, WalletProvider, -} from '@solana/wallet-adapter-react' -import { WalletModalProvider } from '@solana/wallet-adapter-react-ui' -import dynamic from 'next/dynamic' -import { ReactNode, useCallback, useMemo } from 'react' -import { useCluster } from '../cluster/cluster-data-access' -import '@solana/wallet-adapter-react-ui/styles.css' -import { AnchorProvider } from '@anchor-lang/core' +} from "@solana/wallet-adapter-react"; +import { WalletModalProvider } from "@solana/wallet-adapter-react-ui"; +import dynamic from "next/dynamic"; +import { type ReactNode, useCallback, useMemo } from "react"; +import { useCluster } from "../cluster/cluster-data-access"; +import "@solana/wallet-adapter-react-ui/styles.css"; +import { AnchorProvider } from "@anchor-lang/core"; -export const WalletButton = dynamic(async () => (await import('@solana/wallet-adapter-react-ui')).WalletMultiButton, { +export const WalletButton = dynamic(async () => (await import("@solana/wallet-adapter-react-ui")).WalletMultiButton, { ssr: false, -}) +}); export function SolanaProvider({ children }: { children: ReactNode }) { - const { cluster } = useCluster() - const endpoint = useMemo(() => cluster.endpoint, [cluster]) + const { cluster } = useCluster(); + const endpoint = useMemo(() => cluster.endpoint, [cluster]); const onError = useCallback((error: WalletError) => { - console.error(error) - }, []) + console.error(error); + }, []); return ( @@ -32,12 +32,14 @@ export function SolanaProvider({ children }: { children: ReactNode }) { {children} - ) + ); } export function useAnchorProvider() { - const { connection } = useConnection() - const wallet = useWallet() + const { connection } = useConnection(); + const wallet = useWallet(); - return new AnchorProvider(connection, wallet as AnchorWallet, { commitment: 'confirmed' }) + return new AnchorProvider(connection, wallet as AnchorWallet, { + commitment: "confirmed", + }); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/theme-provider.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/theme-provider.tsx index f7328c86a..8e41496ff 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/theme-provider.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/theme-provider.tsx @@ -1,8 +1,8 @@ -'use client' +"use client"; -import * as React from 'react' -import { ThemeProvider as NextThemesProvider } from 'next-themes' +import { ThemeProvider as NextThemesProvider } from "next-themes"; +import type * as React from "react"; export function ThemeProvider({ children, ...props }: React.ComponentProps) { - return {children} + return {children}; } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/theme-select.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/theme-select.tsx index 7c8331cca..7a8617004 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/theme-select.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/theme-select.tsx @@ -1,14 +1,18 @@ -'use client' +"use client"; -import * as React from 'react' -import { Moon, Sun } from 'lucide-react' -import { useTheme } from 'next-themes' +import { Moon, Sun } from "lucide-react"; +import { useTheme } from "next-themes"; -import { Button } from '@/components/ui/button' -import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu' +import { Button } from "@/components/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; export function ThemeSelect() { - const { setTheme } = useTheme() + const { setTheme } = useTheme(); return ( @@ -20,10 +24,10 @@ export function ThemeSelect() { - setTheme('light')}>Light - setTheme('dark')}>Dark - setTheme('system')}>System + setTheme("light")}>Light + setTheme("dark")}>Dark + setTheme("system")}>System - ) + ); } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/alert.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/alert.tsx index cbf8da2b6..174412a6c 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/alert.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/alert.tsx @@ -1,51 +1,51 @@ -import * as React from 'react' -import { cva, type VariantProps } from 'class-variance-authority' +import { cva, type VariantProps } from "class-variance-authority"; +import type * as React from "react"; -import { cn } from '@/lib/utils' +import { cn } from "@/lib/utils"; const alertVariants = cva( - 'relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current', + "relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current", { variants: { variant: { - default: 'bg-card text-card-foreground', + default: "bg-card text-card-foreground", destructive: - 'text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90', + "text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90", warning: - 'text-yellow-500 bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-yellow-500/90 border-yellow-500 dark:bg-yellow-900/10', + "text-yellow-500 bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-yellow-500/90 border-yellow-500 dark:bg-yellow-900/10", }, }, defaultVariants: { - variant: 'default', + variant: "default", }, }, -) +); -function Alert({ className, variant, ...props }: React.ComponentProps<'div'> & VariantProps) { - return
    +function Alert({ className, variant, ...props }: React.ComponentProps<"div"> & VariantProps) { + return
    ; } -function AlertTitle({ className, ...props }: React.ComponentProps<'div'>) { +function AlertTitle({ className, ...props }: React.ComponentProps<"div">) { return (
    - ) + ); } -function AlertDescription({ className, ...props }: React.ComponentProps<'div'>) { +function AlertDescription({ className, ...props }: React.ComponentProps<"div">) { return (
    - ) + ); } -export { Alert, AlertTitle, AlertDescription } +export { Alert, AlertDescription, AlertTitle }; diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/button.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/button.tsx index 43a479064..45e1107fd 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/button.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/button.tsx @@ -1,36 +1,36 @@ -import * as React from 'react' -import { Slot } from '@radix-ui/react-slot' -import { cva, type VariantProps } from 'class-variance-authority' +import { Slot } from "@radix-ui/react-slot"; +import { cva, type VariantProps } from "class-variance-authority"; +import type * as React from "react"; -import { cn } from '@/lib/utils' +import { cn } from "@/lib/utils"; const buttonVariants = cva( "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive", { variants: { variant: { - default: 'bg-primary text-primary-foreground shadow-xs hover:bg-primary/90', + default: "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90", destructive: - 'bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60', + "bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60", outline: - 'border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50', - secondary: 'bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80', - ghost: 'hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50', - link: 'text-primary underline-offset-4 hover:underline', + "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50", + secondary: "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80", + ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50", + link: "text-primary underline-offset-4 hover:underline", }, size: { - default: 'h-9 px-4 py-2 has-[>svg]:px-3', - sm: 'h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5', - lg: 'h-10 rounded-md px-6 has-[>svg]:px-4', - icon: 'size-9', + default: "h-9 px-4 py-2 has-[>svg]:px-3", + sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5", + lg: "h-10 rounded-md px-6 has-[>svg]:px-4", + icon: "size-9", }, }, defaultVariants: { - variant: 'default', - size: 'default', + variant: "default", + size: "default", }, }, -) +); function Button({ className, @@ -38,13 +38,13 @@ function Button({ size, asChild = false, ...props -}: React.ComponentProps<'button'> & +}: React.ComponentProps<"button"> & VariantProps & { - asChild?: boolean + asChild?: boolean; }) { - const Comp = asChild ? Slot : 'button' + const Comp = asChild ? Slot : "button"; - return + return ; } -export { Button, buttonVariants } +export { Button, buttonVariants }; diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/card.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/card.tsx index bf20394f7..e5c165f82 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/card.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/card.tsx @@ -1,54 +1,56 @@ -import * as React from 'react' +import type * as React from "react"; -import { cn } from '@/lib/utils' +import { cn } from "@/lib/utils"; -function Card({ className, ...props }: React.ComponentProps<'div'>) { +function Card({ className, ...props }: React.ComponentProps<"div">) { return (
    - ) + ); } -function CardHeader({ className, ...props }: React.ComponentProps<'div'>) { +function CardHeader({ className, ...props }: React.ComponentProps<"div">) { return (
    - ) + ); } -function CardTitle({ className, ...props }: React.ComponentProps<'div'>) { - return
    +function CardTitle({ className, ...props }: React.ComponentProps<"div">) { + return
    ; } -function CardDescription({ className, ...props }: React.ComponentProps<'div'>) { - return
    +function CardDescription({ className, ...props }: React.ComponentProps<"div">) { + return
    ; } -function CardAction({ className, ...props }: React.ComponentProps<'div'>) { +function CardAction({ className, ...props }: React.ComponentProps<"div">) { return (
    - ) + ); } -function CardContent({ className, ...props }: React.ComponentProps<'div'>) { - return
    +function CardContent({ className, ...props }: React.ComponentProps<"div">) { + return
    ; } -function CardFooter({ className, ...props }: React.ComponentProps<'div'>) { - return
    +function CardFooter({ className, ...props }: React.ComponentProps<"div">) { + return ( +
    + ); } -export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent } +export { Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle }; diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/dialog.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/dialog.tsx index f35cad9d9..4a3cb9e9b 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/dialog.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/dialog.tsx @@ -1,25 +1,25 @@ -'use client' +"use client"; -import * as React from 'react' -import * as DialogPrimitive from '@radix-ui/react-dialog' -import { XIcon } from 'lucide-react' +import * as DialogPrimitive from "@radix-ui/react-dialog"; +import { XIcon } from "lucide-react"; +import type * as React from "react"; -import { cn } from '@/lib/utils' +import { cn } from "@/lib/utils"; function Dialog({ ...props }: React.ComponentProps) { - return + return ; } function DialogTrigger({ ...props }: React.ComponentProps) { - return + return ; } function DialogPortal({ ...props }: React.ComponentProps) { - return + return ; } function DialogClose({ ...props }: React.ComponentProps) { - return + return ; } function DialogOverlay({ className, ...props }: React.ComponentProps) { @@ -27,12 +27,12 @@ function DialogOverlay({ className, ...props }: React.ComponentProps - ) + ); } function DialogContent({ className, children, ...props }: React.ComponentProps) { @@ -42,7 +42,7 @@ function DialogContent({ className, children, ...props }: React.ComponentProps - ) + ); } -function DialogHeader({ className, ...props }: React.ComponentProps<'div'>) { +function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { return (
    - ) + ); } -function DialogFooter({ className, ...props }: React.ComponentProps<'div'>) { +function DialogFooter({ className, ...props }: React.ComponentProps<"div">) { return (
    - ) + ); } function DialogTitle({ className, ...props }: React.ComponentProps) { return ( - ) + ); } function DialogDescription({ className, ...props }: React.ComponentProps) { return ( - ) + ); } export { @@ -108,4 +108,4 @@ export { DialogPortal, DialogTitle, DialogTrigger, -} +}; diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/dropdown-menu.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/dropdown-menu.tsx index 6c34345fb..c485a2a37 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/dropdown-menu.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/dropdown-menu.tsx @@ -1,21 +1,21 @@ -'use client' +"use client"; -import * as React from 'react' -import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu' -import { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react' +import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"; +import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"; +import type * as React from "react"; -import { cn } from '@/lib/utils' +import { cn } from "@/lib/utils"; function DropdownMenu({ ...props }: React.ComponentProps) { - return + return ; } function DropdownMenuPortal({ ...props }: React.ComponentProps) { - return + return ; } function DropdownMenuTrigger({ ...props }: React.ComponentProps) { - return + return ; } function DropdownMenuContent({ @@ -29,27 +29,27 @@ function DropdownMenuContent({ data-slot="dropdown-menu-content" sideOffset={sideOffset} className={cn( - 'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md', + "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md", className, )} {...props} /> - ) + ); } function DropdownMenuGroup({ ...props }: React.ComponentProps) { - return + return ; } function DropdownMenuItem({ className, inset, - variant = 'default', + variant = "default", ...props }: React.ComponentProps & { - inset?: boolean - variant?: 'default' | 'destructive' + inset?: boolean; + variant?: "default" | "destructive"; }) { return ( - ) + ); } function DropdownMenuCheckboxItem({ @@ -88,11 +88,11 @@ function DropdownMenuCheckboxItem({ {children} - ) + ); } function DropdownMenuRadioGroup({ ...props }: React.ComponentProps) { - return + return ; } function DropdownMenuRadioItem({ @@ -116,7 +116,7 @@ function DropdownMenuRadioItem({ {children} - ) + ); } function DropdownMenuLabel({ @@ -124,40 +124,40 @@ function DropdownMenuLabel({ inset, ...props }: React.ComponentProps & { - inset?: boolean + inset?: boolean; }) { return ( - ) + ); } function DropdownMenuSeparator({ className, ...props }: React.ComponentProps) { return ( - ) + ); } -function DropdownMenuShortcut({ className, ...props }: React.ComponentProps<'span'>) { +function DropdownMenuShortcut({ className, ...props }: React.ComponentProps<"span">) { return ( - ) + ); } function DropdownMenuSub({ ...props }: React.ComponentProps) { - return + return ; } function DropdownMenuSubTrigger({ @@ -166,14 +166,14 @@ function DropdownMenuSubTrigger({ children, ...props }: React.ComponentProps & { - inset?: boolean + inset?: boolean; }) { return ( - ) + ); } function DropdownMenuSubContent({ @@ -192,28 +192,28 @@ function DropdownMenuSubContent({ - ) + ); } export { DropdownMenu, - DropdownMenuPortal, - DropdownMenuTrigger, + DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, - DropdownMenuLabel, DropdownMenuItem, - DropdownMenuCheckboxItem, + DropdownMenuLabel, + DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, - DropdownMenuSubTrigger, DropdownMenuSubContent, -} + DropdownMenuSubTrigger, + DropdownMenuTrigger, +}; diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/input.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/input.tsx index 75fee7dfc..cb0e803b0 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/input.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/input.tsx @@ -1,21 +1,21 @@ -import * as React from 'react' +import type * as React from "react"; -import { cn } from '@/lib/utils' +import { cn } from "@/lib/utils"; -function Input({ className, type, ...props }: React.ComponentProps<'input'>) { +function Input({ className, type, ...props }: React.ComponentProps<"input">) { return ( - ) + ); } -export { Input } +export { Input }; diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/label.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/label.tsx index a50c56949..aa7fe645a 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/label.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/label.tsx @@ -1,21 +1,21 @@ -'use client' +"use client"; -import * as React from 'react' -import * as LabelPrimitive from '@radix-ui/react-label' +import * as LabelPrimitive from "@radix-ui/react-label"; +import type * as React from "react"; -import { cn } from '@/lib/utils' +import { cn } from "@/lib/utils"; function Label({ className, ...props }: React.ComponentProps) { return ( - ) + ); } -export { Label } +export { Label }; diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/sonner.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/sonner.tsx index 0626cafa8..f96a98d91 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/sonner.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/sonner.tsx @@ -1,25 +1,25 @@ -'use client' +"use client"; -import { useTheme } from 'next-themes' -import { Toaster as Sonner, ToasterProps } from 'sonner' +import { useTheme } from "next-themes"; +import { Toaster as Sonner, type ToasterProps } from "sonner"; const Toaster = ({ ...props }: ToasterProps) => { - const { theme = 'system' } = useTheme() + const { theme = "system" } = useTheme(); return ( - ) -} + ); +}; -export { Toaster } +export { Toaster }; diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/table.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/table.tsx index e5351ccd0..afe6d5f82 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/table.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/ui/table.tsx @@ -1,75 +1,75 @@ -'use client' +"use client"; -import * as React from 'react' +import type * as React from "react"; -import { cn } from '@/lib/utils' +import { cn } from "@/lib/utils"; -function Table({ className, ...props }: React.ComponentProps<'table'>) { +function Table({ className, ...props }: React.ComponentProps<"table">) { return (
    - +
    - ) + ); } -function TableHeader({ className, ...props }: React.ComponentProps<'thead'>) { - return +function TableHeader({ className, ...props }: React.ComponentProps<"thead">) { + return ; } -function TableBody({ className, ...props }: React.ComponentProps<'tbody'>) { - return +function TableBody({ className, ...props }: React.ComponentProps<"tbody">) { + return ; } -function TableFooter({ className, ...props }: React.ComponentProps<'tfoot'>) { +function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) { return ( tr]:last:border-b-0', className)} + className={cn("bg-muted/50 border-t font-medium [&>tr]:last:border-b-0", className)} {...props} /> - ) + ); } -function TableRow({ className, ...props }: React.ComponentProps<'tr'>) { +function TableRow({ className, ...props }: React.ComponentProps<"tr">) { return ( - ) + ); } -function TableHead({ className, ...props }: React.ComponentProps<'th'>) { +function TableHead({ className, ...props }: React.ComponentProps<"th">) { return (
    [role=checkbox]]:translate-y-[2px]', + "text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]", className, )} {...props} /> - ) + ); } -function TableCell({ className, ...props }: React.ComponentProps<'td'>) { +function TableCell({ className, ...props }: React.ComponentProps<"td">) { return ( [role=checkbox]]:translate-y-[2px]', + "p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]", className, )} {...props} /> - ) + ); } -function TableCaption({ className, ...props }: React.ComponentProps<'caption'>) { +function TableCaption({ className, ...props }: React.ComponentProps<"caption">) { return ( -
    - ) + + ); } -export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption } +export { Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow }; diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/use-transaction-toast.tsx b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/use-transaction-toast.tsx index d354a5d17..6032f5d85 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/use-transaction-toast.tsx +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/components/use-transaction-toast.tsx @@ -1,13 +1,13 @@ -import { toast } from 'sonner' -import { ExplorerLink } from './cluster/cluster-ui' -import { Connection, SendTransactionError } from '@solana/web3.js' +import type { Connection, SendTransactionError } from "@solana/web3.js"; +import { toast } from "sonner"; +import { ExplorerLink } from "./cluster/cluster-ui"; export function useTransactionToast() { return (signature: string) => { - toast('Transaction sent', { + toast("Transaction sent", { description: , - }) - } + }); + }; } export function useTransactionErrorToast() { @@ -16,18 +16,18 @@ export function useTransactionErrorToast() { const anchorError = logs.find((l) => l.startsWith("Program log: AnchorError occurred")); if (anchorError) { if (anchorError.includes("WalletBlocked")) { - toast.error(`Destination wallet is blocked from receiving funds.`) + toast.error(`Destination wallet is blocked from receiving funds.`); } else if (anchorError.includes("WalletNotAllowed")) { - toast.error(`Destination wallet is not allowed to receive funds.`) + toast.error(`Destination wallet is not allowed to receive funds.`); } else if (anchorError.includes("AmountNotAllowed")) { - toast.error(`Destination wallet is not authorized to receive this amount.`) + toast.error(`Destination wallet is not authorized to receive this amount.`); } else { - console.log("ERROR: ", error) - toast.error(`Failed to run program: ${error}`) + console.log("ERROR: ", error); + toast.error(`Failed to run program: ${error}`); } } else { - console.log("ERROR: ", error) - toast.error(`Failed to run program: ${error}`) + console.log("ERROR: ", error); + toast.error(`Failed to run program: ${error}`); } - } + }; } diff --git a/tokens/token-2022/transfer-hook/allow-block-list-token/src/lib/utils.ts b/tokens/token-2022/transfer-hook/allow-block-list-token/src/lib/utils.ts index 1f56ee2d2..c666f4338 100644 --- a/tokens/token-2022/transfer-hook/allow-block-list-token/src/lib/utils.ts +++ b/tokens/token-2022/transfer-hook/allow-block-list-token/src/lib/utils.ts @@ -1,11 +1,11 @@ -import { type ClassValue, clsx } from 'clsx'; -import { twMerge } from 'tailwind-merge'; +import { type ClassValue, clsx } from "clsx"; +import { twMerge } from "tailwind-merge"; export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); } -export function ellipsify(str = '', len = 4, delimiter = '..') { +export function ellipsify(str = "", len = 4, delimiter = "..") { const strLen = str.length; const limit = len * 2 + delimiter.length; diff --git a/tokens/token-2022/transfer-hook/counter/anchor/migrations/deploy.ts b/tokens/token-2022/transfer-hook/counter/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/tokens/token-2022/transfer-hook/counter/anchor/migrations/deploy.ts +++ b/tokens/token-2022/transfer-hook/counter/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/token-2022/transfer-hook/counter/anchor/package.json b/tokens/token-2022/transfer-hook/counter/anchor/package.json index 3c254f5f9..c4ab86214 100644 --- a/tokens/token-2022/transfer-hook/counter/anchor/package.json +++ b/tokens/token-2022/transfer-hook/counter/anchor/package.json @@ -1,24 +1,24 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.4.0", - "@solana/web3.js": "^1.98.4" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/chai-as-promised": "^7.1.8", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "chai-as-promised": "^7.1.2", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.4.0", + "@solana/web3.js": "^1.98.4" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/chai-as-promised": "^7.1.8", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "chai-as-promised": "^7.1.2", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-2022/transfer-hook/counter/anchor/tests/transfer-hook.ts b/tokens/token-2022/transfer-hook/counter/anchor/tests/transfer-hook.ts index 1ace10b1a..feaced79d 100644 --- a/tokens/token-2022/transfer-hook/counter/anchor/tests/transfer-hook.ts +++ b/tokens/token-2022/transfer-hook/counter/anchor/tests/transfer-hook.ts @@ -1,5 +1,5 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; import { ASSOCIATED_TOKEN_PROGRAM_ID, createAssociatedTokenAccountInstruction, @@ -11,16 +11,23 @@ import { getAssociatedTokenAddressSync, getMintLen, TOKEN_2022_PROGRAM_ID, -} from '@solana/spl-token'; -import { Keypair, PublicKey, SendTransactionError, SystemProgram, sendAndConfirmTransaction, Transaction } from '@solana/web3.js'; -import { BN } from 'bn.js'; -import chai, { expect } from 'chai'; -import chaiAsPromised from 'chai-as-promised'; -import type { TransferHook } from '../target/types/transfer_hook'; +} from "@solana/spl-token"; +import { + Keypair, + PublicKey, + SendTransactionError, + SystemProgram, + sendAndConfirmTransaction, + Transaction, +} from "@solana/web3.js"; +import { BN } from "bn.js"; +import chai, { expect } from "chai"; +import chaiAsPromised from "chai-as-promised"; +import type { TransferHook } from "../target/types/transfer_hook"; chai.use(chaiAsPromised); -describe('transfer-hook', () => { +describe("transfer-hook", () => { // Configure the client to use the local cluster. const provider = anchor.AnchorProvider.env(); anchor.setProvider(provider); @@ -55,13 +62,13 @@ describe('transfer-hook', () => { // ExtraAccountMetaList address // Store extra accounts required by the custom transfer hook instruction const [extraAccountMetaListPDA] = PublicKey.findProgramAddressSync( - [Buffer.from('extra-account-metas'), mint.publicKey.toBuffer()], + [Buffer.from("extra-account-metas"), mint.publicKey.toBuffer()], program.programId, ); - const [counterPDA] = PublicKey.findProgramAddressSync([Buffer.from('counter')], program.programId); + const [counterPDA] = PublicKey.findProgramAddressSync([Buffer.from("counter")], program.programId); - it('Create Mint Account with Transfer Hook Extension', async () => { + it("Create Mint Account with Transfer Hook Extension", async () => { const extensions = [ExtensionType.TransferHook]; const mintLen = getMintLen(extensions); const lamports = await provider.connection.getMinimumBalanceForRentExemption(mintLen); @@ -85,12 +92,12 @@ describe('transfer-hook', () => { const txSig = await sendAndConfirmTransaction(provider.connection, transaction, [wallet.payer, mint], { skipPreflight: true, - commitment: 'finalized', + commitment: "finalized", }); const txDetails = await program.provider.connection.getTransaction(txSig, { maxSupportedTransactionVersion: 0, - commitment: 'confirmed', + commitment: "confirmed", }); console.log(txDetails.meta.logMessages); @@ -99,7 +106,7 @@ describe('transfer-hook', () => { // Create the two token accounts for the transfer-hook enabled mint // Fund the sender token account with 100 tokens - it('Create Token Accounts and Mint Tokens', async () => { + it("Create Token Accounts and Mint Tokens", async () => { // 100 tokens const amount = 100 * 10 ** decimals; @@ -129,7 +136,7 @@ describe('transfer-hook', () => { }); // Account to store extra accounts required by the transfer hook instruction - it('Create ExtraAccountMetaList Account', async () => { + it("Create ExtraAccountMetaList Account", async () => { const initializeExtraAccountMetaListInstruction = await program.methods .initializeExtraAccountMetaList() .accounts({ @@ -139,11 +146,14 @@ describe('transfer-hook', () => { const transaction = new Transaction().add(initializeExtraAccountMetaListInstruction); - const txSig = await sendAndConfirmTransaction(provider.connection, transaction, [wallet.payer], { skipPreflight: true, commitment: 'confirmed' }); - console.log('Transaction Signature:', txSig); + const txSig = await sendAndConfirmTransaction(provider.connection, transaction, [wallet.payer], { + skipPreflight: true, + commitment: "confirmed", + }); + console.log("Transaction Signature:", txSig); }); - it('Transfer Hook with Extra Account Meta', async () => { + it("Transfer Hook with Extra Account Meta", async () => { // 1 tokens const amount = 1 * 10 ** decimals; const amountBigInt = BigInt(amount); @@ -157,7 +167,7 @@ describe('transfer-hook', () => { amountBigInt, decimals, [], - 'confirmed', + "confirmed", TOKEN_2022_PROGRAM_ID, ); @@ -168,10 +178,10 @@ describe('transfer-hook', () => { const transaction = new Transaction().add(transferInstructionWithHelper); const txSig = await sendAndConfirmTransaction(connection, transaction, [wallet.payer], { skipPreflight: true }); - console.log('Transfer Signature:', txSig); + console.log("Transfer Signature:", txSig); }); - it('Try call transfer hook without transfer', async () => { + it("Try call transfer hook without transfer", async () => { const transferHookIx = await program.methods .transferHook(new BN(1)) .accounts({ diff --git a/tokens/token-2022/transfer-hook/hello-world/anchor/migrations/deploy.ts b/tokens/token-2022/transfer-hook/hello-world/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/tokens/token-2022/transfer-hook/hello-world/anchor/migrations/deploy.ts +++ b/tokens/token-2022/transfer-hook/hello-world/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/token-2022/transfer-hook/hello-world/anchor/package.json b/tokens/token-2022/transfer-hook/hello-world/anchor/package.json index 3c254f5f9..c4ab86214 100644 --- a/tokens/token-2022/transfer-hook/hello-world/anchor/package.json +++ b/tokens/token-2022/transfer-hook/hello-world/anchor/package.json @@ -1,24 +1,24 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.4.0", - "@solana/web3.js": "^1.98.4" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/chai-as-promised": "^7.1.8", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "chai-as-promised": "^7.1.2", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.4.0", + "@solana/web3.js": "^1.98.4" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/chai-as-promised": "^7.1.8", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "chai-as-promised": "^7.1.2", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-2022/transfer-hook/hello-world/anchor/tests/transfer-hook.ts b/tokens/token-2022/transfer-hook/hello-world/anchor/tests/transfer-hook.ts index 7f1dd1825..03716a2b4 100644 --- a/tokens/token-2022/transfer-hook/hello-world/anchor/tests/transfer-hook.ts +++ b/tokens/token-2022/transfer-hook/hello-world/anchor/tests/transfer-hook.ts @@ -1,5 +1,5 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; import { ASSOCIATED_TOKEN_PROGRAM_ID, createAssociatedTokenAccountInstruction, @@ -7,16 +7,16 @@ import { createTransferCheckedWithTransferHookInstruction, getAssociatedTokenAddressSync, TOKEN_2022_PROGRAM_ID, -} from '@solana/spl-token'; -import { Keypair, SendTransactionError, sendAndConfirmTransaction, Transaction } from '@solana/web3.js'; -import { BN } from 'bn.js'; -import chai, { expect } from 'chai'; -import chaiAsPromised from 'chai-as-promised'; -import type { TransferHook } from '../target/types/transfer_hook'; +} from "@solana/spl-token"; +import { Keypair, SendTransactionError, sendAndConfirmTransaction, Transaction } from "@solana/web3.js"; +import { BN } from "bn.js"; +import chai, { expect } from "chai"; +import chaiAsPromised from "chai-as-promised"; +import type { TransferHook } from "../target/types/transfer_hook"; chai.use(chaiAsPromised); -describe('transfer-hook', () => { +describe("transfer-hook", () => { // Configure the client to use the local cluster. const provider = anchor.AnchorProvider.env(); anchor.setProvider(provider); @@ -48,18 +48,18 @@ describe('transfer-hook', () => { ASSOCIATED_TOKEN_PROGRAM_ID, ); - it('Create Mint with Transfer Hook Extension', async () => { + it("Create Mint with Transfer Hook Extension", async () => { const transactionSignature = await program.methods .initialize(decimals) .accounts({ mintAccount: mint.publicKey }) .signers([mint]) .rpc({ skipPreflight: true }); - console.log('Your transaction signature', transactionSignature); + console.log("Your transaction signature", transactionSignature); }); // Create the two token accounts for the transfer-hook enabled mint // Fund the sender token account with 100 tokens - it('Create Token Accounts and Mint Tokens', async () => { + it("Create Token Accounts and Mint Tokens", async () => { // 100 tokens const amount = 100 * 10 ** decimals; @@ -89,7 +89,7 @@ describe('transfer-hook', () => { }); // Account to store extra accounts required by the transfer hook instruction - it('Create ExtraAccountMetaList Account', async () => { + it("Create ExtraAccountMetaList Account", async () => { const initializeExtraAccountMetaListInstruction = await program.methods .initializeExtraAccountMetaList() .accounts({ @@ -99,11 +99,14 @@ describe('transfer-hook', () => { const transaction = new Transaction().add(initializeExtraAccountMetaListInstruction); - const txSig = await sendAndConfirmTransaction(provider.connection, transaction, [wallet.payer], { skipPreflight: true, commitment: 'confirmed' }); - console.log('Transaction Signature:', txSig); + const txSig = await sendAndConfirmTransaction(provider.connection, transaction, [wallet.payer], { + skipPreflight: true, + commitment: "confirmed", + }); + console.log("Transaction Signature:", txSig); }); - it('Transfer Hook with Extra Account Meta', async () => { + it("Transfer Hook with Extra Account Meta", async () => { // 1 tokens const amount = 1 * 10 ** decimals; const bigIntAmount = BigInt(amount); @@ -118,17 +121,17 @@ describe('transfer-hook', () => { bigIntAmount, decimals, [], - 'confirmed', + "confirmed", TOKEN_2022_PROGRAM_ID, ); const transaction = new Transaction().add(transferInstruction); const txSig = await sendAndConfirmTransaction(connection, transaction, [wallet.payer], { skipPreflight: true }); - console.log('Transfer Signature:', txSig); + console.log("Transfer Signature:", txSig); }); - it('Try call transfer hook without transfer', async () => { + it("Try call transfer hook without transfer", async () => { const transferHookIx = await program.methods .transferHook(new BN(1)) .accounts({ diff --git a/tokens/token-2022/transfer-hook/pblock-list/codama.ts b/tokens/token-2022/transfer-hook/pblock-list/codama.ts index b21a0112c..643c667a5 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/codama.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/codama.ts @@ -1,6 +1,6 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { renderJavaScriptVisitor, renderRustVisitor } from '@codama/renderers'; +import fs from "node:fs"; +import path from "node:path"; +import { renderJavaScriptVisitor, renderRustVisitor } from "@codama/renderers"; import { accountNode, booleanTypeNode, @@ -24,242 +24,248 @@ import { structFieldTypeNode, structTypeNode, variablePdaSeedNode, -} from 'codama'; +} from "codama"; -const _rustClientsDir = path.join(__dirname, '..', 'sdk', 'rust'); -const typescriptClientsDir = path.join(__dirname, '..', 'sdk', 'ts'); +const _rustClientsDir = path.join(__dirname, "..", "sdk", "rust"); +const typescriptClientsDir = path.join(__dirname, "..", "sdk", "ts"); const root = rootNode( programNode({ - name: 'block-list', - publicKey: 'BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf', - version: '1.0.0', + name: "block-list", + publicKey: "BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf", + version: "1.0.0", accounts: [ accountNode({ - name: 'config', - discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode('u8'), numberValueNode(0)))], + name: "config", + discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode("u8"), numberValueNode(0)))], size: 41, - pda: pdaLinkNode('config'), - docs: ['The config PDA account'], + pda: pdaLinkNode("config"), + docs: ["The config PDA account"], data: structTypeNode([ structFieldTypeNode({ - name: 'discriminator', - type: numberTypeNode('u8'), - defaultValueStrategy: 'omitted', + name: "discriminator", + type: numberTypeNode("u8"), + defaultValueStrategy: "omitted", }), structFieldTypeNode({ - name: 'authority', + name: "authority", type: publicKeyTypeNode(), }), structFieldTypeNode({ - name: 'blocked_wallets_count', - type: numberTypeNode('u64'), + name: "blocked_wallets_count", + type: numberTypeNode("u64"), }), ]), }), accountNode({ - name: 'walletBlock', - discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode('u8'), numberValueNode(1)))], + name: "walletBlock", + discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode("u8"), numberValueNode(1)))], size: 33, - pda: pdaLinkNode('walletBlock'), - docs: ['The config PDA account'], + pda: pdaLinkNode("walletBlock"), + docs: ["The config PDA account"], data: structTypeNode([ structFieldTypeNode({ - name: 'authority', + name: "authority", type: publicKeyTypeNode(), }), ]), }), accountNode({ - name: 'extraMetas', - pda: pdaLinkNode('extraMetas'), - docs: ['The extra metas PDA account'], + name: "extraMetas", + pda: pdaLinkNode("extraMetas"), + docs: ["The extra metas PDA account"], }), ], instructions: [ instructionNode({ - name: 'init', + name: "init", arguments: [ instructionArgumentNode({ - name: 'discriminator', - type: numberTypeNode('u8'), + name: "discriminator", + type: numberTypeNode("u8"), defaultValue: numberValueNode(0xf1), - defaultValueStrategy: 'omitted', + defaultValueStrategy: "omitted", }), ], accounts: [ instructionAccountNode({ - name: 'authority', + name: "authority", isSigner: true, isWritable: true, }), instructionAccountNode({ - name: 'config', + name: "config", isSigner: false, isWritable: true, - defaultValue: pdaValueNode(pdaLinkNode('config')), + defaultValue: pdaValueNode(pdaLinkNode("config")), }), instructionAccountNode({ - name: 'systemProgram', - defaultValue: publicKeyValueNode('11111111111111111111111111111111', 'systemProgram'), + name: "systemProgram", + defaultValue: publicKeyValueNode("11111111111111111111111111111111", "systemProgram"), isSigner: false, isWritable: false, }), ], - discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode('u8'), numberValueNode(0xf1)))], - docs: ['Initialize the config PDA account'], + discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode("u8"), numberValueNode(0xf1)))], + docs: ["Initialize the config PDA account"], }), instructionNode({ - name: 'blockWallet', + name: "blockWallet", arguments: [ instructionArgumentNode({ - name: 'discriminator', - type: numberTypeNode('u8'), + name: "discriminator", + type: numberTypeNode("u8"), defaultValue: numberValueNode(0xf2), - defaultValueStrategy: 'omitted', + defaultValueStrategy: "omitted", }), ], accounts: [ instructionAccountNode({ - name: 'authority', + name: "authority", isSigner: true, isWritable: true, }), instructionAccountNode({ - name: 'config', + name: "config", isSigner: false, isWritable: true, - defaultValue: pdaValueNode(pdaLinkNode('config')), + defaultValue: pdaValueNode(pdaLinkNode("config")), }), instructionAccountNode({ - name: 'wallet', + name: "wallet", isSigner: false, isWritable: false, }), instructionAccountNode({ - name: 'walletBlock', + name: "walletBlock", isSigner: false, isWritable: true, }), instructionAccountNode({ - name: 'systemProgram', - defaultValue: publicKeyValueNode('11111111111111111111111111111111', 'systemProgram'), + name: "systemProgram", + defaultValue: publicKeyValueNode("11111111111111111111111111111111", "systemProgram"), isSigner: false, isWritable: false, }), ], - discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode('u8'), numberValueNode(0xf2)))], - docs: ['Block a wallet'], + discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode("u8"), numberValueNode(0xf2)))], + docs: ["Block a wallet"], }), instructionNode({ - name: 'unblockWallet', + name: "unblockWallet", arguments: [ instructionArgumentNode({ - name: 'discriminator', - type: numberTypeNode('u8'), + name: "discriminator", + type: numberTypeNode("u8"), defaultValue: numberValueNode(0xf3), - defaultValueStrategy: 'omitted', + defaultValueStrategy: "omitted", }), ], accounts: [ instructionAccountNode({ - name: 'authority', + name: "authority", isSigner: true, isWritable: true, }), instructionAccountNode({ - name: 'config', + name: "config", isSigner: false, isWritable: true, - defaultValue: pdaValueNode(pdaLinkNode('config')), + defaultValue: pdaValueNode(pdaLinkNode("config")), }), instructionAccountNode({ - name: 'walletBlock', + name: "walletBlock", isSigner: false, isWritable: true, }), instructionAccountNode({ - name: 'systemProgram', - defaultValue: publicKeyValueNode('11111111111111111111111111111111', 'systemProgram'), + name: "systemProgram", + defaultValue: publicKeyValueNode("11111111111111111111111111111111", "systemProgram"), isSigner: false, isWritable: false, }), ], - discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode('u8'), numberValueNode(0xf3)))], - docs: ['Unblock a wallet'], + discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode("u8"), numberValueNode(0xf3)))], + docs: ["Unblock a wallet"], }), instructionNode({ - name: 'setupExtraMetas', + name: "setupExtraMetas", arguments: [ instructionArgumentNode({ - name: 'discriminator', - type: numberTypeNode('u8'), + name: "discriminator", + type: numberTypeNode("u8"), defaultValue: numberValueNode(0x6a), - defaultValueStrategy: 'omitted', + defaultValueStrategy: "omitted", }), instructionArgumentNode({ - name: 'checkBothWallets', + name: "checkBothWallets", type: booleanTypeNode(), defaultValue: booleanValueNode(false), - defaultValueStrategy: 'optional', + defaultValueStrategy: "optional", }), ], accounts: [ instructionAccountNode({ - name: 'authority', + name: "authority", isSigner: true, isWritable: true, }), instructionAccountNode({ - name: 'config', + name: "config", isSigner: false, isWritable: false, - defaultValue: pdaValueNode(pdaLinkNode('config')), + defaultValue: pdaValueNode(pdaLinkNode("config")), }), instructionAccountNode({ - name: 'mint', + name: "mint", isSigner: false, isWritable: false, }), instructionAccountNode({ - name: 'extraMetas', + name: "extraMetas", isSigner: false, isWritable: true, - defaultValue: pdaValueNode(pdaLinkNode('extraMetas')), + defaultValue: pdaValueNode(pdaLinkNode("extraMetas")), }), instructionAccountNode({ - name: 'systemProgram', - defaultValue: publicKeyValueNode('11111111111111111111111111111111', 'systemProgram'), + name: "systemProgram", + defaultValue: publicKeyValueNode("11111111111111111111111111111111", "systemProgram"), isSigner: false, isWritable: false, }), ], - discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode('u8'), numberValueNode(0x6a)))], - docs: ['Unblock a wallet'], + discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode("u8"), numberValueNode(0x6a)))], + docs: ["Unblock a wallet"], }), ], pdas: [ pdaNode({ - name: 'config', - seeds: [constantPdaSeedNodeFromString('utf8', 'config')], - docs: ['The config PDA account'], + name: "config", + seeds: [constantPdaSeedNodeFromString("utf8", "config")], + docs: ["The config PDA account"], }), pdaNode({ - name: 'walletBlock', - seeds: [constantPdaSeedNodeFromString('utf8', 'wallet_block'), variablePdaSeedNode('wallet', publicKeyTypeNode())], - docs: ['The wallet block PDA account'], + name: "walletBlock", + seeds: [ + constantPdaSeedNodeFromString("utf8", "wallet_block"), + variablePdaSeedNode("wallet", publicKeyTypeNode()), + ], + docs: ["The wallet block PDA account"], }), pdaNode({ - name: 'extraMetas', - seeds: [constantPdaSeedNodeFromString('utf8', 'extra-account-metas'), variablePdaSeedNode('mint', publicKeyTypeNode())], - docs: ['The extra metas PDA account'], + name: "extraMetas", + seeds: [ + constantPdaSeedNodeFromString("utf8", "extra-account-metas"), + variablePdaSeedNode("mint", publicKeyTypeNode()), + ], + docs: ["The extra metas PDA account"], }), ], }), ); function preserveConfigFiles() { - const filesToPreserve = ['package.json', 'tsconfig.json', '.npmignore', 'pnpm-lock.yaml', 'Cargo.toml']; + const filesToPreserve = ["package.json", "tsconfig.json", ".npmignore", "pnpm-lock.yaml", "Cargo.toml"]; const preservedFiles = new Map(); for (const filename of filesToPreserve) { @@ -289,5 +295,10 @@ const codama = createFromRoot(root); const _configPreserver = preserveConfigFiles(); -codama.accept(renderJavaScriptVisitor('sdk/ts/src', { formatCode: true })); -codama.accept(renderRustVisitor('sdk/rust/src/client', { crateFolder: 'sdk/rust/', formatCode: true })); +codama.accept(renderJavaScriptVisitor("sdk/ts/src", { formatCode: true })); +codama.accept( + renderRustVisitor("sdk/rust/src/client", { + crateFolder: "sdk/rust/", + formatCode: true, + }), +); diff --git a/tokens/token-2022/transfer-hook/pblock-list/pino/codama.ts b/tokens/token-2022/transfer-hook/pblock-list/pino/codama.ts index b21a0112c..643c667a5 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/pino/codama.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/pino/codama.ts @@ -1,6 +1,6 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { renderJavaScriptVisitor, renderRustVisitor } from '@codama/renderers'; +import fs from "node:fs"; +import path from "node:path"; +import { renderJavaScriptVisitor, renderRustVisitor } from "@codama/renderers"; import { accountNode, booleanTypeNode, @@ -24,242 +24,248 @@ import { structFieldTypeNode, structTypeNode, variablePdaSeedNode, -} from 'codama'; +} from "codama"; -const _rustClientsDir = path.join(__dirname, '..', 'sdk', 'rust'); -const typescriptClientsDir = path.join(__dirname, '..', 'sdk', 'ts'); +const _rustClientsDir = path.join(__dirname, "..", "sdk", "rust"); +const typescriptClientsDir = path.join(__dirname, "..", "sdk", "ts"); const root = rootNode( programNode({ - name: 'block-list', - publicKey: 'BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf', - version: '1.0.0', + name: "block-list", + publicKey: "BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf", + version: "1.0.0", accounts: [ accountNode({ - name: 'config', - discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode('u8'), numberValueNode(0)))], + name: "config", + discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode("u8"), numberValueNode(0)))], size: 41, - pda: pdaLinkNode('config'), - docs: ['The config PDA account'], + pda: pdaLinkNode("config"), + docs: ["The config PDA account"], data: structTypeNode([ structFieldTypeNode({ - name: 'discriminator', - type: numberTypeNode('u8'), - defaultValueStrategy: 'omitted', + name: "discriminator", + type: numberTypeNode("u8"), + defaultValueStrategy: "omitted", }), structFieldTypeNode({ - name: 'authority', + name: "authority", type: publicKeyTypeNode(), }), structFieldTypeNode({ - name: 'blocked_wallets_count', - type: numberTypeNode('u64'), + name: "blocked_wallets_count", + type: numberTypeNode("u64"), }), ]), }), accountNode({ - name: 'walletBlock', - discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode('u8'), numberValueNode(1)))], + name: "walletBlock", + discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode("u8"), numberValueNode(1)))], size: 33, - pda: pdaLinkNode('walletBlock'), - docs: ['The config PDA account'], + pda: pdaLinkNode("walletBlock"), + docs: ["The config PDA account"], data: structTypeNode([ structFieldTypeNode({ - name: 'authority', + name: "authority", type: publicKeyTypeNode(), }), ]), }), accountNode({ - name: 'extraMetas', - pda: pdaLinkNode('extraMetas'), - docs: ['The extra metas PDA account'], + name: "extraMetas", + pda: pdaLinkNode("extraMetas"), + docs: ["The extra metas PDA account"], }), ], instructions: [ instructionNode({ - name: 'init', + name: "init", arguments: [ instructionArgumentNode({ - name: 'discriminator', - type: numberTypeNode('u8'), + name: "discriminator", + type: numberTypeNode("u8"), defaultValue: numberValueNode(0xf1), - defaultValueStrategy: 'omitted', + defaultValueStrategy: "omitted", }), ], accounts: [ instructionAccountNode({ - name: 'authority', + name: "authority", isSigner: true, isWritable: true, }), instructionAccountNode({ - name: 'config', + name: "config", isSigner: false, isWritable: true, - defaultValue: pdaValueNode(pdaLinkNode('config')), + defaultValue: pdaValueNode(pdaLinkNode("config")), }), instructionAccountNode({ - name: 'systemProgram', - defaultValue: publicKeyValueNode('11111111111111111111111111111111', 'systemProgram'), + name: "systemProgram", + defaultValue: publicKeyValueNode("11111111111111111111111111111111", "systemProgram"), isSigner: false, isWritable: false, }), ], - discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode('u8'), numberValueNode(0xf1)))], - docs: ['Initialize the config PDA account'], + discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode("u8"), numberValueNode(0xf1)))], + docs: ["Initialize the config PDA account"], }), instructionNode({ - name: 'blockWallet', + name: "blockWallet", arguments: [ instructionArgumentNode({ - name: 'discriminator', - type: numberTypeNode('u8'), + name: "discriminator", + type: numberTypeNode("u8"), defaultValue: numberValueNode(0xf2), - defaultValueStrategy: 'omitted', + defaultValueStrategy: "omitted", }), ], accounts: [ instructionAccountNode({ - name: 'authority', + name: "authority", isSigner: true, isWritable: true, }), instructionAccountNode({ - name: 'config', + name: "config", isSigner: false, isWritable: true, - defaultValue: pdaValueNode(pdaLinkNode('config')), + defaultValue: pdaValueNode(pdaLinkNode("config")), }), instructionAccountNode({ - name: 'wallet', + name: "wallet", isSigner: false, isWritable: false, }), instructionAccountNode({ - name: 'walletBlock', + name: "walletBlock", isSigner: false, isWritable: true, }), instructionAccountNode({ - name: 'systemProgram', - defaultValue: publicKeyValueNode('11111111111111111111111111111111', 'systemProgram'), + name: "systemProgram", + defaultValue: publicKeyValueNode("11111111111111111111111111111111", "systemProgram"), isSigner: false, isWritable: false, }), ], - discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode('u8'), numberValueNode(0xf2)))], - docs: ['Block a wallet'], + discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode("u8"), numberValueNode(0xf2)))], + docs: ["Block a wallet"], }), instructionNode({ - name: 'unblockWallet', + name: "unblockWallet", arguments: [ instructionArgumentNode({ - name: 'discriminator', - type: numberTypeNode('u8'), + name: "discriminator", + type: numberTypeNode("u8"), defaultValue: numberValueNode(0xf3), - defaultValueStrategy: 'omitted', + defaultValueStrategy: "omitted", }), ], accounts: [ instructionAccountNode({ - name: 'authority', + name: "authority", isSigner: true, isWritable: true, }), instructionAccountNode({ - name: 'config', + name: "config", isSigner: false, isWritable: true, - defaultValue: pdaValueNode(pdaLinkNode('config')), + defaultValue: pdaValueNode(pdaLinkNode("config")), }), instructionAccountNode({ - name: 'walletBlock', + name: "walletBlock", isSigner: false, isWritable: true, }), instructionAccountNode({ - name: 'systemProgram', - defaultValue: publicKeyValueNode('11111111111111111111111111111111', 'systemProgram'), + name: "systemProgram", + defaultValue: publicKeyValueNode("11111111111111111111111111111111", "systemProgram"), isSigner: false, isWritable: false, }), ], - discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode('u8'), numberValueNode(0xf3)))], - docs: ['Unblock a wallet'], + discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode("u8"), numberValueNode(0xf3)))], + docs: ["Unblock a wallet"], }), instructionNode({ - name: 'setupExtraMetas', + name: "setupExtraMetas", arguments: [ instructionArgumentNode({ - name: 'discriminator', - type: numberTypeNode('u8'), + name: "discriminator", + type: numberTypeNode("u8"), defaultValue: numberValueNode(0x6a), - defaultValueStrategy: 'omitted', + defaultValueStrategy: "omitted", }), instructionArgumentNode({ - name: 'checkBothWallets', + name: "checkBothWallets", type: booleanTypeNode(), defaultValue: booleanValueNode(false), - defaultValueStrategy: 'optional', + defaultValueStrategy: "optional", }), ], accounts: [ instructionAccountNode({ - name: 'authority', + name: "authority", isSigner: true, isWritable: true, }), instructionAccountNode({ - name: 'config', + name: "config", isSigner: false, isWritable: false, - defaultValue: pdaValueNode(pdaLinkNode('config')), + defaultValue: pdaValueNode(pdaLinkNode("config")), }), instructionAccountNode({ - name: 'mint', + name: "mint", isSigner: false, isWritable: false, }), instructionAccountNode({ - name: 'extraMetas', + name: "extraMetas", isSigner: false, isWritable: true, - defaultValue: pdaValueNode(pdaLinkNode('extraMetas')), + defaultValue: pdaValueNode(pdaLinkNode("extraMetas")), }), instructionAccountNode({ - name: 'systemProgram', - defaultValue: publicKeyValueNode('11111111111111111111111111111111', 'systemProgram'), + name: "systemProgram", + defaultValue: publicKeyValueNode("11111111111111111111111111111111", "systemProgram"), isSigner: false, isWritable: false, }), ], - discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode('u8'), numberValueNode(0x6a)))], - docs: ['Unblock a wallet'], + discriminators: [constantDiscriminatorNode(constantValueNode(numberTypeNode("u8"), numberValueNode(0x6a)))], + docs: ["Unblock a wallet"], }), ], pdas: [ pdaNode({ - name: 'config', - seeds: [constantPdaSeedNodeFromString('utf8', 'config')], - docs: ['The config PDA account'], + name: "config", + seeds: [constantPdaSeedNodeFromString("utf8", "config")], + docs: ["The config PDA account"], }), pdaNode({ - name: 'walletBlock', - seeds: [constantPdaSeedNodeFromString('utf8', 'wallet_block'), variablePdaSeedNode('wallet', publicKeyTypeNode())], - docs: ['The wallet block PDA account'], + name: "walletBlock", + seeds: [ + constantPdaSeedNodeFromString("utf8", "wallet_block"), + variablePdaSeedNode("wallet", publicKeyTypeNode()), + ], + docs: ["The wallet block PDA account"], }), pdaNode({ - name: 'extraMetas', - seeds: [constantPdaSeedNodeFromString('utf8', 'extra-account-metas'), variablePdaSeedNode('mint', publicKeyTypeNode())], - docs: ['The extra metas PDA account'], + name: "extraMetas", + seeds: [ + constantPdaSeedNodeFromString("utf8", "extra-account-metas"), + variablePdaSeedNode("mint", publicKeyTypeNode()), + ], + docs: ["The extra metas PDA account"], }), ], }), ); function preserveConfigFiles() { - const filesToPreserve = ['package.json', 'tsconfig.json', '.npmignore', 'pnpm-lock.yaml', 'Cargo.toml']; + const filesToPreserve = ["package.json", "tsconfig.json", ".npmignore", "pnpm-lock.yaml", "Cargo.toml"]; const preservedFiles = new Map(); for (const filename of filesToPreserve) { @@ -289,5 +295,10 @@ const codama = createFromRoot(root); const _configPreserver = preserveConfigFiles(); -codama.accept(renderJavaScriptVisitor('sdk/ts/src', { formatCode: true })); -codama.accept(renderRustVisitor('sdk/rust/src/client', { crateFolder: 'sdk/rust/', formatCode: true })); +codama.accept(renderJavaScriptVisitor("sdk/ts/src", { formatCode: true })); +codama.accept( + renderRustVisitor("sdk/rust/src/client", { + crateFolder: "sdk/rust/", + formatCode: true, + }), +); diff --git a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/accounts/config.ts b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/accounts/config.ts index d59757590..03a52b664 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/accounts/config.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/accounts/config.ts @@ -31,8 +31,8 @@ import { getU64Encoder, type MaybeAccount, type MaybeEncodedAccount, -} from '@solana/kit'; -import { findConfigPda } from '../pdas'; +} from "@solana/kit"; +import { findConfigPda } from "../pdas"; export const CONFIG_DISCRIMINATOR = 0; @@ -54,17 +54,17 @@ export type ConfigArgs = { export function getConfigEncoder(): Encoder { return getStructEncoder([ - ['discriminator', getU8Encoder()], - ['authority', getAddressEncoder()], - ['blockedWalletsCount', getU64Encoder()], + ["discriminator", getU8Encoder()], + ["authority", getAddressEncoder()], + ["blockedWalletsCount", getU64Encoder()], ]); } export function getConfigDecoder(): Decoder { return getStructDecoder([ - ['discriminator', getU8Decoder()], - ['authority', getAddressDecoder()], - ['blockedWalletsCount', getU64Decoder()], + ["discriminator", getU8Decoder()], + ["authority", getAddressDecoder()], + ["blockedWalletsCount", getU64Decoder()], ]); } @@ -72,8 +72,12 @@ export function getConfigCodec(): Codec { return combineCodec(getConfigEncoder(), getConfigDecoder()); } -export function decodeConfig(encodedAccount: EncodedAccount): Account; -export function decodeConfig(encodedAccount: MaybeEncodedAccount): MaybeAccount; +export function decodeConfig( + encodedAccount: EncodedAccount, +): Account; +export function decodeConfig( + encodedAccount: MaybeEncodedAccount, +): MaybeAccount; export function decodeConfig( encodedAccount: EncodedAccount | MaybeEncodedAccount, ): Account | MaybeAccount { diff --git a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/accounts/extraMetas.ts b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/accounts/extraMetas.ts index 3292ead79..93859232f 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/accounts/extraMetas.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/accounts/extraMetas.ts @@ -25,10 +25,10 @@ import { getStructEncoder, type MaybeAccount, type MaybeEncodedAccount, -} from '@solana/kit'; -import { ExtraMetasSeeds, findExtraMetasPda } from '../pdas'; +} from "@solana/kit"; +import { type ExtraMetasSeeds, findExtraMetasPda } from "../pdas"; -export type ExtraMetas = {}; +export type ExtraMetas = Record; export type ExtraMetasArgs = ExtraMetas; @@ -44,8 +44,12 @@ export function getExtraMetasCodec(): Codec { return combineCodec(getExtraMetasEncoder(), getExtraMetasDecoder()); } -export function decodeExtraMetas(encodedAccount: EncodedAccount): Account; -export function decodeExtraMetas(encodedAccount: MaybeEncodedAccount): MaybeAccount; +export function decodeExtraMetas( + encodedAccount: EncodedAccount, +): Account; +export function decodeExtraMetas( + encodedAccount: MaybeEncodedAccount, +): MaybeAccount; export function decodeExtraMetas( encodedAccount: EncodedAccount | MaybeEncodedAccount, ): Account | MaybeAccount { diff --git a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/accounts/index.ts b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/accounts/index.ts index ed620eb19..6135b7a67 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/accounts/index.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/accounts/index.ts @@ -6,6 +6,6 @@ * @see https://github.com/codama-idl/codama */ -export * from './config'; -export * from './extraMetas'; -export * from './walletBlock'; +export * from "./config"; +export * from "./extraMetas"; +export * from "./walletBlock"; diff --git a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/accounts/walletBlock.ts b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/accounts/walletBlock.ts index 886a73f79..29a8309a9 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/accounts/walletBlock.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/accounts/walletBlock.ts @@ -28,8 +28,8 @@ import { getU8Encoder, type MaybeAccount, type MaybeEncodedAccount, -} from '@solana/kit'; -import { findWalletBlockPda, WalletBlockSeeds } from '../pdas'; +} from "@solana/kit"; +import { findWalletBlockPda, type WalletBlockSeeds } from "../pdas"; export const WALLET_BLOCK_DISCRIMINATOR = 1; @@ -42,18 +42,20 @@ export type WalletBlock = { authority: Address }; export type WalletBlockArgs = WalletBlock; export function getWalletBlockEncoder(): Encoder { - return getStructEncoder([['authority', getAddressEncoder()]]); + return getStructEncoder([["authority", getAddressEncoder()]]); } export function getWalletBlockDecoder(): Decoder { - return getStructDecoder([['authority', getAddressDecoder()]]); + return getStructDecoder([["authority", getAddressDecoder()]]); } export function getWalletBlockCodec(): Codec { return combineCodec(getWalletBlockEncoder(), getWalletBlockDecoder()); } -export function decodeWalletBlock(encodedAccount: EncodedAccount): Account; +export function decodeWalletBlock( + encodedAccount: EncodedAccount, +): Account; export function decodeWalletBlock( encodedAccount: MaybeEncodedAccount, ): MaybeAccount; diff --git a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/index.ts b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/index.ts index 1002b8203..cf9bea234 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/index.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/index.ts @@ -6,7 +6,7 @@ * @see https://github.com/codama-idl/codama */ -export * from './accounts'; -export * from './instructions'; -export * from './pdas'; -export * from './programs'; +export * from "./accounts"; +export * from "./instructions"; +export * from "./pdas"; +export * from "./programs"; diff --git a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/blockWallet.ts b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/blockWallet.ts index b0f1d4d19..e49ba63b7 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/blockWallet.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/blockWallet.ts @@ -26,10 +26,10 @@ import { transformEncoder, type WritableAccount, type WritableSignerAccount, -} from '@solana/kit'; -import { findConfigPda } from '../pdas'; -import { BLOCK_LIST_PROGRAM_ADDRESS } from '../programs'; -import { getAccountMetaFactory, type ResolvedAccount } from '../shared'; +} from "@solana/kit"; +import { findConfigPda } from "../pdas"; +import { BLOCK_LIST_PROGRAM_ADDRESS } from "../programs"; +import { getAccountMetaFactory, type ResolvedAccount } from "../shared"; export const BLOCK_WALLET_DISCRIMINATOR = 242; @@ -43,13 +43,15 @@ export type BlockWalletInstruction< TAccountConfig extends string | IAccountMeta = string, TAccountWallet extends string | IAccountMeta = string, TAccountWalletBlock extends string | IAccountMeta = string, - TAccountSystemProgram extends string | IAccountMeta = '11111111111111111111111111111111', + TAccountSystemProgram extends string | IAccountMeta = "11111111111111111111111111111111", TRemainingAccounts extends readonly IAccountMeta[] = [], > = IInstruction & IInstructionWithData & IInstructionWithAccounts< [ - TAccountAuthority extends string ? WritableSignerAccount & IAccountSignerMeta : TAccountAuthority, + TAccountAuthority extends string + ? WritableSignerAccount & IAccountSignerMeta + : TAccountAuthority, TAccountConfig extends string ? WritableAccount : TAccountConfig, TAccountWallet extends string ? ReadonlyAccount : TAccountWallet, TAccountWalletBlock extends string ? WritableAccount : TAccountWalletBlock, @@ -60,17 +62,23 @@ export type BlockWalletInstruction< export type BlockWalletInstructionData = { discriminator: number }; -export type BlockWalletInstructionDataArgs = {}; +export type BlockWalletInstructionDataArgs = Record; export function getBlockWalletInstructionDataEncoder(): Encoder { - return transformEncoder(getStructEncoder([['discriminator', getU8Encoder()]]), (value) => ({ ...value, discriminator: 242 })); + return transformEncoder(getStructEncoder([["discriminator", getU8Encoder()]]), (value) => ({ + ...value, + discriminator: 242, + })); } export function getBlockWalletInstructionDataDecoder(): Decoder { - return getStructDecoder([['discriminator', getU8Decoder()]]); + return getStructDecoder([["discriminator", getU8Decoder()]]); } -export function getBlockWalletInstructionDataCodec(): Codec { +export function getBlockWalletInstructionDataCodec(): Codec< + BlockWalletInstructionDataArgs, + BlockWalletInstructionData +> { return combineCodec(getBlockWalletInstructionDataEncoder(), getBlockWalletInstructionDataDecoder()); } @@ -96,9 +104,24 @@ export async function getBlockWalletInstructionAsync< TAccountSystemProgram extends string, TProgramAddress extends Address = typeof BLOCK_LIST_PROGRAM_ADDRESS, >( - input: BlockWalletAsyncInput, + input: BlockWalletAsyncInput< + TAccountAuthority, + TAccountConfig, + TAccountWallet, + TAccountWalletBlock, + TAccountSystemProgram + >, config?: { programAddress?: TProgramAddress }, -): Promise> { +): Promise< + BlockWalletInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountWallet, + TAccountWalletBlock, + TAccountSystemProgram + > +> { // Program address. const programAddress = config?.programAddress ?? BLOCK_LIST_PROGRAM_ADDRESS; @@ -117,10 +140,10 @@ export async function getBlockWalletInstructionAsync< accounts.config.value = await findConfigPda(); } if (!accounts.systemProgram.value) { - accounts.systemProgram.value = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; + accounts.systemProgram.value = "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">; } - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); + const getAccountMeta = getAccountMetaFactory(programAddress, "programId"); const instruction = { accounts: [ getAccountMeta(accounts.authority), @@ -131,7 +154,14 @@ export async function getBlockWalletInstructionAsync< ], programAddress, data: getBlockWalletInstructionDataEncoder().encode({}), - } as BlockWalletInstruction; + } as BlockWalletInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountWallet, + TAccountWalletBlock, + TAccountSystemProgram + >; return instruction; } @@ -158,9 +188,22 @@ export function getBlockWalletInstruction< TAccountSystemProgram extends string, TProgramAddress extends Address = typeof BLOCK_LIST_PROGRAM_ADDRESS, >( - input: BlockWalletInput, + input: BlockWalletInput< + TAccountAuthority, + TAccountConfig, + TAccountWallet, + TAccountWalletBlock, + TAccountSystemProgram + >, config?: { programAddress?: TProgramAddress }, -): BlockWalletInstruction { +): BlockWalletInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountWallet, + TAccountWalletBlock, + TAccountSystemProgram +> { // Program address. const programAddress = config?.programAddress ?? BLOCK_LIST_PROGRAM_ADDRESS; @@ -176,10 +219,10 @@ export function getBlockWalletInstruction< // Resolve default values. if (!accounts.systemProgram.value) { - accounts.systemProgram.value = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; + accounts.systemProgram.value = "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">; } - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); + const getAccountMeta = getAccountMetaFactory(programAddress, "programId"); const instruction = { accounts: [ getAccountMeta(accounts.authority), @@ -190,7 +233,14 @@ export function getBlockWalletInstruction< ], programAddress, data: getBlockWalletInstructionDataEncoder().encode({}), - } as BlockWalletInstruction; + } as BlockWalletInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountWallet, + TAccountWalletBlock, + TAccountSystemProgram + >; return instruction; } @@ -215,11 +265,11 @@ export function parseBlockWalletInstruction { if (instruction.accounts.length < 5) { // TODO: Coded error. - throw new Error('Not enough accounts'); + throw new Error("Not enough accounts"); } let accountIndex = 0; const getNextAccount = () => { - const accountMeta = instruction.accounts?.[accountIndex]!; + const accountMeta = instruction.accounts[accountIndex]; accountIndex += 1; return accountMeta; }; diff --git a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/index.ts b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/index.ts index 864cb10b3..f4bba88c5 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/index.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/index.ts @@ -6,7 +6,7 @@ * @see https://github.com/codama-idl/codama */ -export * from './blockWallet'; -export * from './init'; -export * from './setupExtraMetas'; -export * from './unblockWallet'; +export * from "./blockWallet"; +export * from "./init"; +export * from "./setupExtraMetas"; +export * from "./unblockWallet"; diff --git a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/init.ts b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/init.ts index f02a8fe63..860840983 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/init.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/init.ts @@ -26,10 +26,10 @@ import { transformEncoder, type WritableAccount, type WritableSignerAccount, -} from '@solana/kit'; -import { findConfigPda } from '../pdas'; -import { BLOCK_LIST_PROGRAM_ADDRESS } from '../programs'; -import { getAccountMetaFactory, type ResolvedAccount } from '../shared'; +} from "@solana/kit"; +import { findConfigPda } from "../pdas"; +import { BLOCK_LIST_PROGRAM_ADDRESS } from "../programs"; +import { getAccountMetaFactory, type ResolvedAccount } from "../shared"; export const INIT_DISCRIMINATOR = 241; @@ -41,13 +41,15 @@ export type InitInstruction< TProgram extends string = typeof BLOCK_LIST_PROGRAM_ADDRESS, TAccountAuthority extends string | IAccountMeta = string, TAccountConfig extends string | IAccountMeta = string, - TAccountSystemProgram extends string | IAccountMeta = '11111111111111111111111111111111', + TAccountSystemProgram extends string | IAccountMeta = "11111111111111111111111111111111", TRemainingAccounts extends readonly IAccountMeta[] = [], > = IInstruction & IInstructionWithData & IInstructionWithAccounts< [ - TAccountAuthority extends string ? WritableSignerAccount & IAccountSignerMeta : TAccountAuthority, + TAccountAuthority extends string + ? WritableSignerAccount & IAccountSignerMeta + : TAccountAuthority, TAccountConfig extends string ? WritableAccount : TAccountConfig, TAccountSystemProgram extends string ? ReadonlyAccount : TAccountSystemProgram, ...TRemainingAccounts, @@ -56,14 +58,17 @@ export type InitInstruction< export type InitInstructionData = { discriminator: number }; -export type InitInstructionDataArgs = {}; +export type InitInstructionDataArgs = Record; export function getInitInstructionDataEncoder(): Encoder { - return transformEncoder(getStructEncoder([['discriminator', getU8Encoder()]]), (value) => ({ ...value, discriminator: 241 })); + return transformEncoder(getStructEncoder([["discriminator", getU8Encoder()]]), (value) => ({ + ...value, + discriminator: 241, + })); } export function getInitInstructionDataDecoder(): Decoder { - return getStructDecoder([['discriminator', getU8Decoder()]]); + return getStructDecoder([["discriminator", getU8Decoder()]]); } export function getInitInstructionDataCodec(): Codec { @@ -105,12 +110,16 @@ export async function getInitInstructionAsync< accounts.config.value = await findConfigPda(); } if (!accounts.systemProgram.value) { - accounts.systemProgram.value = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; + accounts.systemProgram.value = "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">; } - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); + const getAccountMeta = getAccountMetaFactory(programAddress, "programId"); const instruction = { - accounts: [getAccountMeta(accounts.authority), getAccountMeta(accounts.config), getAccountMeta(accounts.systemProgram)], + accounts: [ + getAccountMeta(accounts.authority), + getAccountMeta(accounts.config), + getAccountMeta(accounts.systemProgram), + ], programAddress, data: getInitInstructionDataEncoder().encode({}), } as InitInstruction; @@ -150,12 +159,16 @@ export function getInitInstruction< // Resolve default values. if (!accounts.systemProgram.value) { - accounts.systemProgram.value = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; + accounts.systemProgram.value = "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">; } - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); + const getAccountMeta = getAccountMetaFactory(programAddress, "programId"); const instruction = { - accounts: [getAccountMeta(accounts.authority), getAccountMeta(accounts.config), getAccountMeta(accounts.systemProgram)], + accounts: [ + getAccountMeta(accounts.authority), + getAccountMeta(accounts.config), + getAccountMeta(accounts.systemProgram), + ], programAddress, data: getInitInstructionDataEncoder().encode({}), } as InitInstruction; @@ -181,11 +194,11 @@ export function parseInitInstruction { if (instruction.accounts.length < 3) { // TODO: Coded error. - throw new Error('Not enough accounts'); + throw new Error("Not enough accounts"); } let accountIndex = 0; const getNextAccount = () => { - const accountMeta = instruction.accounts?.[accountIndex]!; + const accountMeta = instruction.accounts[accountIndex]; accountIndex += 1; return accountMeta; }; diff --git a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/setupExtraMetas.ts b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/setupExtraMetas.ts index 021e6729c..c9004cd3b 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/setupExtraMetas.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/setupExtraMetas.ts @@ -28,10 +28,10 @@ import { transformEncoder, type WritableAccount, type WritableSignerAccount, -} from '@solana/kit'; -import { findConfigPda, findExtraMetasPda } from '../pdas'; -import { BLOCK_LIST_PROGRAM_ADDRESS } from '../programs'; -import { getAccountMetaFactory, type ResolvedAccount } from '../shared'; +} from "@solana/kit"; +import { findConfigPda, findExtraMetasPda } from "../pdas"; +import { BLOCK_LIST_PROGRAM_ADDRESS } from "../programs"; +import { getAccountMetaFactory, type ResolvedAccount } from "../shared"; export const SETUP_EXTRA_METAS_DISCRIMINATOR = 106; @@ -45,13 +45,15 @@ export type SetupExtraMetasInstruction< TAccountConfig extends string | IAccountMeta = string, TAccountMint extends string | IAccountMeta = string, TAccountExtraMetas extends string | IAccountMeta = string, - TAccountSystemProgram extends string | IAccountMeta = '11111111111111111111111111111111', + TAccountSystemProgram extends string | IAccountMeta = "11111111111111111111111111111111", TRemainingAccounts extends readonly IAccountMeta[] = [], > = IInstruction & IInstructionWithData & IInstructionWithAccounts< [ - TAccountAuthority extends string ? WritableSignerAccount & IAccountSignerMeta : TAccountAuthority, + TAccountAuthority extends string + ? WritableSignerAccount & IAccountSignerMeta + : TAccountAuthority, TAccountConfig extends string ? ReadonlyAccount : TAccountConfig, TAccountMint extends string ? ReadonlyAccount : TAccountMint, TAccountExtraMetas extends string ? WritableAccount : TAccountExtraMetas, @@ -70,8 +72,8 @@ export type SetupExtraMetasInstructionDataArgs = { checkBothWallets?: boolean }; export function getSetupExtraMetasInstructionDataEncoder(): Encoder { return transformEncoder( getStructEncoder([ - ['discriminator', getU8Encoder()], - ['checkBothWallets', getBooleanEncoder()], + ["discriminator", getU8Encoder()], + ["checkBothWallets", getBooleanEncoder()], ]), (value) => ({ ...value, @@ -83,12 +85,15 @@ export function getSetupExtraMetasInstructionDataEncoder(): Encoder { return getStructDecoder([ - ['discriminator', getU8Decoder()], - ['checkBothWallets', getBooleanDecoder()], + ["discriminator", getU8Decoder()], + ["checkBothWallets", getBooleanDecoder()], ]); } -export function getSetupExtraMetasInstructionDataCodec(): Codec { +export function getSetupExtraMetasInstructionDataCodec(): Codec< + SetupExtraMetasInstructionDataArgs, + SetupExtraMetasInstructionData +> { return combineCodec(getSetupExtraMetasInstructionDataEncoder(), getSetupExtraMetasInstructionDataDecoder()); } @@ -104,7 +109,7 @@ export type SetupExtraMetasAsyncInput< mint: Address; extraMetas?: Address; systemProgram?: Address; - checkBothWallets?: SetupExtraMetasInstructionDataArgs['checkBothWallets']; + checkBothWallets?: SetupExtraMetasInstructionDataArgs["checkBothWallets"]; }; export async function getSetupExtraMetasInstructionAsync< @@ -115,9 +120,24 @@ export async function getSetupExtraMetasInstructionAsync< TAccountSystemProgram extends string, TProgramAddress extends Address = typeof BLOCK_LIST_PROGRAM_ADDRESS, >( - input: SetupExtraMetasAsyncInput, + input: SetupExtraMetasAsyncInput< + TAccountAuthority, + TAccountConfig, + TAccountMint, + TAccountExtraMetas, + TAccountSystemProgram + >, config?: { programAddress?: TProgramAddress }, -): Promise> { +): Promise< + SetupExtraMetasInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountMint, + TAccountExtraMetas, + TAccountSystemProgram + > +> { // Program address. const programAddress = config?.programAddress ?? BLOCK_LIST_PROGRAM_ADDRESS; @@ -142,10 +162,10 @@ export async function getSetupExtraMetasInstructionAsync< accounts.extraMetas.value = await findExtraMetasPda(); } if (!accounts.systemProgram.value) { - accounts.systemProgram.value = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; + accounts.systemProgram.value = "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">; } - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); + const getAccountMeta = getAccountMetaFactory(programAddress, "programId"); const instruction = { accounts: [ getAccountMeta(accounts.authority), @@ -156,7 +176,14 @@ export async function getSetupExtraMetasInstructionAsync< ], programAddress, data: getSetupExtraMetasInstructionDataEncoder().encode(args as SetupExtraMetasInstructionDataArgs), - } as SetupExtraMetasInstruction; + } as SetupExtraMetasInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountMint, + TAccountExtraMetas, + TAccountSystemProgram + >; return instruction; } @@ -173,7 +200,7 @@ export type SetupExtraMetasInput< mint: Address; extraMetas: Address; systemProgram?: Address; - checkBothWallets?: SetupExtraMetasInstructionDataArgs['checkBothWallets']; + checkBothWallets?: SetupExtraMetasInstructionDataArgs["checkBothWallets"]; }; export function getSetupExtraMetasInstruction< @@ -184,9 +211,22 @@ export function getSetupExtraMetasInstruction< TAccountSystemProgram extends string, TProgramAddress extends Address = typeof BLOCK_LIST_PROGRAM_ADDRESS, >( - input: SetupExtraMetasInput, + input: SetupExtraMetasInput< + TAccountAuthority, + TAccountConfig, + TAccountMint, + TAccountExtraMetas, + TAccountSystemProgram + >, config?: { programAddress?: TProgramAddress }, -): SetupExtraMetasInstruction { +): SetupExtraMetasInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountMint, + TAccountExtraMetas, + TAccountSystemProgram +> { // Program address. const programAddress = config?.programAddress ?? BLOCK_LIST_PROGRAM_ADDRESS; @@ -205,10 +245,10 @@ export function getSetupExtraMetasInstruction< // Resolve default values. if (!accounts.systemProgram.value) { - accounts.systemProgram.value = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; + accounts.systemProgram.value = "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">; } - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); + const getAccountMeta = getAccountMetaFactory(programAddress, "programId"); const instruction = { accounts: [ getAccountMeta(accounts.authority), @@ -219,7 +259,14 @@ export function getSetupExtraMetasInstruction< ], programAddress, data: getSetupExtraMetasInstructionDataEncoder().encode(args as SetupExtraMetasInstructionDataArgs), - } as SetupExtraMetasInstruction; + } as SetupExtraMetasInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountMint, + TAccountExtraMetas, + TAccountSystemProgram + >; return instruction; } @@ -244,11 +291,11 @@ export function parseSetupExtraMetasInstruction { if (instruction.accounts.length < 5) { // TODO: Coded error. - throw new Error('Not enough accounts'); + throw new Error("Not enough accounts"); } let accountIndex = 0; const getNextAccount = () => { - const accountMeta = instruction.accounts?.[accountIndex]!; + const accountMeta = instruction.accounts[accountIndex]; accountIndex += 1; return accountMeta; }; diff --git a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/unblockWallet.ts b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/unblockWallet.ts index d17158efe..40b3f33f0 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/unblockWallet.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/instructions/unblockWallet.ts @@ -26,10 +26,10 @@ import { transformEncoder, type WritableAccount, type WritableSignerAccount, -} from '@solana/kit'; -import { findConfigPda } from '../pdas'; -import { BLOCK_LIST_PROGRAM_ADDRESS } from '../programs'; -import { getAccountMetaFactory, type ResolvedAccount } from '../shared'; +} from "@solana/kit"; +import { findConfigPda } from "../pdas"; +import { BLOCK_LIST_PROGRAM_ADDRESS } from "../programs"; +import { getAccountMetaFactory, type ResolvedAccount } from "../shared"; export const UNBLOCK_WALLET_DISCRIMINATOR = 243; @@ -42,13 +42,15 @@ export type UnblockWalletInstruction< TAccountAuthority extends string | IAccountMeta = string, TAccountConfig extends string | IAccountMeta = string, TAccountWalletBlock extends string | IAccountMeta = string, - TAccountSystemProgram extends string | IAccountMeta = '11111111111111111111111111111111', + TAccountSystemProgram extends string | IAccountMeta = "11111111111111111111111111111111", TRemainingAccounts extends readonly IAccountMeta[] = [], > = IInstruction & IInstructionWithData & IInstructionWithAccounts< [ - TAccountAuthority extends string ? WritableSignerAccount & IAccountSignerMeta : TAccountAuthority, + TAccountAuthority extends string + ? WritableSignerAccount & IAccountSignerMeta + : TAccountAuthority, TAccountConfig extends string ? WritableAccount : TAccountConfig, TAccountWalletBlock extends string ? WritableAccount : TAccountWalletBlock, TAccountSystemProgram extends string ? ReadonlyAccount : TAccountSystemProgram, @@ -58,17 +60,23 @@ export type UnblockWalletInstruction< export type UnblockWalletInstructionData = { discriminator: number }; -export type UnblockWalletInstructionDataArgs = {}; +export type UnblockWalletInstructionDataArgs = Record; export function getUnblockWalletInstructionDataEncoder(): Encoder { - return transformEncoder(getStructEncoder([['discriminator', getU8Encoder()]]), (value) => ({ ...value, discriminator: 243 })); + return transformEncoder(getStructEncoder([["discriminator", getU8Encoder()]]), (value) => ({ + ...value, + discriminator: 243, + })); } export function getUnblockWalletInstructionDataDecoder(): Decoder { - return getStructDecoder([['discriminator', getU8Decoder()]]); + return getStructDecoder([["discriminator", getU8Decoder()]]); } -export function getUnblockWalletInstructionDataCodec(): Codec { +export function getUnblockWalletInstructionDataCodec(): Codec< + UnblockWalletInstructionDataArgs, + UnblockWalletInstructionData +> { return combineCodec(getUnblockWalletInstructionDataEncoder(), getUnblockWalletInstructionDataDecoder()); } @@ -93,7 +101,15 @@ export async function getUnblockWalletInstructionAsync< >( input: UnblockWalletAsyncInput, config?: { programAddress?: TProgramAddress }, -): Promise> { +): Promise< + UnblockWalletInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountWalletBlock, + TAccountSystemProgram + > +> { // Program address. const programAddress = config?.programAddress ?? BLOCK_LIST_PROGRAM_ADDRESS; @@ -111,10 +127,10 @@ export async function getUnblockWalletInstructionAsync< accounts.config.value = await findConfigPda(); } if (!accounts.systemProgram.value) { - accounts.systemProgram.value = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; + accounts.systemProgram.value = "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">; } - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); + const getAccountMeta = getAccountMetaFactory(programAddress, "programId"); const instruction = { accounts: [ getAccountMeta(accounts.authority), @@ -124,7 +140,13 @@ export async function getUnblockWalletInstructionAsync< ], programAddress, data: getUnblockWalletInstructionDataEncoder().encode({}), - } as UnblockWalletInstruction; + } as UnblockWalletInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountWalletBlock, + TAccountSystemProgram + >; return instruction; } @@ -150,7 +172,13 @@ export function getUnblockWalletInstruction< >( input: UnblockWalletInput, config?: { programAddress?: TProgramAddress }, -): UnblockWalletInstruction { +): UnblockWalletInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountWalletBlock, + TAccountSystemProgram +> { // Program address. const programAddress = config?.programAddress ?? BLOCK_LIST_PROGRAM_ADDRESS; @@ -165,10 +193,10 @@ export function getUnblockWalletInstruction< // Resolve default values. if (!accounts.systemProgram.value) { - accounts.systemProgram.value = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; + accounts.systemProgram.value = "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">; } - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); + const getAccountMeta = getAccountMetaFactory(programAddress, "programId"); const instruction = { accounts: [ getAccountMeta(accounts.authority), @@ -178,7 +206,13 @@ export function getUnblockWalletInstruction< ], programAddress, data: getUnblockWalletInstructionDataEncoder().encode({}), - } as UnblockWalletInstruction; + } as UnblockWalletInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountWalletBlock, + TAccountSystemProgram + >; return instruction; } @@ -202,11 +236,11 @@ export function parseUnblockWalletInstruction { if (instruction.accounts.length < 4) { // TODO: Coded error. - throw new Error('Not enough accounts'); + throw new Error("Not enough accounts"); } let accountIndex = 0; const getNextAccount = () => { - const accountMeta = instruction.accounts?.[accountIndex]!; + const accountMeta = instruction.accounts[accountIndex]; accountIndex += 1; return accountMeta; }; diff --git a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/pdas/config.ts b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/pdas/config.ts index 343f6f4ce..be83310f6 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/pdas/config.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/pdas/config.ts @@ -6,12 +6,16 @@ * @see https://github.com/codama-idl/codama */ -import { type Address, getProgramDerivedAddress, getUtf8Encoder, type ProgramDerivedAddress } from '@solana/kit'; +import { type Address, getProgramDerivedAddress, getUtf8Encoder, type ProgramDerivedAddress } from "@solana/kit"; -export async function findConfigPda(config: { programAddress?: Address | undefined } = {}): Promise { - const { programAddress = 'BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf' as Address<'BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf'> } = config; +export async function findConfigPda( + config: { programAddress?: Address | undefined } = {}, +): Promise { + const { + programAddress = "BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf" as Address<"BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf">, + } = config; return await getProgramDerivedAddress({ programAddress, - seeds: [getUtf8Encoder().encode('config')], + seeds: [getUtf8Encoder().encode("config")], }); } diff --git a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/pdas/extraMetas.ts b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/pdas/extraMetas.ts index a66a9d189..db4a84483 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/pdas/extraMetas.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/pdas/extraMetas.ts @@ -6,7 +6,13 @@ * @see https://github.com/codama-idl/codama */ -import { type Address, getAddressEncoder, getProgramDerivedAddress, getUtf8Encoder, type ProgramDerivedAddress } from '@solana/kit'; +import { + type Address, + getAddressEncoder, + getProgramDerivedAddress, + getUtf8Encoder, + type ProgramDerivedAddress, +} from "@solana/kit"; export type ExtraMetasSeeds = { mint: Address; @@ -16,9 +22,11 @@ export async function findExtraMetasPda( seeds: ExtraMetasSeeds, config: { programAddress?: Address | undefined } = {}, ): Promise { - const { programAddress = 'BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf' as Address<'BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf'> } = config; + const { + programAddress = "BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf" as Address<"BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf">, + } = config; return await getProgramDerivedAddress({ programAddress, - seeds: [getUtf8Encoder().encode('extra-account-metas'), getAddressEncoder().encode(seeds.mint)], + seeds: [getUtf8Encoder().encode("extra-account-metas"), getAddressEncoder().encode(seeds.mint)], }); } diff --git a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/pdas/index.ts b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/pdas/index.ts index ed620eb19..6135b7a67 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/pdas/index.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/pdas/index.ts @@ -6,6 +6,6 @@ * @see https://github.com/codama-idl/codama */ -export * from './config'; -export * from './extraMetas'; -export * from './walletBlock'; +export * from "./config"; +export * from "./extraMetas"; +export * from "./walletBlock"; diff --git a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/pdas/walletBlock.ts b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/pdas/walletBlock.ts index 1a5e84096..2705fbcef 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/pdas/walletBlock.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/pdas/walletBlock.ts @@ -6,7 +6,13 @@ * @see https://github.com/codama-idl/codama */ -import { type Address, getAddressEncoder, getProgramDerivedAddress, getUtf8Encoder, type ProgramDerivedAddress } from '@solana/kit'; +import { + type Address, + getAddressEncoder, + getProgramDerivedAddress, + getUtf8Encoder, + type ProgramDerivedAddress, +} from "@solana/kit"; export type WalletBlockSeeds = { wallet: Address; @@ -16,9 +22,11 @@ export async function findWalletBlockPda( seeds: WalletBlockSeeds, config: { programAddress?: Address | undefined } = {}, ): Promise { - const { programAddress = 'BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf' as Address<'BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf'> } = config; + const { + programAddress = "BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf" as Address<"BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf">, + } = config; return await getProgramDerivedAddress({ programAddress, - seeds: [getUtf8Encoder().encode('wallet_block'), getAddressEncoder().encode(seeds.wallet)], + seeds: [getUtf8Encoder().encode("wallet_block"), getAddressEncoder().encode(seeds.wallet)], }); } diff --git a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/programs/blockList.ts b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/programs/blockList.ts index 4ba42d741..d22c9ccf9 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/programs/blockList.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/programs/blockList.ts @@ -6,15 +6,16 @@ * @see https://github.com/codama-idl/codama */ -import { type Address, containsBytes, getU8Encoder, type ReadonlyUint8Array } from '@solana/kit'; -import { - type ParsedBlockWalletInstruction, - type ParsedInitInstruction, - type ParsedSetupExtraMetasInstruction, - type ParsedUnblockWalletInstruction, -} from '../instructions'; +import { type Address, containsBytes, getU8Encoder, type ReadonlyUint8Array } from "@solana/kit"; +import type { + ParsedBlockWalletInstruction, + ParsedInitInstruction, + ParsedSetupExtraMetasInstruction, + ParsedUnblockWalletInstruction, +} from "../instructions"; -export const BLOCK_LIST_PROGRAM_ADDRESS = 'BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf' as Address<'BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf'>; +export const BLOCK_LIST_PROGRAM_ADDRESS = + "BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf" as Address<"BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf">; export enum BlockListAccount { Config, @@ -23,14 +24,14 @@ export enum BlockListAccount { } export function identifyBlockListAccount(account: { data: ReadonlyUint8Array } | ReadonlyUint8Array): BlockListAccount { - const data = 'data' in account ? account.data : account; + const data = "data" in account ? account.data : account; if (containsBytes(data, getU8Encoder().encode(0), 0)) { return BlockListAccount.Config; } if (containsBytes(data, getU8Encoder().encode(1), 0)) { return BlockListAccount.WalletBlock; } - throw new Error('The provided account could not be identified as a blockList account.'); + throw new Error("The provided account could not be identified as a blockList account."); } export enum BlockListInstruction { @@ -40,8 +41,10 @@ export enum BlockListInstruction { SetupExtraMetas, } -export function identifyBlockListInstruction(instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array): BlockListInstruction { - const data = 'data' in instruction ? instruction.data : instruction; +export function identifyBlockListInstruction( + instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array, +): BlockListInstruction { + const data = "data" in instruction ? instruction.data : instruction; if (containsBytes(data, getU8Encoder().encode(241), 0)) { return BlockListInstruction.Init; } @@ -54,10 +57,10 @@ export function identifyBlockListInstruction(instruction: { data: ReadonlyUint8A if (containsBytes(data, getU8Encoder().encode(106), 0)) { return BlockListInstruction.SetupExtraMetas; } - throw new Error('The provided instruction could not be identified as a blockList instruction.'); + throw new Error("The provided instruction could not be identified as a blockList instruction."); } -export type ParsedBlockListInstruction = +export type ParsedBlockListInstruction = | ({ instructionType: BlockListInstruction.Init; } & ParsedInitInstruction) diff --git a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/programs/index.ts b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/programs/index.ts index f945615bd..01ddfbdee 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/programs/index.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/programs/index.ts @@ -6,4 +6,4 @@ * @see https://github.com/codama-idl/codama */ -export * from './blockList'; +export * from "./blockList"; diff --git a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/shared/index.ts b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/shared/index.ts index 27141fc40..6b3bc4a6a 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/shared/index.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/pino/sdk/ts/src/shared/index.ts @@ -16,7 +16,7 @@ import { type ProgramDerivedAddress, type TransactionSigner, upgradeRoleToSigner, -} from '@solana/kit'; +} from "@solana/kit"; /** * Asserts that the given value is not null or undefined. @@ -24,7 +24,7 @@ import { */ export function expectSome(value: T | null | undefined): T { if (value == null) { - throw new Error('Expected a value but received null or undefined.'); + throw new Error("Expected a value but received null or undefined."); } return value; } @@ -37,9 +37,9 @@ export function expectAddress( value: Address | ProgramDerivedAddress | TransactionSigner | null | undefined, ): Address { if (!value) { - throw new Error('Expected a Address.'); + throw new Error("Expected a Address."); } - if (typeof value === 'object' && 'address' in value) { + if (typeof value === "object" && "address" in value) { return value.address; } if (Array.isArray(value)) { @@ -56,7 +56,7 @@ export function expectProgramDerivedAddress( value: Address | ProgramDerivedAddress | TransactionSigner | null | undefined, ): ProgramDerivedAddress { if (!value || !Array.isArray(value) || !isProgramDerivedAddress(value)) { - throw new Error('Expected a ProgramDerivedAddress.'); + throw new Error("Expected a ProgramDerivedAddress."); } return value; } @@ -69,7 +69,7 @@ export function expectTransactionSigner( value: Address | ProgramDerivedAddress | TransactionSigner | null | undefined, ): TransactionSigner { if (!value || !isTransactionSigner(value)) { - throw new Error('Expected a TransactionSigner.'); + throw new Error("Expected a TransactionSigner."); } return value; } @@ -80,7 +80,11 @@ export function expectTransactionSigner( */ export type ResolvedAccount< T extends string = string, - U extends Address | ProgramDerivedAddress | TransactionSigner | null = Address | ProgramDerivedAddress | TransactionSigner | null, + U extends Address | ProgramDerivedAddress | TransactionSigner | null = + | Address + | ProgramDerivedAddress + | TransactionSigner + | null, > = { isWritable: boolean; value: U; @@ -98,10 +102,10 @@ export type IInstructionWithByteDelta = { * Get account metas and signers from resolved accounts. * @internal */ -export function getAccountMetaFactory(programAddress: Address, optionalAccountStrategy: 'omitted' | 'programId') { +export function getAccountMetaFactory(programAddress: Address, optionalAccountStrategy: "omitted" | "programId") { return (account: ResolvedAccount): IAccountMeta | IAccountSignerMeta | undefined => { if (!account.value) { - if (optionalAccountStrategy === 'omitted') return; + if (optionalAccountStrategy === "omitted") return; return Object.freeze({ address: programAddress, role: AccountRole.READONLY, @@ -120,5 +124,5 @@ export function getAccountMetaFactory(programAddress: Address, optionalAccountSt export function isTransactionSigner( value: Address | ProgramDerivedAddress | TransactionSigner, ): value is TransactionSigner { - return !!value && typeof value === 'object' && 'address' in value && kitIsTransactionSigner(value); + return !!value && typeof value === "object" && "address" in value && kitIsTransactionSigner(value); } diff --git a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/accounts/config.ts b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/accounts/config.ts index d59757590..03a52b664 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/accounts/config.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/accounts/config.ts @@ -31,8 +31,8 @@ import { getU64Encoder, type MaybeAccount, type MaybeEncodedAccount, -} from '@solana/kit'; -import { findConfigPda } from '../pdas'; +} from "@solana/kit"; +import { findConfigPda } from "../pdas"; export const CONFIG_DISCRIMINATOR = 0; @@ -54,17 +54,17 @@ export type ConfigArgs = { export function getConfigEncoder(): Encoder { return getStructEncoder([ - ['discriminator', getU8Encoder()], - ['authority', getAddressEncoder()], - ['blockedWalletsCount', getU64Encoder()], + ["discriminator", getU8Encoder()], + ["authority", getAddressEncoder()], + ["blockedWalletsCount", getU64Encoder()], ]); } export function getConfigDecoder(): Decoder { return getStructDecoder([ - ['discriminator', getU8Decoder()], - ['authority', getAddressDecoder()], - ['blockedWalletsCount', getU64Decoder()], + ["discriminator", getU8Decoder()], + ["authority", getAddressDecoder()], + ["blockedWalletsCount", getU64Decoder()], ]); } @@ -72,8 +72,12 @@ export function getConfigCodec(): Codec { return combineCodec(getConfigEncoder(), getConfigDecoder()); } -export function decodeConfig(encodedAccount: EncodedAccount): Account; -export function decodeConfig(encodedAccount: MaybeEncodedAccount): MaybeAccount; +export function decodeConfig( + encodedAccount: EncodedAccount, +): Account; +export function decodeConfig( + encodedAccount: MaybeEncodedAccount, +): MaybeAccount; export function decodeConfig( encodedAccount: EncodedAccount | MaybeEncodedAccount, ): Account | MaybeAccount { diff --git a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/accounts/extraMetas.ts b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/accounts/extraMetas.ts index 3292ead79..93859232f 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/accounts/extraMetas.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/accounts/extraMetas.ts @@ -25,10 +25,10 @@ import { getStructEncoder, type MaybeAccount, type MaybeEncodedAccount, -} from '@solana/kit'; -import { ExtraMetasSeeds, findExtraMetasPda } from '../pdas'; +} from "@solana/kit"; +import { type ExtraMetasSeeds, findExtraMetasPda } from "../pdas"; -export type ExtraMetas = {}; +export type ExtraMetas = Record; export type ExtraMetasArgs = ExtraMetas; @@ -44,8 +44,12 @@ export function getExtraMetasCodec(): Codec { return combineCodec(getExtraMetasEncoder(), getExtraMetasDecoder()); } -export function decodeExtraMetas(encodedAccount: EncodedAccount): Account; -export function decodeExtraMetas(encodedAccount: MaybeEncodedAccount): MaybeAccount; +export function decodeExtraMetas( + encodedAccount: EncodedAccount, +): Account; +export function decodeExtraMetas( + encodedAccount: MaybeEncodedAccount, +): MaybeAccount; export function decodeExtraMetas( encodedAccount: EncodedAccount | MaybeEncodedAccount, ): Account | MaybeAccount { diff --git a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/accounts/index.ts b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/accounts/index.ts index ed620eb19..6135b7a67 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/accounts/index.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/accounts/index.ts @@ -6,6 +6,6 @@ * @see https://github.com/codama-idl/codama */ -export * from './config'; -export * from './extraMetas'; -export * from './walletBlock'; +export * from "./config"; +export * from "./extraMetas"; +export * from "./walletBlock"; diff --git a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/accounts/walletBlock.ts b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/accounts/walletBlock.ts index 886a73f79..29a8309a9 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/accounts/walletBlock.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/accounts/walletBlock.ts @@ -28,8 +28,8 @@ import { getU8Encoder, type MaybeAccount, type MaybeEncodedAccount, -} from '@solana/kit'; -import { findWalletBlockPda, WalletBlockSeeds } from '../pdas'; +} from "@solana/kit"; +import { findWalletBlockPda, type WalletBlockSeeds } from "../pdas"; export const WALLET_BLOCK_DISCRIMINATOR = 1; @@ -42,18 +42,20 @@ export type WalletBlock = { authority: Address }; export type WalletBlockArgs = WalletBlock; export function getWalletBlockEncoder(): Encoder { - return getStructEncoder([['authority', getAddressEncoder()]]); + return getStructEncoder([["authority", getAddressEncoder()]]); } export function getWalletBlockDecoder(): Decoder { - return getStructDecoder([['authority', getAddressDecoder()]]); + return getStructDecoder([["authority", getAddressDecoder()]]); } export function getWalletBlockCodec(): Codec { return combineCodec(getWalletBlockEncoder(), getWalletBlockDecoder()); } -export function decodeWalletBlock(encodedAccount: EncodedAccount): Account; +export function decodeWalletBlock( + encodedAccount: EncodedAccount, +): Account; export function decodeWalletBlock( encodedAccount: MaybeEncodedAccount, ): MaybeAccount; diff --git a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/index.ts b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/index.ts index 1002b8203..cf9bea234 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/index.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/index.ts @@ -6,7 +6,7 @@ * @see https://github.com/codama-idl/codama */ -export * from './accounts'; -export * from './instructions'; -export * from './pdas'; -export * from './programs'; +export * from "./accounts"; +export * from "./instructions"; +export * from "./pdas"; +export * from "./programs"; diff --git a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/blockWallet.ts b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/blockWallet.ts index b0f1d4d19..e49ba63b7 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/blockWallet.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/blockWallet.ts @@ -26,10 +26,10 @@ import { transformEncoder, type WritableAccount, type WritableSignerAccount, -} from '@solana/kit'; -import { findConfigPda } from '../pdas'; -import { BLOCK_LIST_PROGRAM_ADDRESS } from '../programs'; -import { getAccountMetaFactory, type ResolvedAccount } from '../shared'; +} from "@solana/kit"; +import { findConfigPda } from "../pdas"; +import { BLOCK_LIST_PROGRAM_ADDRESS } from "../programs"; +import { getAccountMetaFactory, type ResolvedAccount } from "../shared"; export const BLOCK_WALLET_DISCRIMINATOR = 242; @@ -43,13 +43,15 @@ export type BlockWalletInstruction< TAccountConfig extends string | IAccountMeta = string, TAccountWallet extends string | IAccountMeta = string, TAccountWalletBlock extends string | IAccountMeta = string, - TAccountSystemProgram extends string | IAccountMeta = '11111111111111111111111111111111', + TAccountSystemProgram extends string | IAccountMeta = "11111111111111111111111111111111", TRemainingAccounts extends readonly IAccountMeta[] = [], > = IInstruction & IInstructionWithData & IInstructionWithAccounts< [ - TAccountAuthority extends string ? WritableSignerAccount & IAccountSignerMeta : TAccountAuthority, + TAccountAuthority extends string + ? WritableSignerAccount & IAccountSignerMeta + : TAccountAuthority, TAccountConfig extends string ? WritableAccount : TAccountConfig, TAccountWallet extends string ? ReadonlyAccount : TAccountWallet, TAccountWalletBlock extends string ? WritableAccount : TAccountWalletBlock, @@ -60,17 +62,23 @@ export type BlockWalletInstruction< export type BlockWalletInstructionData = { discriminator: number }; -export type BlockWalletInstructionDataArgs = {}; +export type BlockWalletInstructionDataArgs = Record; export function getBlockWalletInstructionDataEncoder(): Encoder { - return transformEncoder(getStructEncoder([['discriminator', getU8Encoder()]]), (value) => ({ ...value, discriminator: 242 })); + return transformEncoder(getStructEncoder([["discriminator", getU8Encoder()]]), (value) => ({ + ...value, + discriminator: 242, + })); } export function getBlockWalletInstructionDataDecoder(): Decoder { - return getStructDecoder([['discriminator', getU8Decoder()]]); + return getStructDecoder([["discriminator", getU8Decoder()]]); } -export function getBlockWalletInstructionDataCodec(): Codec { +export function getBlockWalletInstructionDataCodec(): Codec< + BlockWalletInstructionDataArgs, + BlockWalletInstructionData +> { return combineCodec(getBlockWalletInstructionDataEncoder(), getBlockWalletInstructionDataDecoder()); } @@ -96,9 +104,24 @@ export async function getBlockWalletInstructionAsync< TAccountSystemProgram extends string, TProgramAddress extends Address = typeof BLOCK_LIST_PROGRAM_ADDRESS, >( - input: BlockWalletAsyncInput, + input: BlockWalletAsyncInput< + TAccountAuthority, + TAccountConfig, + TAccountWallet, + TAccountWalletBlock, + TAccountSystemProgram + >, config?: { programAddress?: TProgramAddress }, -): Promise> { +): Promise< + BlockWalletInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountWallet, + TAccountWalletBlock, + TAccountSystemProgram + > +> { // Program address. const programAddress = config?.programAddress ?? BLOCK_LIST_PROGRAM_ADDRESS; @@ -117,10 +140,10 @@ export async function getBlockWalletInstructionAsync< accounts.config.value = await findConfigPda(); } if (!accounts.systemProgram.value) { - accounts.systemProgram.value = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; + accounts.systemProgram.value = "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">; } - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); + const getAccountMeta = getAccountMetaFactory(programAddress, "programId"); const instruction = { accounts: [ getAccountMeta(accounts.authority), @@ -131,7 +154,14 @@ export async function getBlockWalletInstructionAsync< ], programAddress, data: getBlockWalletInstructionDataEncoder().encode({}), - } as BlockWalletInstruction; + } as BlockWalletInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountWallet, + TAccountWalletBlock, + TAccountSystemProgram + >; return instruction; } @@ -158,9 +188,22 @@ export function getBlockWalletInstruction< TAccountSystemProgram extends string, TProgramAddress extends Address = typeof BLOCK_LIST_PROGRAM_ADDRESS, >( - input: BlockWalletInput, + input: BlockWalletInput< + TAccountAuthority, + TAccountConfig, + TAccountWallet, + TAccountWalletBlock, + TAccountSystemProgram + >, config?: { programAddress?: TProgramAddress }, -): BlockWalletInstruction { +): BlockWalletInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountWallet, + TAccountWalletBlock, + TAccountSystemProgram +> { // Program address. const programAddress = config?.programAddress ?? BLOCK_LIST_PROGRAM_ADDRESS; @@ -176,10 +219,10 @@ export function getBlockWalletInstruction< // Resolve default values. if (!accounts.systemProgram.value) { - accounts.systemProgram.value = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; + accounts.systemProgram.value = "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">; } - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); + const getAccountMeta = getAccountMetaFactory(programAddress, "programId"); const instruction = { accounts: [ getAccountMeta(accounts.authority), @@ -190,7 +233,14 @@ export function getBlockWalletInstruction< ], programAddress, data: getBlockWalletInstructionDataEncoder().encode({}), - } as BlockWalletInstruction; + } as BlockWalletInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountWallet, + TAccountWalletBlock, + TAccountSystemProgram + >; return instruction; } @@ -215,11 +265,11 @@ export function parseBlockWalletInstruction { if (instruction.accounts.length < 5) { // TODO: Coded error. - throw new Error('Not enough accounts'); + throw new Error("Not enough accounts"); } let accountIndex = 0; const getNextAccount = () => { - const accountMeta = instruction.accounts?.[accountIndex]!; + const accountMeta = instruction.accounts[accountIndex]; accountIndex += 1; return accountMeta; }; diff --git a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/index.ts b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/index.ts index 864cb10b3..f4bba88c5 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/index.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/index.ts @@ -6,7 +6,7 @@ * @see https://github.com/codama-idl/codama */ -export * from './blockWallet'; -export * from './init'; -export * from './setupExtraMetas'; -export * from './unblockWallet'; +export * from "./blockWallet"; +export * from "./init"; +export * from "./setupExtraMetas"; +export * from "./unblockWallet"; diff --git a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/init.ts b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/init.ts index f02a8fe63..860840983 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/init.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/init.ts @@ -26,10 +26,10 @@ import { transformEncoder, type WritableAccount, type WritableSignerAccount, -} from '@solana/kit'; -import { findConfigPda } from '../pdas'; -import { BLOCK_LIST_PROGRAM_ADDRESS } from '../programs'; -import { getAccountMetaFactory, type ResolvedAccount } from '../shared'; +} from "@solana/kit"; +import { findConfigPda } from "../pdas"; +import { BLOCK_LIST_PROGRAM_ADDRESS } from "../programs"; +import { getAccountMetaFactory, type ResolvedAccount } from "../shared"; export const INIT_DISCRIMINATOR = 241; @@ -41,13 +41,15 @@ export type InitInstruction< TProgram extends string = typeof BLOCK_LIST_PROGRAM_ADDRESS, TAccountAuthority extends string | IAccountMeta = string, TAccountConfig extends string | IAccountMeta = string, - TAccountSystemProgram extends string | IAccountMeta = '11111111111111111111111111111111', + TAccountSystemProgram extends string | IAccountMeta = "11111111111111111111111111111111", TRemainingAccounts extends readonly IAccountMeta[] = [], > = IInstruction & IInstructionWithData & IInstructionWithAccounts< [ - TAccountAuthority extends string ? WritableSignerAccount & IAccountSignerMeta : TAccountAuthority, + TAccountAuthority extends string + ? WritableSignerAccount & IAccountSignerMeta + : TAccountAuthority, TAccountConfig extends string ? WritableAccount : TAccountConfig, TAccountSystemProgram extends string ? ReadonlyAccount : TAccountSystemProgram, ...TRemainingAccounts, @@ -56,14 +58,17 @@ export type InitInstruction< export type InitInstructionData = { discriminator: number }; -export type InitInstructionDataArgs = {}; +export type InitInstructionDataArgs = Record; export function getInitInstructionDataEncoder(): Encoder { - return transformEncoder(getStructEncoder([['discriminator', getU8Encoder()]]), (value) => ({ ...value, discriminator: 241 })); + return transformEncoder(getStructEncoder([["discriminator", getU8Encoder()]]), (value) => ({ + ...value, + discriminator: 241, + })); } export function getInitInstructionDataDecoder(): Decoder { - return getStructDecoder([['discriminator', getU8Decoder()]]); + return getStructDecoder([["discriminator", getU8Decoder()]]); } export function getInitInstructionDataCodec(): Codec { @@ -105,12 +110,16 @@ export async function getInitInstructionAsync< accounts.config.value = await findConfigPda(); } if (!accounts.systemProgram.value) { - accounts.systemProgram.value = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; + accounts.systemProgram.value = "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">; } - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); + const getAccountMeta = getAccountMetaFactory(programAddress, "programId"); const instruction = { - accounts: [getAccountMeta(accounts.authority), getAccountMeta(accounts.config), getAccountMeta(accounts.systemProgram)], + accounts: [ + getAccountMeta(accounts.authority), + getAccountMeta(accounts.config), + getAccountMeta(accounts.systemProgram), + ], programAddress, data: getInitInstructionDataEncoder().encode({}), } as InitInstruction; @@ -150,12 +159,16 @@ export function getInitInstruction< // Resolve default values. if (!accounts.systemProgram.value) { - accounts.systemProgram.value = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; + accounts.systemProgram.value = "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">; } - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); + const getAccountMeta = getAccountMetaFactory(programAddress, "programId"); const instruction = { - accounts: [getAccountMeta(accounts.authority), getAccountMeta(accounts.config), getAccountMeta(accounts.systemProgram)], + accounts: [ + getAccountMeta(accounts.authority), + getAccountMeta(accounts.config), + getAccountMeta(accounts.systemProgram), + ], programAddress, data: getInitInstructionDataEncoder().encode({}), } as InitInstruction; @@ -181,11 +194,11 @@ export function parseInitInstruction { if (instruction.accounts.length < 3) { // TODO: Coded error. - throw new Error('Not enough accounts'); + throw new Error("Not enough accounts"); } let accountIndex = 0; const getNextAccount = () => { - const accountMeta = instruction.accounts?.[accountIndex]!; + const accountMeta = instruction.accounts[accountIndex]; accountIndex += 1; return accountMeta; }; diff --git a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/setupExtraMetas.ts b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/setupExtraMetas.ts index 021e6729c..c9004cd3b 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/setupExtraMetas.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/setupExtraMetas.ts @@ -28,10 +28,10 @@ import { transformEncoder, type WritableAccount, type WritableSignerAccount, -} from '@solana/kit'; -import { findConfigPda, findExtraMetasPda } from '../pdas'; -import { BLOCK_LIST_PROGRAM_ADDRESS } from '../programs'; -import { getAccountMetaFactory, type ResolvedAccount } from '../shared'; +} from "@solana/kit"; +import { findConfigPda, findExtraMetasPda } from "../pdas"; +import { BLOCK_LIST_PROGRAM_ADDRESS } from "../programs"; +import { getAccountMetaFactory, type ResolvedAccount } from "../shared"; export const SETUP_EXTRA_METAS_DISCRIMINATOR = 106; @@ -45,13 +45,15 @@ export type SetupExtraMetasInstruction< TAccountConfig extends string | IAccountMeta = string, TAccountMint extends string | IAccountMeta = string, TAccountExtraMetas extends string | IAccountMeta = string, - TAccountSystemProgram extends string | IAccountMeta = '11111111111111111111111111111111', + TAccountSystemProgram extends string | IAccountMeta = "11111111111111111111111111111111", TRemainingAccounts extends readonly IAccountMeta[] = [], > = IInstruction & IInstructionWithData & IInstructionWithAccounts< [ - TAccountAuthority extends string ? WritableSignerAccount & IAccountSignerMeta : TAccountAuthority, + TAccountAuthority extends string + ? WritableSignerAccount & IAccountSignerMeta + : TAccountAuthority, TAccountConfig extends string ? ReadonlyAccount : TAccountConfig, TAccountMint extends string ? ReadonlyAccount : TAccountMint, TAccountExtraMetas extends string ? WritableAccount : TAccountExtraMetas, @@ -70,8 +72,8 @@ export type SetupExtraMetasInstructionDataArgs = { checkBothWallets?: boolean }; export function getSetupExtraMetasInstructionDataEncoder(): Encoder { return transformEncoder( getStructEncoder([ - ['discriminator', getU8Encoder()], - ['checkBothWallets', getBooleanEncoder()], + ["discriminator", getU8Encoder()], + ["checkBothWallets", getBooleanEncoder()], ]), (value) => ({ ...value, @@ -83,12 +85,15 @@ export function getSetupExtraMetasInstructionDataEncoder(): Encoder { return getStructDecoder([ - ['discriminator', getU8Decoder()], - ['checkBothWallets', getBooleanDecoder()], + ["discriminator", getU8Decoder()], + ["checkBothWallets", getBooleanDecoder()], ]); } -export function getSetupExtraMetasInstructionDataCodec(): Codec { +export function getSetupExtraMetasInstructionDataCodec(): Codec< + SetupExtraMetasInstructionDataArgs, + SetupExtraMetasInstructionData +> { return combineCodec(getSetupExtraMetasInstructionDataEncoder(), getSetupExtraMetasInstructionDataDecoder()); } @@ -104,7 +109,7 @@ export type SetupExtraMetasAsyncInput< mint: Address; extraMetas?: Address; systemProgram?: Address; - checkBothWallets?: SetupExtraMetasInstructionDataArgs['checkBothWallets']; + checkBothWallets?: SetupExtraMetasInstructionDataArgs["checkBothWallets"]; }; export async function getSetupExtraMetasInstructionAsync< @@ -115,9 +120,24 @@ export async function getSetupExtraMetasInstructionAsync< TAccountSystemProgram extends string, TProgramAddress extends Address = typeof BLOCK_LIST_PROGRAM_ADDRESS, >( - input: SetupExtraMetasAsyncInput, + input: SetupExtraMetasAsyncInput< + TAccountAuthority, + TAccountConfig, + TAccountMint, + TAccountExtraMetas, + TAccountSystemProgram + >, config?: { programAddress?: TProgramAddress }, -): Promise> { +): Promise< + SetupExtraMetasInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountMint, + TAccountExtraMetas, + TAccountSystemProgram + > +> { // Program address. const programAddress = config?.programAddress ?? BLOCK_LIST_PROGRAM_ADDRESS; @@ -142,10 +162,10 @@ export async function getSetupExtraMetasInstructionAsync< accounts.extraMetas.value = await findExtraMetasPda(); } if (!accounts.systemProgram.value) { - accounts.systemProgram.value = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; + accounts.systemProgram.value = "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">; } - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); + const getAccountMeta = getAccountMetaFactory(programAddress, "programId"); const instruction = { accounts: [ getAccountMeta(accounts.authority), @@ -156,7 +176,14 @@ export async function getSetupExtraMetasInstructionAsync< ], programAddress, data: getSetupExtraMetasInstructionDataEncoder().encode(args as SetupExtraMetasInstructionDataArgs), - } as SetupExtraMetasInstruction; + } as SetupExtraMetasInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountMint, + TAccountExtraMetas, + TAccountSystemProgram + >; return instruction; } @@ -173,7 +200,7 @@ export type SetupExtraMetasInput< mint: Address; extraMetas: Address; systemProgram?: Address; - checkBothWallets?: SetupExtraMetasInstructionDataArgs['checkBothWallets']; + checkBothWallets?: SetupExtraMetasInstructionDataArgs["checkBothWallets"]; }; export function getSetupExtraMetasInstruction< @@ -184,9 +211,22 @@ export function getSetupExtraMetasInstruction< TAccountSystemProgram extends string, TProgramAddress extends Address = typeof BLOCK_LIST_PROGRAM_ADDRESS, >( - input: SetupExtraMetasInput, + input: SetupExtraMetasInput< + TAccountAuthority, + TAccountConfig, + TAccountMint, + TAccountExtraMetas, + TAccountSystemProgram + >, config?: { programAddress?: TProgramAddress }, -): SetupExtraMetasInstruction { +): SetupExtraMetasInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountMint, + TAccountExtraMetas, + TAccountSystemProgram +> { // Program address. const programAddress = config?.programAddress ?? BLOCK_LIST_PROGRAM_ADDRESS; @@ -205,10 +245,10 @@ export function getSetupExtraMetasInstruction< // Resolve default values. if (!accounts.systemProgram.value) { - accounts.systemProgram.value = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; + accounts.systemProgram.value = "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">; } - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); + const getAccountMeta = getAccountMetaFactory(programAddress, "programId"); const instruction = { accounts: [ getAccountMeta(accounts.authority), @@ -219,7 +259,14 @@ export function getSetupExtraMetasInstruction< ], programAddress, data: getSetupExtraMetasInstructionDataEncoder().encode(args as SetupExtraMetasInstructionDataArgs), - } as SetupExtraMetasInstruction; + } as SetupExtraMetasInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountMint, + TAccountExtraMetas, + TAccountSystemProgram + >; return instruction; } @@ -244,11 +291,11 @@ export function parseSetupExtraMetasInstruction { if (instruction.accounts.length < 5) { // TODO: Coded error. - throw new Error('Not enough accounts'); + throw new Error("Not enough accounts"); } let accountIndex = 0; const getNextAccount = () => { - const accountMeta = instruction.accounts?.[accountIndex]!; + const accountMeta = instruction.accounts[accountIndex]; accountIndex += 1; return accountMeta; }; diff --git a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/unblockWallet.ts b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/unblockWallet.ts index d17158efe..40b3f33f0 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/unblockWallet.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/instructions/unblockWallet.ts @@ -26,10 +26,10 @@ import { transformEncoder, type WritableAccount, type WritableSignerAccount, -} from '@solana/kit'; -import { findConfigPda } from '../pdas'; -import { BLOCK_LIST_PROGRAM_ADDRESS } from '../programs'; -import { getAccountMetaFactory, type ResolvedAccount } from '../shared'; +} from "@solana/kit"; +import { findConfigPda } from "../pdas"; +import { BLOCK_LIST_PROGRAM_ADDRESS } from "../programs"; +import { getAccountMetaFactory, type ResolvedAccount } from "../shared"; export const UNBLOCK_WALLET_DISCRIMINATOR = 243; @@ -42,13 +42,15 @@ export type UnblockWalletInstruction< TAccountAuthority extends string | IAccountMeta = string, TAccountConfig extends string | IAccountMeta = string, TAccountWalletBlock extends string | IAccountMeta = string, - TAccountSystemProgram extends string | IAccountMeta = '11111111111111111111111111111111', + TAccountSystemProgram extends string | IAccountMeta = "11111111111111111111111111111111", TRemainingAccounts extends readonly IAccountMeta[] = [], > = IInstruction & IInstructionWithData & IInstructionWithAccounts< [ - TAccountAuthority extends string ? WritableSignerAccount & IAccountSignerMeta : TAccountAuthority, + TAccountAuthority extends string + ? WritableSignerAccount & IAccountSignerMeta + : TAccountAuthority, TAccountConfig extends string ? WritableAccount : TAccountConfig, TAccountWalletBlock extends string ? WritableAccount : TAccountWalletBlock, TAccountSystemProgram extends string ? ReadonlyAccount : TAccountSystemProgram, @@ -58,17 +60,23 @@ export type UnblockWalletInstruction< export type UnblockWalletInstructionData = { discriminator: number }; -export type UnblockWalletInstructionDataArgs = {}; +export type UnblockWalletInstructionDataArgs = Record; export function getUnblockWalletInstructionDataEncoder(): Encoder { - return transformEncoder(getStructEncoder([['discriminator', getU8Encoder()]]), (value) => ({ ...value, discriminator: 243 })); + return transformEncoder(getStructEncoder([["discriminator", getU8Encoder()]]), (value) => ({ + ...value, + discriminator: 243, + })); } export function getUnblockWalletInstructionDataDecoder(): Decoder { - return getStructDecoder([['discriminator', getU8Decoder()]]); + return getStructDecoder([["discriminator", getU8Decoder()]]); } -export function getUnblockWalletInstructionDataCodec(): Codec { +export function getUnblockWalletInstructionDataCodec(): Codec< + UnblockWalletInstructionDataArgs, + UnblockWalletInstructionData +> { return combineCodec(getUnblockWalletInstructionDataEncoder(), getUnblockWalletInstructionDataDecoder()); } @@ -93,7 +101,15 @@ export async function getUnblockWalletInstructionAsync< >( input: UnblockWalletAsyncInput, config?: { programAddress?: TProgramAddress }, -): Promise> { +): Promise< + UnblockWalletInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountWalletBlock, + TAccountSystemProgram + > +> { // Program address. const programAddress = config?.programAddress ?? BLOCK_LIST_PROGRAM_ADDRESS; @@ -111,10 +127,10 @@ export async function getUnblockWalletInstructionAsync< accounts.config.value = await findConfigPda(); } if (!accounts.systemProgram.value) { - accounts.systemProgram.value = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; + accounts.systemProgram.value = "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">; } - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); + const getAccountMeta = getAccountMetaFactory(programAddress, "programId"); const instruction = { accounts: [ getAccountMeta(accounts.authority), @@ -124,7 +140,13 @@ export async function getUnblockWalletInstructionAsync< ], programAddress, data: getUnblockWalletInstructionDataEncoder().encode({}), - } as UnblockWalletInstruction; + } as UnblockWalletInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountWalletBlock, + TAccountSystemProgram + >; return instruction; } @@ -150,7 +172,13 @@ export function getUnblockWalletInstruction< >( input: UnblockWalletInput, config?: { programAddress?: TProgramAddress }, -): UnblockWalletInstruction { +): UnblockWalletInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountWalletBlock, + TAccountSystemProgram +> { // Program address. const programAddress = config?.programAddress ?? BLOCK_LIST_PROGRAM_ADDRESS; @@ -165,10 +193,10 @@ export function getUnblockWalletInstruction< // Resolve default values. if (!accounts.systemProgram.value) { - accounts.systemProgram.value = '11111111111111111111111111111111' as Address<'11111111111111111111111111111111'>; + accounts.systemProgram.value = "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">; } - const getAccountMeta = getAccountMetaFactory(programAddress, 'programId'); + const getAccountMeta = getAccountMetaFactory(programAddress, "programId"); const instruction = { accounts: [ getAccountMeta(accounts.authority), @@ -178,7 +206,13 @@ export function getUnblockWalletInstruction< ], programAddress, data: getUnblockWalletInstructionDataEncoder().encode({}), - } as UnblockWalletInstruction; + } as UnblockWalletInstruction< + TProgramAddress, + TAccountAuthority, + TAccountConfig, + TAccountWalletBlock, + TAccountSystemProgram + >; return instruction; } @@ -202,11 +236,11 @@ export function parseUnblockWalletInstruction { if (instruction.accounts.length < 4) { // TODO: Coded error. - throw new Error('Not enough accounts'); + throw new Error("Not enough accounts"); } let accountIndex = 0; const getNextAccount = () => { - const accountMeta = instruction.accounts?.[accountIndex]!; + const accountMeta = instruction.accounts[accountIndex]; accountIndex += 1; return accountMeta; }; diff --git a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/pdas/config.ts b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/pdas/config.ts index 343f6f4ce..be83310f6 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/pdas/config.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/pdas/config.ts @@ -6,12 +6,16 @@ * @see https://github.com/codama-idl/codama */ -import { type Address, getProgramDerivedAddress, getUtf8Encoder, type ProgramDerivedAddress } from '@solana/kit'; +import { type Address, getProgramDerivedAddress, getUtf8Encoder, type ProgramDerivedAddress } from "@solana/kit"; -export async function findConfigPda(config: { programAddress?: Address | undefined } = {}): Promise { - const { programAddress = 'BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf' as Address<'BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf'> } = config; +export async function findConfigPda( + config: { programAddress?: Address | undefined } = {}, +): Promise { + const { + programAddress = "BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf" as Address<"BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf">, + } = config; return await getProgramDerivedAddress({ programAddress, - seeds: [getUtf8Encoder().encode('config')], + seeds: [getUtf8Encoder().encode("config")], }); } diff --git a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/pdas/extraMetas.ts b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/pdas/extraMetas.ts index a66a9d189..db4a84483 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/pdas/extraMetas.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/pdas/extraMetas.ts @@ -6,7 +6,13 @@ * @see https://github.com/codama-idl/codama */ -import { type Address, getAddressEncoder, getProgramDerivedAddress, getUtf8Encoder, type ProgramDerivedAddress } from '@solana/kit'; +import { + type Address, + getAddressEncoder, + getProgramDerivedAddress, + getUtf8Encoder, + type ProgramDerivedAddress, +} from "@solana/kit"; export type ExtraMetasSeeds = { mint: Address; @@ -16,9 +22,11 @@ export async function findExtraMetasPda( seeds: ExtraMetasSeeds, config: { programAddress?: Address | undefined } = {}, ): Promise { - const { programAddress = 'BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf' as Address<'BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf'> } = config; + const { + programAddress = "BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf" as Address<"BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf">, + } = config; return await getProgramDerivedAddress({ programAddress, - seeds: [getUtf8Encoder().encode('extra-account-metas'), getAddressEncoder().encode(seeds.mint)], + seeds: [getUtf8Encoder().encode("extra-account-metas"), getAddressEncoder().encode(seeds.mint)], }); } diff --git a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/pdas/index.ts b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/pdas/index.ts index ed620eb19..6135b7a67 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/pdas/index.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/pdas/index.ts @@ -6,6 +6,6 @@ * @see https://github.com/codama-idl/codama */ -export * from './config'; -export * from './extraMetas'; -export * from './walletBlock'; +export * from "./config"; +export * from "./extraMetas"; +export * from "./walletBlock"; diff --git a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/pdas/walletBlock.ts b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/pdas/walletBlock.ts index 1a5e84096..2705fbcef 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/pdas/walletBlock.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/pdas/walletBlock.ts @@ -6,7 +6,13 @@ * @see https://github.com/codama-idl/codama */ -import { type Address, getAddressEncoder, getProgramDerivedAddress, getUtf8Encoder, type ProgramDerivedAddress } from '@solana/kit'; +import { + type Address, + getAddressEncoder, + getProgramDerivedAddress, + getUtf8Encoder, + type ProgramDerivedAddress, +} from "@solana/kit"; export type WalletBlockSeeds = { wallet: Address; @@ -16,9 +22,11 @@ export async function findWalletBlockPda( seeds: WalletBlockSeeds, config: { programAddress?: Address | undefined } = {}, ): Promise { - const { programAddress = 'BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf' as Address<'BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf'> } = config; + const { + programAddress = "BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf" as Address<"BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf">, + } = config; return await getProgramDerivedAddress({ programAddress, - seeds: [getUtf8Encoder().encode('wallet_block'), getAddressEncoder().encode(seeds.wallet)], + seeds: [getUtf8Encoder().encode("wallet_block"), getAddressEncoder().encode(seeds.wallet)], }); } diff --git a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/programs/blockList.ts b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/programs/blockList.ts index 4ba42d741..d22c9ccf9 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/programs/blockList.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/programs/blockList.ts @@ -6,15 +6,16 @@ * @see https://github.com/codama-idl/codama */ -import { type Address, containsBytes, getU8Encoder, type ReadonlyUint8Array } from '@solana/kit'; -import { - type ParsedBlockWalletInstruction, - type ParsedInitInstruction, - type ParsedSetupExtraMetasInstruction, - type ParsedUnblockWalletInstruction, -} from '../instructions'; +import { type Address, containsBytes, getU8Encoder, type ReadonlyUint8Array } from "@solana/kit"; +import type { + ParsedBlockWalletInstruction, + ParsedInitInstruction, + ParsedSetupExtraMetasInstruction, + ParsedUnblockWalletInstruction, +} from "../instructions"; -export const BLOCK_LIST_PROGRAM_ADDRESS = 'BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf' as Address<'BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf'>; +export const BLOCK_LIST_PROGRAM_ADDRESS = + "BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf" as Address<"BLoCKLSG2qMQ9YxEyrrKKAQzthvW4Lu8Eyv74axF6mf">; export enum BlockListAccount { Config, @@ -23,14 +24,14 @@ export enum BlockListAccount { } export function identifyBlockListAccount(account: { data: ReadonlyUint8Array } | ReadonlyUint8Array): BlockListAccount { - const data = 'data' in account ? account.data : account; + const data = "data" in account ? account.data : account; if (containsBytes(data, getU8Encoder().encode(0), 0)) { return BlockListAccount.Config; } if (containsBytes(data, getU8Encoder().encode(1), 0)) { return BlockListAccount.WalletBlock; } - throw new Error('The provided account could not be identified as a blockList account.'); + throw new Error("The provided account could not be identified as a blockList account."); } export enum BlockListInstruction { @@ -40,8 +41,10 @@ export enum BlockListInstruction { SetupExtraMetas, } -export function identifyBlockListInstruction(instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array): BlockListInstruction { - const data = 'data' in instruction ? instruction.data : instruction; +export function identifyBlockListInstruction( + instruction: { data: ReadonlyUint8Array } | ReadonlyUint8Array, +): BlockListInstruction { + const data = "data" in instruction ? instruction.data : instruction; if (containsBytes(data, getU8Encoder().encode(241), 0)) { return BlockListInstruction.Init; } @@ -54,10 +57,10 @@ export function identifyBlockListInstruction(instruction: { data: ReadonlyUint8A if (containsBytes(data, getU8Encoder().encode(106), 0)) { return BlockListInstruction.SetupExtraMetas; } - throw new Error('The provided instruction could not be identified as a blockList instruction.'); + throw new Error("The provided instruction could not be identified as a blockList instruction."); } -export type ParsedBlockListInstruction = +export type ParsedBlockListInstruction = | ({ instructionType: BlockListInstruction.Init; } & ParsedInitInstruction) diff --git a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/programs/index.ts b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/programs/index.ts index f945615bd..01ddfbdee 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/programs/index.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/programs/index.ts @@ -6,4 +6,4 @@ * @see https://github.com/codama-idl/codama */ -export * from './blockList'; +export * from "./blockList"; diff --git a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/shared/index.ts b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/shared/index.ts index 27141fc40..6b3bc4a6a 100644 --- a/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/shared/index.ts +++ b/tokens/token-2022/transfer-hook/pblock-list/sdk/ts/src/shared/index.ts @@ -16,7 +16,7 @@ import { type ProgramDerivedAddress, type TransactionSigner, upgradeRoleToSigner, -} from '@solana/kit'; +} from "@solana/kit"; /** * Asserts that the given value is not null or undefined. @@ -24,7 +24,7 @@ import { */ export function expectSome(value: T | null | undefined): T { if (value == null) { - throw new Error('Expected a value but received null or undefined.'); + throw new Error("Expected a value but received null or undefined."); } return value; } @@ -37,9 +37,9 @@ export function expectAddress( value: Address | ProgramDerivedAddress | TransactionSigner | null | undefined, ): Address { if (!value) { - throw new Error('Expected a Address.'); + throw new Error("Expected a Address."); } - if (typeof value === 'object' && 'address' in value) { + if (typeof value === "object" && "address" in value) { return value.address; } if (Array.isArray(value)) { @@ -56,7 +56,7 @@ export function expectProgramDerivedAddress( value: Address | ProgramDerivedAddress | TransactionSigner | null | undefined, ): ProgramDerivedAddress { if (!value || !Array.isArray(value) || !isProgramDerivedAddress(value)) { - throw new Error('Expected a ProgramDerivedAddress.'); + throw new Error("Expected a ProgramDerivedAddress."); } return value; } @@ -69,7 +69,7 @@ export function expectTransactionSigner( value: Address | ProgramDerivedAddress | TransactionSigner | null | undefined, ): TransactionSigner { if (!value || !isTransactionSigner(value)) { - throw new Error('Expected a TransactionSigner.'); + throw new Error("Expected a TransactionSigner."); } return value; } @@ -80,7 +80,11 @@ export function expectTransactionSigner( */ export type ResolvedAccount< T extends string = string, - U extends Address | ProgramDerivedAddress | TransactionSigner | null = Address | ProgramDerivedAddress | TransactionSigner | null, + U extends Address | ProgramDerivedAddress | TransactionSigner | null = + | Address + | ProgramDerivedAddress + | TransactionSigner + | null, > = { isWritable: boolean; value: U; @@ -98,10 +102,10 @@ export type IInstructionWithByteDelta = { * Get account metas and signers from resolved accounts. * @internal */ -export function getAccountMetaFactory(programAddress: Address, optionalAccountStrategy: 'omitted' | 'programId') { +export function getAccountMetaFactory(programAddress: Address, optionalAccountStrategy: "omitted" | "programId") { return (account: ResolvedAccount): IAccountMeta | IAccountSignerMeta | undefined => { if (!account.value) { - if (optionalAccountStrategy === 'omitted') return; + if (optionalAccountStrategy === "omitted") return; return Object.freeze({ address: programAddress, role: AccountRole.READONLY, @@ -120,5 +124,5 @@ export function getAccountMetaFactory(programAddress: Address, optionalAccountSt export function isTransactionSigner( value: Address | ProgramDerivedAddress | TransactionSigner, ): value is TransactionSigner { - return !!value && typeof value === 'object' && 'address' in value && kitIsTransactionSigner(value); + return !!value && typeof value === "object" && "address" in value && kitIsTransactionSigner(value); } diff --git a/tokens/token-2022/transfer-hook/transfer-cost/anchor/migrations/deploy.ts b/tokens/token-2022/transfer-hook/transfer-cost/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/tokens/token-2022/transfer-hook/transfer-cost/anchor/migrations/deploy.ts +++ b/tokens/token-2022/transfer-hook/transfer-cost/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/token-2022/transfer-hook/transfer-cost/anchor/package.json b/tokens/token-2022/transfer-hook/transfer-cost/anchor/package.json index 4faaff4b4..0839cf5e9 100644 --- a/tokens/token-2022/transfer-hook/transfer-cost/anchor/package.json +++ b/tokens/token-2022/transfer-hook/transfer-cost/anchor/package.json @@ -1,21 +1,21 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.4.0" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.4.0" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-2022/transfer-hook/transfer-cost/anchor/tests/transfer-hook.ts b/tokens/token-2022/transfer-hook/transfer-cost/anchor/tests/transfer-hook.ts index d1a806bfe..2ea7cda84 100644 --- a/tokens/token-2022/transfer-hook/transfer-cost/anchor/tests/transfer-hook.ts +++ b/tokens/token-2022/transfer-hook/transfer-cost/anchor/tests/transfer-hook.ts @@ -1,6 +1,6 @@ -import assert from 'node:assert'; -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; +import assert from "node:assert"; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; import { ASSOCIATED_TOKEN_PROGRAM_ID, createApproveInstruction, @@ -22,11 +22,11 @@ import { NATIVE_MINT, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID, -} from '@solana/spl-token'; -import { Keypair, PublicKey, SystemProgram, sendAndConfirmTransaction, Transaction } from '@solana/web3.js'; -import type { TransferHook } from '../target/types/transfer_hook'; +} from "@solana/spl-token"; +import { Keypair, PublicKey, SystemProgram, sendAndConfirmTransaction, Transaction } from "@solana/web3.js"; +import type { TransferHook } from "../target/types/transfer_hook"; -describe('transfer-hook', () => { +describe("transfer-hook", () => { // Configure the client to use the local cluster. const provider = anchor.AnchorProvider.env(); anchor.setProvider(provider); @@ -59,7 +59,7 @@ describe('transfer-hook', () => { ); // PDA delegate to transfer wSOL tokens from sender - const [delegatePDA] = PublicKey.findProgramAddressSync([Buffer.from('delegate')], program.programId); + const [delegatePDA] = PublicKey.findProgramAddressSync([Buffer.from("delegate")], program.programId); // Sender wSOL token account address const senderWSolTokenAccount = getAssociatedTokenAddressSync( @@ -83,7 +83,7 @@ describe('transfer-hook', () => { await getOrCreateAssociatedTokenAccount(connection, wallet.payer, NATIVE_MINT, delegatePDA, true); }); - it('Create Mint Account with Transfer Hook Extension', async () => { + it("Create Mint Account with Transfer Hook Extension", async () => { const extensions = [ExtensionType.TransferHook]; const mintLen = getMintLen(extensions); const lamports = await provider.connection.getMinimumBalanceForRentExemption(mintLen); @@ -111,7 +111,7 @@ describe('transfer-hook', () => { // Create the two token accounts for the transfer-hook enabled mint // Fund the sender token account with 100 tokens - it('Create Token Accounts and Mint Tokens', async () => { + it("Create Token Accounts and Mint Tokens", async () => { // 100 tokens const amount = 100 * 10 ** decimals; @@ -141,7 +141,7 @@ describe('transfer-hook', () => { }); // Account to store extra accounts required by the transfer hook instruction - it('Create ExtraAccountMetaList Account', async () => { + it("Create ExtraAccountMetaList Account", async () => { const initializeExtraAccountMetaListInstruction = await program.methods .initializeExtraAccountMetaList() .accounts({ @@ -152,11 +152,14 @@ describe('transfer-hook', () => { const transaction = new Transaction().add(initializeExtraAccountMetaListInstruction); - const txSig = await sendAndConfirmTransaction(provider.connection, transaction, [wallet.payer], { skipPreflight: true, commitment: 'confirmed' }); - console.log('Transaction Signature:', txSig); + const txSig = await sendAndConfirmTransaction(provider.connection, transaction, [wallet.payer], { + skipPreflight: true, + commitment: "confirmed", + }); + console.log("Transaction Signature:", txSig); }); - it('Transfer Hook with Extra Account Meta', async () => { + it("Transfer Hook with Extra Account Meta", async () => { // 1 tokens const amount = 1 * 10 ** decimals; const bigIntAmount = BigInt(amount); @@ -169,19 +172,26 @@ describe('transfer-hook', () => { }); // Approve delegate PDA to transfer WSol tokens from sender WSol token account - const approveInstruction = createApproveInstruction(senderWSolTokenAccount, delegatePDA, wallet.publicKey, amount, [], TOKEN_PROGRAM_ID); + const approveInstruction = createApproveInstruction( + senderWSolTokenAccount, + delegatePDA, + wallet.publicKey, + amount, + [], + TOKEN_PROGRAM_ID, + ); // Sync sender WSol token account const syncWrappedSolInstruction = createSyncNativeInstruction(senderWSolTokenAccount); - const mintInfo = await getMint(connection, mint.publicKey, 'confirmed', TOKEN_2022_PROGRAM_ID); + const mintInfo = await getMint(connection, mint.publicKey, "confirmed", TOKEN_2022_PROGRAM_ID); const transferHook = getTransferHook(mintInfo); if (transferHook != null) { console.log(`Transfer hook program found: ${JSON.stringify(transferHook, null, 2)}`); } const extraAccountsAccount = getExtraAccountMetaAddress(mint.publicKey, transferHook.programId); - const extraAccountsInfo = await connection.getAccountInfo(extraAccountsAccount, 'confirmed'); + const extraAccountsInfo = await connection.getAccountInfo(extraAccountsAccount, "confirmed"); const extraAccountMetas = getExtraAccountMetas(extraAccountsInfo); for (const extraAccountMeta of extraAccountMetas) { @@ -198,16 +208,21 @@ describe('transfer-hook', () => { bigIntAmount, decimals, [], - 'confirmed', + "confirmed", TOKEN_2022_PROGRAM_ID, ); - console.log('Pushed keys:', JSON.stringify(transferInstruction.keys, null, 2)); + console.log("Pushed keys:", JSON.stringify(transferInstruction.keys, null, 2)); - const transaction = new Transaction().add(solTransferInstruction, syncWrappedSolInstruction, approveInstruction, transferInstruction); + const transaction = new Transaction().add( + solTransferInstruction, + syncWrappedSolInstruction, + approveInstruction, + transferInstruction, + ); const txSig = await sendAndConfirmTransaction(connection, transaction, [wallet.payer], { skipPreflight: true }); - console.log('Transfer Signature:', txSig); + console.log("Transfer Signature:", txSig); const tokenAccount = await getAccount(connection, delegateWSolTokenAccount); diff --git a/tokens/token-2022/transfer-hook/transfer-switch/anchor/package.json b/tokens/token-2022/transfer-hook/transfer-switch/anchor/package.json index e65993ea8..1cfed0947 100644 --- a/tokens/token-2022/transfer-hook/transfer-switch/anchor/package.json +++ b/tokens/token-2022/transfer-hook/transfer-switch/anchor/package.json @@ -1,19 +1,19 @@ { - "type": "module", - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.4.0" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "10.0.9", - "anchor-bankrun": "^0.5.0", - "chai": "^4.3.4", - "mocha": "^10.8.2", - "prettier": "^2.6.2", - "solana-bankrun": "^0.4.0", - "ts-mocha": "^10.0.0", - "typescript": "^5" - } + "type": "module", + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.4.0" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "10.0.9", + "anchor-bankrun": "^0.5.0", + "chai": "^4.3.4", + "mocha": "^10.8.2", + "prettier": "^2.6.2", + "solana-bankrun": "^0.4.0", + "ts-mocha": "^10.0.0", + "typescript": "^5" + } } diff --git a/tokens/token-2022/transfer-hook/transfer-switch/anchor/tests/transfer-switch.ts b/tokens/token-2022/transfer-hook/transfer-switch/anchor/tests/transfer-switch.ts index 85969836f..f762a429a 100644 --- a/tokens/token-2022/transfer-hook/transfer-switch/anchor/tests/transfer-switch.ts +++ b/tokens/token-2022/transfer-hook/transfer-switch/anchor/tests/transfer-switch.ts @@ -13,21 +13,16 @@ import { getMintLen, TOKEN_2022_PROGRAM_ID, } from "@solana/spl-token"; -import { - Keypair, - PublicKey, - SystemProgram, - Transaction, - TransactionInstruction, -} from "@solana/web3.js"; +import { Keypair, PublicKey, SystemProgram, Transaction, type TransactionInstruction } from "@solana/web3.js"; import { BankrunProvider } from "anchor-bankrun"; import { assert } from "chai"; import { startAnchor } from "solana-bankrun"; +import IDL from "../target/idl/transfer_switch.json"; import type { TransferSwitch } from "../target/types/transfer_switch"; -import IDL from "../target/idl/transfer_switch.json"; const PROGRAM_ID = new PublicKey(IDL.address); +// biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 const expectRevert = async (promise: Promise) => { try { await promise; @@ -38,11 +33,7 @@ const expectRevert = async (promise: Promise) => { }; describe("Transfer switch", async () => { - const context = await startAnchor( - "", - [{ name: "transfer_switch", programId: PROGRAM_ID }], - [], - ); + const context = await startAnchor("", [{ name: "transfer_switch", programId: PROGRAM_ID }], []); const provider = new BankrunProvider(context); const _wallet = provider.wallet as anchor.Wallet; @@ -77,10 +68,7 @@ describe("Transfer switch", async () => { } // admin config address - const adminConfigAddress = PublicKey.findProgramAddressSync( - [Buffer.from("admin-config")], - PROGRAM_ID, - )[0]; + const adminConfigAddress = PublicKey.findProgramAddressSync([Buffer.from("admin-config")], PROGRAM_ID)[0]; // helper for getting wallet switch const walletTransferSwitchAddress = (wallet: PublicKey) => @@ -92,8 +80,7 @@ describe("Transfer switch", async () => { it("Create Mint Account with Transfer Hook Extension", async () => { const extensions = [ExtensionType.TransferHook]; const mintLen = getMintLen(extensions); - const lamports = - await provider.connection.getMinimumBalanceForRentExemption(mintLen); + const lamports = await provider.connection.getMinimumBalanceForRentExemption(mintLen); const transaction = new Transaction().add( SystemProgram.createAccount({ @@ -109,13 +96,7 @@ describe("Transfer switch", async () => { program.programId, // Transfer Hook Program ID TOKEN_2022_PROGRAM_ID, ), - createInitializeMintInstruction( - mint.publicKey, - decimals, - payer.publicKey, - null, - TOKEN_2022_PROGRAM_ID, - ), + createInitializeMintInstruction(mint.publicKey, decimals, payer.publicKey, null, TOKEN_2022_PROGRAM_ID), ); transaction.recentBlockhash = context.lastBlockhash; @@ -132,14 +113,7 @@ describe("Transfer switch", async () => { const transaction = new Transaction().add( senderTokenAccountCreateIx, // create sender token account - createMintToInstruction( - mint.publicKey, - senderTokenAccount, - payer.publicKey, - amount, - [], - TOKEN_2022_PROGRAM_ID, - ), + createMintToInstruction(mint.publicKey, senderTokenAccount, payer.publicKey, amount, [], TOKEN_2022_PROGRAM_ID), ); transaction.recentBlockhash = context.lastBlockhash; @@ -173,13 +147,9 @@ describe("Transfer switch", async () => { .signers([payer]) .rpc(); - const adminConfig = - await program.account.adminConfig.fetch(adminConfigAddress); + const adminConfig = await program.account.adminConfig.fetch(adminConfigAddress); assert(adminConfig.isInitialised === true, "admin config not initialised"); - assert( - adminConfig.admin.toBase58() === payer.publicKey.toBase58(), - "admin does not match", - ); + assert(adminConfig.admin.toBase58() === payer.publicKey.toBase58(), "admin does not match"); }); // Account to store extra accounts required by the transfer hook instruction @@ -193,14 +163,9 @@ describe("Transfer switch", async () => { .signers([payer]) .rpc(); - const walletSwitch = await program.account.transferSwitch.fetch( - walletTransferSwitchAddress(sender.publicKey), - ); + const walletSwitch = await program.account.transferSwitch.fetch(walletTransferSwitchAddress(sender.publicKey)); - assert( - walletSwitch.wallet.toBase58() === sender.publicKey.toBase58(), - "wallet key does not match", - ); + assert(walletSwitch.wallet.toBase58() === sender.publicKey.toBase58(), "wallet key does not match"); assert(!walletSwitch.on, "wallet switch not set to false"); }); @@ -209,8 +174,7 @@ describe("Transfer switch", async () => { const amount = 1 * 10 ** decimals; const bigIntAmount = BigInt(amount); - const [recipient, recipientTokenAccount, recipientTokenAccountCreateIx] = - newUser(); + const [recipient, recipientTokenAccount, recipientTokenAccountCreateIx] = newUser(); // create the recipient token account ahead of the transfer, // @@ -224,19 +188,18 @@ describe("Transfer switch", async () => { client.processTransaction(transaction); // Standard token transfer instruction - const transferInstruction = - await createTransferCheckedWithTransferHookInstruction( - connection, - senderTokenAccount, - mint.publicKey, - recipientTokenAccount, - sender.publicKey, - bigIntAmount, - decimals, - [], - "confirmed", - TOKEN_2022_PROGRAM_ID, - ); + const transferInstruction = await createTransferCheckedWithTransferHookInstruction( + connection, + senderTokenAccount, + mint.publicKey, + recipientTokenAccount, + sender.publicKey, + bigIntAmount, + decimals, + [], + "confirmed", + TOKEN_2022_PROGRAM_ID, + ); transaction = new Transaction().add( transferInstruction, // transfer instruction @@ -249,12 +212,8 @@ describe("Transfer switch", async () => { // expectRevert(client.processTransaction(transaction)); - const recipientTokenAccountData = ( - await client.getAccount(recipientTokenAccount) - ).data; - const recipientBalance = AccountLayout.decode( - recipientTokenAccountData, - ).amount; + const recipientTokenAccountData = (await client.getAccount(recipientTokenAccount)).data; + const recipientBalance = AccountLayout.decode(recipientTokenAccountData).amount; assert(recipientBalance === BigInt(0), "transfer was successful"); }); @@ -270,14 +229,9 @@ describe("Transfer switch", async () => { .signers([payer]) .rpc(); - const walletSwitch = await program.account.transferSwitch.fetch( - walletTransferSwitchAddress(sender.publicKey), - ); + const walletSwitch = await program.account.transferSwitch.fetch(walletTransferSwitchAddress(sender.publicKey)); - assert( - walletSwitch.wallet.toBase58() === sender.publicKey.toBase58(), - "wallet key does not match", - ); + assert(walletSwitch.wallet.toBase58() === sender.publicKey.toBase58(), "wallet key does not match"); assert(walletSwitch.on, "wallet switch not set to true"); }); @@ -286,41 +240,32 @@ describe("Transfer switch", async () => { const amount = 1 * 10 ** decimals; const bigIntAmount = BigInt(amount); - const [_recipient, recipientTokenAccount, recipientTokenAccountCreateIx] = - newUser(); + const [_recipient, recipientTokenAccount, recipientTokenAccountCreateIx] = newUser(); // Standard token transfer instruction - const transferInstruction = - await createTransferCheckedWithTransferHookInstruction( - connection, - senderTokenAccount, - mint.publicKey, - recipientTokenAccount, - sender.publicKey, - bigIntAmount, - decimals, - [], - "confirmed", - TOKEN_2022_PROGRAM_ID, - ); - - const transaction = new Transaction().add( - recipientTokenAccountCreateIx, - transferInstruction, + const transferInstruction = await createTransferCheckedWithTransferHookInstruction( + connection, + senderTokenAccount, + mint.publicKey, + recipientTokenAccount, + sender.publicKey, + bigIntAmount, + decimals, + [], + "confirmed", + TOKEN_2022_PROGRAM_ID, ); + const transaction = new Transaction().add(recipientTokenAccountCreateIx, transferInstruction); + transaction.recentBlockhash = context.lastBlockhash; transaction.sign(payer, sender); await client.processTransaction(transaction); - const recipientTokenAccountData = ( - await client.getAccount(recipientTokenAccount) - ).data; + const recipientTokenAccountData = (await client.getAccount(recipientTokenAccount)).data; - const recipientBalance = AccountLayout.decode( - recipientTokenAccountData, - ).amount; + const recipientBalance = AccountLayout.decode(recipientTokenAccountData).amount; assert(recipientBalance === bigIntAmount, "transfer was not successful"); }); diff --git a/tokens/token-2022/transfer-hook/whitelist/anchor/migrations/deploy.ts b/tokens/token-2022/transfer-hook/whitelist/anchor/migrations/deploy.ts index cfcedbc47..81b3ef439 100644 --- a/tokens/token-2022/transfer-hook/whitelist/anchor/migrations/deploy.ts +++ b/tokens/token-2022/transfer-hook/whitelist/anchor/migrations/deploy.ts @@ -2,7 +2,7 @@ // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. -const anchor = require('@anchor-lang/core'); +const anchor = require("@anchor-lang/core"); module.exports = async (provider) => { // Configure client to use the provider. diff --git a/tokens/token-2022/transfer-hook/whitelist/anchor/package.json b/tokens/token-2022/transfer-hook/whitelist/anchor/package.json index 908f2ae4d..1d970c8e4 100644 --- a/tokens/token-2022/transfer-hook/whitelist/anchor/package.json +++ b/tokens/token-2022/transfer-hook/whitelist/anchor/package.json @@ -1,23 +1,23 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.4.0" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/chai-as-promised": "^7.1.8", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "chai-as-promised": "^7.1.2", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.4.0" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/chai-as-promised": "^7.1.8", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "chai-as-promised": "^7.1.2", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-2022/transfer-hook/whitelist/anchor/tests/transfer-hook.ts b/tokens/token-2022/transfer-hook/whitelist/anchor/tests/transfer-hook.ts index 3dd06a21c..70d2bdcbb 100644 --- a/tokens/token-2022/transfer-hook/whitelist/anchor/tests/transfer-hook.ts +++ b/tokens/token-2022/transfer-hook/whitelist/anchor/tests/transfer-hook.ts @@ -1,5 +1,5 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; import { ASSOCIATED_TOKEN_PROGRAM_ID, createAssociatedTokenAccountInstruction, @@ -11,11 +11,11 @@ import { getAssociatedTokenAddressSync, getMintLen, TOKEN_2022_PROGRAM_ID, -} from '@solana/spl-token'; -import { Keypair, SystemProgram, sendAndConfirmTransaction, Transaction } from '@solana/web3.js'; -import type { TransferHook } from '../target/types/transfer_hook'; +} from "@solana/spl-token"; +import { Keypair, SystemProgram, sendAndConfirmTransaction, Transaction } from "@solana/web3.js"; +import type { TransferHook } from "../target/types/transfer_hook"; -describe('transfer-hook', () => { +describe("transfer-hook", () => { // Configure the client to use the local cluster. const provider = anchor.AnchorProvider.env(); anchor.setProvider(provider); @@ -47,7 +47,7 @@ describe('transfer-hook', () => { ASSOCIATED_TOKEN_PROGRAM_ID, ); - it('Create Mint Account with Transfer Hook Extension', async () => { + it("Create Mint Account with Transfer Hook Extension", async () => { const extensions = [ExtensionType.TransferHook]; const mintLen = getMintLen(extensions); const lamports = await provider.connection.getMinimumBalanceForRentExemption(mintLen); @@ -75,7 +75,7 @@ describe('transfer-hook', () => { // Create the two token accounts for the transfer-hook enabled mint // Fund the sender token account with 100 tokens - it('Create Token Accounts and Mint Tokens', async () => { + it("Create Token Accounts and Mint Tokens", async () => { // 100 tokens const amount = 100 * 10 ** decimals; @@ -105,7 +105,7 @@ describe('transfer-hook', () => { }); // Account to store extra accounts required by the transfer hook instruction - it('Create ExtraAccountMetaList Account', async () => { + it("Create ExtraAccountMetaList Account", async () => { const initializeExtraAccountMetaListInstruction = await program.methods .initializeExtraAccountMetaList() .accounts({ @@ -115,12 +115,15 @@ describe('transfer-hook', () => { const transaction = new Transaction().add(initializeExtraAccountMetaListInstruction); - const txSig = await sendAndConfirmTransaction(provider.connection, transaction, [wallet.payer], { skipPreflight: true, commitment: 'confirmed' }); + const txSig = await sendAndConfirmTransaction(provider.connection, transaction, [wallet.payer], { + skipPreflight: true, + commitment: "confirmed", + }); - console.log('Transaction Signature:', txSig); + console.log("Transaction Signature:", txSig); }); - it('Add account to white list', async () => { + it("Add account to white list", async () => { const addAccountToWhiteListInstruction = await program.methods .addToWhitelist() .accounts({ @@ -132,10 +135,10 @@ describe('transfer-hook', () => { const transaction = new Transaction().add(addAccountToWhiteListInstruction); const txSig = await sendAndConfirmTransaction(connection, transaction, [wallet.payer], { skipPreflight: true }); - console.log('White Listed:', txSig); + console.log("White Listed:", txSig); }); - it('Transfer Hook with Extra Account Meta', async () => { + it("Transfer Hook with Extra Account Meta", async () => { // 1 tokens const amount = 1 * 10 ** decimals; const bigIntAmount = BigInt(amount); @@ -150,13 +153,13 @@ describe('transfer-hook', () => { bigIntAmount, decimals, [], - 'confirmed', + "confirmed", TOKEN_2022_PROGRAM_ID, ); const transaction = new Transaction().add(transferInstruction); const txSig = await sendAndConfirmTransaction(connection, transaction, [wallet.payer], { skipPreflight: true }); - console.log('Transfer Checked:', txSig); + console.log("Transfer Checked:", txSig); }); }); diff --git a/tokens/token-fundraiser/anchor/package.json b/tokens/token-fundraiser/anchor/package.json index ec93e2a0e..2c9c49143 100644 --- a/tokens/token-fundraiser/anchor/package.json +++ b/tokens/token-fundraiser/anchor/package.json @@ -1,23 +1,23 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.4.6" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "anchor-bankrun": "^0.4.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "solana-bankrun": "^0.3.0", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.4.6" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "anchor-bankrun": "^0.4.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "solana-bankrun": "^0.3.0", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-fundraiser/anchor/tests/bankrun.test.ts b/tokens/token-fundraiser/anchor/tests/bankrun.test.ts index 86baeb62d..ce11539aa 100644 --- a/tokens/token-fundraiser/anchor/tests/bankrun.test.ts +++ b/tokens/token-fundraiser/anchor/tests/bankrun.test.ts @@ -2,27 +2,23 @@ import { describe, it } from "node:test"; import * as anchor from "@anchor-lang/core"; import { ASSOCIATED_TOKEN_PROGRAM_ID, - TOKEN_PROGRAM_ID, createMint, getAssociatedTokenAddressSync, getOrCreateAssociatedTokenAccount, mintTo, + TOKEN_PROGRAM_ID, } from "@solana/spl-token"; import { PublicKey } from "@solana/web3.js"; import { BankrunProvider } from "anchor-bankrun"; import BN from "bn.js"; import { startAnchor } from "solana-bankrun"; +import IDL from "../target/idl/fundraiser.json"; import type { Fundraiser } from "../target/types/fundraiser"; -import IDL from "../target/idl/fundraiser.json"; const PROGRAM_ID = new PublicKey(IDL.address); describe("fundraiser bankrun", async () => { - const context = await startAnchor( - "", - [{ name: "fundraiser", programId: PROGRAM_ID }], - [] - ); + const context = await startAnchor("", [{ name: "fundraiser", programId: PROGRAM_ID }], []); const provider = new BankrunProvider(context); anchor.setProvider(provider); const wallet = provider.wallet as anchor.Wallet; @@ -38,16 +34,12 @@ describe("fundraiser bankrun", async () => { const fundraiser = anchor.web3.PublicKey.findProgramAddressSync( [Buffer.from("fundraiser"), maker.publicKey.toBuffer()], - program.programId + program.programId, )[0]; const contributor = anchor.web3.PublicKey.findProgramAddressSync( - [ - Buffer.from("contributor"), - fundraiser.toBuffer(), - provider.publicKey.toBuffer(), - ], - program.programId + [Buffer.from("contributor"), fundraiser.toBuffer(), provider.publicKey.toBuffer()], + program.programId, )[0]; const confirm = async (signature: string): Promise => { @@ -65,32 +57,15 @@ describe("fundraiser bankrun", async () => { .then(confirm); console.log("\nAirdropped 1 SOL to maker", airdrop); - mint = await createMint( - provider.connection, - wallet.payer, - provider.publicKey, - provider.publicKey, - 6 - ); + mint = await createMint(provider.connection, wallet.payer, provider.publicKey, provider.publicKey, 6); console.log("Mint created", mint.toBase58()); contributorATA = ( - await getOrCreateAssociatedTokenAccount( - provider.connection, - wallet.payer, - mint, - wallet.publicKey - ) + await getOrCreateAssociatedTokenAccount(provider.connection, wallet.payer, mint, wallet.publicKey) ).address; - makerATA = ( - await getOrCreateAssociatedTokenAccount( - provider.connection, - wallet.payer, - mint, - maker.publicKey - ) - ).address; + makerATA = (await getOrCreateAssociatedTokenAccount(provider.connection, wallet.payer, mint, maker.publicKey)) + .address; const mintTx = await mintTo( provider.connection, @@ -98,7 +73,7 @@ describe("fundraiser bankrun", async () => { mint, contributorATA, provider.publicKey, - 1_000_000_0 + 1_000_000_0, ); console.log("Minted 10 tokens to contributor", mintTx); }); @@ -143,14 +118,9 @@ describe("fundraiser bankrun", async () => { console.log("\nContributed to fundraiser", tx); console.log("Your transaction signature", tx); - console.log( - "Vault balance", - (await provider.connection.getTokenAccountBalance(vault)).value.amount - ); + console.log("Vault balance", (await provider.connection.getTokenAccountBalance(vault)).value.amount); - const contributorAccount = await program.account.contributor.fetch( - contributor - ); + const contributorAccount = await program.account.contributor.fetch(contributor); console.log("Contributor balance", contributorAccount.amount.toString()); }); it("Contribute to Fundraiser", async () => { @@ -171,14 +141,9 @@ describe("fundraiser bankrun", async () => { console.log("\nContributed to fundraiser", tx); console.log("Your transaction signature", tx); - console.log( - "Vault balance", - (await provider.connection.getTokenAccountBalance(vault)).value.amount - ); + console.log("Vault balance", (await provider.connection.getTokenAccountBalance(vault)).value.amount); - const contributorAccount = await program.account.contributor.fetch( - contributor - ); + const contributorAccount = await program.account.contributor.fetch(contributor); console.log("Contributor balance", contributorAccount.amount.toString()); }); @@ -201,10 +166,7 @@ describe("fundraiser bankrun", async () => { console.log("\nContributed to fundraiser", tx); console.log("Your transaction signature", tx); - console.log( - "Vault balance", - (await provider.connection.getTokenAccountBalance(vault)).value.amount - ); + console.log("Vault balance", (await provider.connection.getTokenAccountBalance(vault)).value.amount); } catch (error) { console.log("\nError contributing to fundraiser"); console.log(error.msg); @@ -231,10 +193,7 @@ describe("fundraiser bankrun", async () => { console.log("\nChecked contributions"); console.log("Your transaction signature", tx); - console.log( - "Vault balance", - (await provider.connection.getTokenAccountBalance(vault)).value.amount - ); + console.log("Vault balance", (await provider.connection.getTokenAccountBalance(vault)).value.amount); } catch (error) { console.log("\nError checking contributions"); console.log(error.msg); @@ -244,9 +203,7 @@ describe("fundraiser bankrun", async () => { it("Refund Contributions", async () => { const vault = getAssociatedTokenAddressSync(mint, fundraiser, true); - const contributorAccount = await program.account.contributor.fetch( - contributor - ); + const contributorAccount = await program.account.contributor.fetch(contributor); console.log("\nContributor balance", contributorAccount.amount.toString()); const tx = await program.methods @@ -267,9 +224,6 @@ describe("fundraiser bankrun", async () => { console.log("\nRefunded contributions", tx); console.log("Your transaction signature", tx); - console.log( - "Vault balance", - (await provider.connection.getTokenAccountBalance(vault)).value.amount - ); + console.log("Vault balance", (await provider.connection.getTokenAccountBalance(vault)).value.amount); }); }); diff --git a/tokens/token-fundraiser/anchor/tests/fundraiser.ts b/tokens/token-fundraiser/anchor/tests/fundraiser.ts index 5f86d630f..8077df4f1 100644 --- a/tokens/token-fundraiser/anchor/tests/fundraiser.ts +++ b/tokens/token-fundraiser/anchor/tests/fundraiser.ts @@ -2,264 +2,225 @@ import type { Program } from "@anchor-lang/core"; import * as anchor from "@anchor-lang/core"; import type NodeWallet from "@anchor-lang/core/dist/cjs/nodewallet"; import { - ASSOCIATED_TOKEN_PROGRAM_ID, - TOKEN_PROGRAM_ID, - createMint, - getAssociatedTokenAddressSync, - getOrCreateAssociatedTokenAccount, - mintTo, + ASSOCIATED_TOKEN_PROGRAM_ID, + createMint, + getAssociatedTokenAddressSync, + getOrCreateAssociatedTokenAccount, + mintTo, + TOKEN_PROGRAM_ID, } from "@solana/spl-token"; import BN from "bn.js"; import type { Fundraiser } from "../target/types/fundraiser"; describe("fundraiser", () => { - // Configure the client to use the local cluster. - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); - - const program = anchor.workspace.Fundraiser as Program; - - const maker = anchor.web3.Keypair.generate(); - - let mint: anchor.web3.PublicKey; - - let contributorATA: anchor.web3.PublicKey; - - let makerATA: anchor.web3.PublicKey; - - const wallet = provider.wallet as NodeWallet; - - const fundraiser = anchor.web3.PublicKey.findProgramAddressSync( - [Buffer.from("fundraiser"), maker.publicKey.toBuffer()], - program.programId, - )[0]; - - const contributor = anchor.web3.PublicKey.findProgramAddressSync( - [ - Buffer.from("contributor"), - fundraiser.toBuffer(), - provider.publicKey.toBuffer(), - ], - program.programId, - )[0]; - - const confirm = async (signature: string): Promise => { - const block = await provider.connection.getLatestBlockhash(); - await provider.connection.confirmTransaction({ - signature, - ...block, - }); - return signature; - }; - - it("Test Preparation", async () => { - const airdrop = await provider.connection - .requestAirdrop(maker.publicKey, 1 * anchor.web3.LAMPORTS_PER_SOL) - .then(confirm); - console.log("\nAirdropped 1 SOL to maker", airdrop); - - mint = await createMint( - provider.connection, - wallet.payer, - provider.publicKey, - provider.publicKey, - 6, - ); - console.log("Mint created", mint.toBase58()); - - contributorATA = ( - await getOrCreateAssociatedTokenAccount( - provider.connection, - wallet.payer, - mint, - wallet.publicKey, - ) - ).address; - - makerATA = ( - await getOrCreateAssociatedTokenAccount( - provider.connection, - wallet.payer, - mint, - maker.publicKey, - ) - ).address; - - const mintTx = await mintTo( - provider.connection, - wallet.payer, - mint, - contributorATA, - provider.publicKey, - 1_000_000_0, - ); - console.log("Minted 10 tokens to contributor", mintTx); - }); - - it("Initialize Fundaraiser", async () => { - const vault = getAssociatedTokenAddressSync(mint, fundraiser, true); - - const tx = await program.methods - .initialize(new BN(30000000), 0) - .accountsPartial({ - maker: maker.publicKey, - fundraiser, - mintToRaise: mint, - vault, - systemProgram: anchor.web3.SystemProgram.programId, - tokenProgram: TOKEN_PROGRAM_ID, - associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID, - }) - .signers([maker]) - .rpc() - .then(confirm); - - console.log("\nInitialized fundraiser Account"); - console.log("Your transaction signature", tx); - }); - - it("Contribute to Fundraiser", async () => { - const vault = getAssociatedTokenAddressSync(mint, fundraiser, true); - - const tx = await program.methods - .contribute(new BN(1000000)) - .accountsPartial({ - contributor: provider.publicKey, - fundraiser, - contributorAccount: contributor, - contributorAta: contributorATA, - vault, - tokenProgram: TOKEN_PROGRAM_ID, - }) - .rpc() - .then(confirm); - - console.log("\nContributed to fundraiser", tx); - console.log("Your transaction signature", tx); - console.log( - "Vault balance", - (await provider.connection.getTokenAccountBalance(vault)).value.amount, - ); - - const contributorAccount = - await program.account.contributor.fetch(contributor); - console.log("Contributor balance", contributorAccount.amount.toString()); - }); - it("Contribute to Fundraiser", async () => { - const vault = getAssociatedTokenAddressSync(mint, fundraiser, true); - - const tx = await program.methods - .contribute(new BN(1000000)) - .accountsPartial({ - contributor: provider.publicKey, - fundraiser, - contributorAccount: contributor, - contributorAta: contributorATA, - vault, - tokenProgram: TOKEN_PROGRAM_ID, - }) - .rpc() - .then(confirm); - - console.log("\nContributed to fundraiser", tx); - console.log("Your transaction signature", tx); - console.log( - "Vault balance", - (await provider.connection.getTokenAccountBalance(vault)).value.amount, - ); - - const contributorAccount = - await program.account.contributor.fetch(contributor); - console.log("Contributor balance", contributorAccount.amount.toString()); - }); - - it("Contribute to Fundraiser - Robustness Test", async () => { - try { - const vault = getAssociatedTokenAddressSync(mint, fundraiser, true); - - const tx = await program.methods - .contribute(new BN(2000000)) - .accountsPartial({ - contributor: provider.publicKey, - fundraiser, - contributorAccount: contributor, - contributorAta: contributorATA, - vault, - tokenProgram: TOKEN_PROGRAM_ID, - }) - .rpc() - .then(confirm); - - console.log("\nContributed to fundraiser", tx); - console.log("Your transaction signature", tx); - console.log( - "Vault balance", - (await provider.connection.getTokenAccountBalance(vault)).value.amount, - ); - } catch (error) { - console.log("\nError contributing to fundraiser"); - console.log(error.msg); - } - }); - - it("Check contributions - Robustness Test", async () => { - try { - const vault = getAssociatedTokenAddressSync(mint, fundraiser, true); - - const tx = await program.methods - .checkContributions() - .accountsPartial({ - maker: maker.publicKey, - mintToRaise: mint, - fundraiser, - makerAta: makerATA, - vault, - tokenProgram: TOKEN_PROGRAM_ID, - }) - .signers([maker]) - .rpc() - .then(confirm); - - console.log("\nChecked contributions"); - console.log("Your transaction signature", tx); - console.log( - "Vault balance", - (await provider.connection.getTokenAccountBalance(vault)).value.amount, - ); - } catch (error) { - console.log("\nError checking contributions"); - console.log(error.msg); - } - }); - - it("Refund Contributions", async () => { - const vault = getAssociatedTokenAddressSync(mint, fundraiser, true); - - const contributorAccount = - await program.account.contributor.fetch(contributor); - console.log("\nContributor balance", contributorAccount.amount.toString()); - - const tx = await program.methods - .refund() - .accountsPartial({ - contributor: provider.publicKey, - maker: maker.publicKey, - mintToRaise: mint, - fundraiser, - contributorAccount: contributor, - contributorAta: contributorATA, - vault, - tokenProgram: TOKEN_PROGRAM_ID, - systemProgram: anchor.web3.SystemProgram.programId, - }) - .rpc() - .then(confirm); - - console.log("\nRefunded contributions", tx); - console.log("Your transaction signature", tx); - console.log( - "Vault balance", - (await provider.connection.getTokenAccountBalance(vault)).value.amount, - ); - }); + // Configure the client to use the local cluster. + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); + + const program = anchor.workspace.Fundraiser as Program; + + const maker = anchor.web3.Keypair.generate(); + + let mint: anchor.web3.PublicKey; + + let contributorATA: anchor.web3.PublicKey; + + let makerATA: anchor.web3.PublicKey; + + const wallet = provider.wallet as NodeWallet; + + const fundraiser = anchor.web3.PublicKey.findProgramAddressSync( + [Buffer.from("fundraiser"), maker.publicKey.toBuffer()], + program.programId, + )[0]; + + const contributor = anchor.web3.PublicKey.findProgramAddressSync( + [Buffer.from("contributor"), fundraiser.toBuffer(), provider.publicKey.toBuffer()], + program.programId, + )[0]; + + const confirm = async (signature: string): Promise => { + const block = await provider.connection.getLatestBlockhash(); + await provider.connection.confirmTransaction({ + signature, + ...block, + }); + return signature; + }; + + it("Test Preparation", async () => { + const airdrop = await provider.connection + .requestAirdrop(maker.publicKey, 1 * anchor.web3.LAMPORTS_PER_SOL) + .then(confirm); + console.log("\nAirdropped 1 SOL to maker", airdrop); + + mint = await createMint(provider.connection, wallet.payer, provider.publicKey, provider.publicKey, 6); + console.log("Mint created", mint.toBase58()); + + contributorATA = ( + await getOrCreateAssociatedTokenAccount(provider.connection, wallet.payer, mint, wallet.publicKey) + ).address; + + makerATA = (await getOrCreateAssociatedTokenAccount(provider.connection, wallet.payer, mint, maker.publicKey)) + .address; + + const mintTx = await mintTo( + provider.connection, + wallet.payer, + mint, + contributorATA, + provider.publicKey, + 1_000_000_0, + ); + console.log("Minted 10 tokens to contributor", mintTx); + }); + + it("Initialize Fundaraiser", async () => { + const vault = getAssociatedTokenAddressSync(mint, fundraiser, true); + + const tx = await program.methods + .initialize(new BN(30000000), 0) + .accountsPartial({ + maker: maker.publicKey, + fundraiser, + mintToRaise: mint, + vault, + systemProgram: anchor.web3.SystemProgram.programId, + tokenProgram: TOKEN_PROGRAM_ID, + associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID, + }) + .signers([maker]) + .rpc() + .then(confirm); + + console.log("\nInitialized fundraiser Account"); + console.log("Your transaction signature", tx); + }); + + it("Contribute to Fundraiser", async () => { + const vault = getAssociatedTokenAddressSync(mint, fundraiser, true); + + const tx = await program.methods + .contribute(new BN(1000000)) + .accountsPartial({ + contributor: provider.publicKey, + fundraiser, + contributorAccount: contributor, + contributorAta: contributorATA, + vault, + tokenProgram: TOKEN_PROGRAM_ID, + }) + .rpc() + .then(confirm); + + console.log("\nContributed to fundraiser", tx); + console.log("Your transaction signature", tx); + console.log("Vault balance", (await provider.connection.getTokenAccountBalance(vault)).value.amount); + + const contributorAccount = await program.account.contributor.fetch(contributor); + console.log("Contributor balance", contributorAccount.amount.toString()); + }); + it("Contribute to Fundraiser", async () => { + const vault = getAssociatedTokenAddressSync(mint, fundraiser, true); + + const tx = await program.methods + .contribute(new BN(1000000)) + .accountsPartial({ + contributor: provider.publicKey, + fundraiser, + contributorAccount: contributor, + contributorAta: contributorATA, + vault, + tokenProgram: TOKEN_PROGRAM_ID, + }) + .rpc() + .then(confirm); + + console.log("\nContributed to fundraiser", tx); + console.log("Your transaction signature", tx); + console.log("Vault balance", (await provider.connection.getTokenAccountBalance(vault)).value.amount); + + const contributorAccount = await program.account.contributor.fetch(contributor); + console.log("Contributor balance", contributorAccount.amount.toString()); + }); + + it("Contribute to Fundraiser - Robustness Test", async () => { + try { + const vault = getAssociatedTokenAddressSync(mint, fundraiser, true); + + const tx = await program.methods + .contribute(new BN(2000000)) + .accountsPartial({ + contributor: provider.publicKey, + fundraiser, + contributorAccount: contributor, + contributorAta: contributorATA, + vault, + tokenProgram: TOKEN_PROGRAM_ID, + }) + .rpc() + .then(confirm); + + console.log("\nContributed to fundraiser", tx); + console.log("Your transaction signature", tx); + console.log("Vault balance", (await provider.connection.getTokenAccountBalance(vault)).value.amount); + } catch (error) { + console.log("\nError contributing to fundraiser"); + console.log(error.msg); + } + }); + + it("Check contributions - Robustness Test", async () => { + try { + const vault = getAssociatedTokenAddressSync(mint, fundraiser, true); + + const tx = await program.methods + .checkContributions() + .accountsPartial({ + maker: maker.publicKey, + mintToRaise: mint, + fundraiser, + makerAta: makerATA, + vault, + tokenProgram: TOKEN_PROGRAM_ID, + }) + .signers([maker]) + .rpc() + .then(confirm); + + console.log("\nChecked contributions"); + console.log("Your transaction signature", tx); + console.log("Vault balance", (await provider.connection.getTokenAccountBalance(vault)).value.amount); + } catch (error) { + console.log("\nError checking contributions"); + console.log(error.msg); + } + }); + + it("Refund Contributions", async () => { + const vault = getAssociatedTokenAddressSync(mint, fundraiser, true); + + const contributorAccount = await program.account.contributor.fetch(contributor); + console.log("\nContributor balance", contributorAccount.amount.toString()); + + const tx = await program.methods + .refund() + .accountsPartial({ + contributor: provider.publicKey, + maker: maker.publicKey, + mintToRaise: mint, + fundraiser, + contributorAccount: contributor, + contributorAta: contributorATA, + vault, + tokenProgram: TOKEN_PROGRAM_ID, + systemProgram: anchor.web3.SystemProgram.programId, + }) + .rpc() + .then(confirm); + + console.log("\nRefunded contributions", tx); + console.log("Your transaction signature", tx); + console.log("Vault balance", (await provider.connection.getTokenAccountBalance(vault)).value.amount); + }); }); diff --git a/tokens/token-swap/anchor/package.json b/tokens/token-swap/anchor/package.json index 088bde1fe..1c904b54d 100644 --- a/tokens/token-swap/anchor/package.json +++ b/tokens/token-swap/anchor/package.json @@ -1,21 +1,21 @@ { - "type": "module", - "scripts": { - "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", - "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" - }, - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.3.8" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "prettier": "^2.6.2", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3" - } + "type": "module", + "scripts": { + "lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w", + "lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check" + }, + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.3.8" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "prettier": "^2.6.2", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3" + } } diff --git a/tokens/token-swap/anchor/tests/create-amm.ts b/tokens/token-swap/anchor/tests/create-amm.ts index 7eee680c4..081ac8b84 100644 --- a/tokens/token-swap/anchor/tests/create-amm.ts +++ b/tokens/token-swap/anchor/tests/create-amm.ts @@ -1,10 +1,10 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; -import { expect } from 'chai'; -import type { SwapExample } from '../target/types/swap_example'; -import { createValues, expectRevert, type TestValues } from './utils'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; +import { expect } from "chai"; +import type { SwapExample } from "../target/types/swap_example"; +import { createValues, expectRevert, type TestValues } from "./utils"; -describe('Create AMM', () => { +describe("Create AMM", () => { const provider = anchor.AnchorProvider.env(); const _connection = provider.connection; anchor.setProvider(provider); @@ -17,8 +17,11 @@ describe('Create AMM', () => { values = createValues(); }); - it('Creation', async () => { - await program.methods.createAmm(values.id, values.fee).accounts({ amm: values.ammKey, admin: values.admin.publicKey }).rpc(); + it("Creation", async () => { + await program.methods + .createAmm(values.id, values.fee) + .accounts({ amm: values.ammKey, admin: values.admin.publicKey }) + .rpc(); const ammAccount = await program.account.amm.fetch(values.ammKey); expect(ammAccount.id.toString()).to.equal(values.id.toString()); @@ -26,9 +29,14 @@ describe('Create AMM', () => { expect(ammAccount.fee.toString()).to.equal(values.fee.toString()); }); - it('Invalid fee', async () => { + it("Invalid fee", async () => { values.fee = 10000; - await expectRevert(program.methods.createAmm(values.id, values.fee).accounts({ amm: values.ammKey, admin: values.admin.publicKey }).rpc()); + await expectRevert( + program.methods + .createAmm(values.id, values.fee) + .accounts({ amm: values.ammKey, admin: values.admin.publicKey }) + .rpc(), + ); }); }); diff --git a/tokens/token-swap/anchor/tests/create-pool.ts b/tokens/token-swap/anchor/tests/create-pool.ts index cdab62af2..a8ff19609 100644 --- a/tokens/token-swap/anchor/tests/create-pool.ts +++ b/tokens/token-swap/anchor/tests/create-pool.ts @@ -1,10 +1,10 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; -import { PublicKey } from '@solana/web3.js'; -import type { SwapExample } from '../target/types/swap_example'; -import { createValues, expectRevert, mintingTokens, type TestValues } from './utils'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; +import { PublicKey } from "@solana/web3.js"; +import type { SwapExample } from "../target/types/swap_example"; +import { createValues, expectRevert, mintingTokens, type TestValues } from "./utils"; -describe('Create pool', () => { +describe("Create pool", () => { const provider = anchor.AnchorProvider.env(); const connection = provider.connection; anchor.setProvider(provider); @@ -16,7 +16,10 @@ describe('Create pool', () => { beforeEach(async () => { values = createValues(); - await program.methods.createAmm(values.id, values.fee).accounts({ amm: values.ammKey, admin: values.admin.publicKey }).rpc(); + await program.methods + .createAmm(values.id, values.fee) + .accounts({ amm: values.ammKey, admin: values.admin.publicKey }) + .rpc(); await mintingTokens({ connection, @@ -26,7 +29,7 @@ describe('Create pool', () => { }); }); - it('Creation', async () => { + it("Creation", async () => { await program.methods .createPool() .accounts({ @@ -42,7 +45,7 @@ describe('Create pool', () => { .rpc({ skipPreflight: true }); }); - it('Invalid mints', async () => { + it("Invalid mints", async () => { values = createValues({ mintBKeypair: values.mintAKeypair, poolKey: PublicKey.findProgramAddressSync( @@ -50,7 +53,12 @@ describe('Create pool', () => { program.programId, )[0], poolAuthority: PublicKey.findProgramAddressSync( - [values.id.toBuffer(), values.mintAKeypair.publicKey.toBuffer(), values.mintBKeypair.publicKey.toBuffer(), Buffer.from('authority')], + [ + values.id.toBuffer(), + values.mintAKeypair.publicKey.toBuffer(), + values.mintBKeypair.publicKey.toBuffer(), + Buffer.from("authority"), + ], program.programId, )[0], }); diff --git a/tokens/token-swap/anchor/tests/deposit-liquidity.ts b/tokens/token-swap/anchor/tests/deposit-liquidity.ts index 10b6d2fee..edf313ece 100644 --- a/tokens/token-swap/anchor/tests/deposit-liquidity.ts +++ b/tokens/token-swap/anchor/tests/deposit-liquidity.ts @@ -1,10 +1,10 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; -import { expect } from 'chai'; -import type { SwapExample } from '../target/types/swap_example'; -import { createValues, mintingTokens, type TestValues } from './utils'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; +import { expect } from "chai"; +import type { SwapExample } from "../target/types/swap_example"; +import { createValues, mintingTokens, type TestValues } from "./utils"; -describe('Deposit liquidity', () => { +describe("Deposit liquidity", () => { const provider = anchor.AnchorProvider.env(); const connection = provider.connection; anchor.setProvider(provider); @@ -16,7 +16,10 @@ describe('Deposit liquidity', () => { beforeEach(async () => { values = createValues(); - await program.methods.createAmm(values.id, values.fee).accounts({ amm: values.ammKey, admin: values.admin.publicKey }).rpc(); + await program.methods + .createAmm(values.id, values.fee) + .accounts({ amm: values.ammKey, admin: values.admin.publicKey }) + .rpc(); await mintingTokens({ connection, @@ -40,7 +43,7 @@ describe('Deposit liquidity', () => { .rpc(); }); - it('Deposit equal amounts', async () => { + it("Deposit equal amounts", async () => { await program.methods .depositLiquidity(values.depositAmountA, values.depositAmountA) .accounts({ @@ -60,7 +63,9 @@ describe('Deposit liquidity', () => { .rpc({ skipPreflight: true }); const depositTokenAccountLiquditiy = await connection.getTokenAccountBalance(values.liquidityAccount); - expect(depositTokenAccountLiquditiy.value.amount).to.equal(values.depositAmountA.sub(values.minimumLiquidity).toString()); + expect(depositTokenAccountLiquditiy.value.amount).to.equal( + values.depositAmountA.sub(values.minimumLiquidity).toString(), + ); const depositTokenAccountA = await connection.getTokenAccountBalance(values.holderAccountA); expect(depositTokenAccountA.value.amount).to.equal(values.defaultSupply.sub(values.depositAmountA).toString()); const depositTokenAccountB = await connection.getTokenAccountBalance(values.holderAccountB); diff --git a/tokens/token-swap/anchor/tests/swap.ts b/tokens/token-swap/anchor/tests/swap.ts index 71afb6c91..cf415ab67 100644 --- a/tokens/token-swap/anchor/tests/swap.ts +++ b/tokens/token-swap/anchor/tests/swap.ts @@ -1,11 +1,11 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; -import { BN } from 'bn.js'; -import { expect } from 'chai'; -import type { SwapExample } from '../target/types/swap_example'; -import { createValues, mintingTokens, type TestValues } from './utils'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; +import { BN } from "bn.js"; +import { expect } from "chai"; +import type { SwapExample } from "../target/types/swap_example"; +import { createValues, mintingTokens, type TestValues } from "./utils"; -describe('Swap', () => { +describe("Swap", () => { const provider = anchor.AnchorProvider.env(); const connection = provider.connection; anchor.setProvider(provider); @@ -17,7 +17,10 @@ describe('Swap', () => { beforeEach(async () => { values = createValues(); - await program.methods.createAmm(values.id, values.fee).accounts({ amm: values.ammKey, admin: values.admin.publicKey }).rpc(); + await program.methods + .createAmm(values.id, values.fee) + .accounts({ amm: values.ammKey, admin: values.admin.publicKey }) + .rpc(); await mintingTokens({ connection, @@ -59,7 +62,7 @@ describe('Swap', () => { .rpc({ skipPreflight: true }); }); - it('Swap from A to B', async () => { + it("Swap from A to B", async () => { const input = new BN(10 ** 6); await program.methods .swapExactTokensForTokens(true, input, new BN(100)) @@ -80,8 +83,14 @@ describe('Swap', () => { const traderTokenAccountA = await connection.getTokenAccountBalance(values.holderAccountA); const traderTokenAccountB = await connection.getTokenAccountBalance(values.holderAccountB); - expect(traderTokenAccountA.value.amount).to.equal(values.defaultSupply.sub(values.depositAmountA).sub(input).toString()); - expect(Number(traderTokenAccountB.value.amount)).to.be.greaterThan(values.defaultSupply.sub(values.depositAmountB).toNumber()); - expect(Number(traderTokenAccountB.value.amount)).to.be.lessThan(values.defaultSupply.sub(values.depositAmountB).add(input).toNumber()); + expect(traderTokenAccountA.value.amount).to.equal( + values.defaultSupply.sub(values.depositAmountA).sub(input).toString(), + ); + expect(Number(traderTokenAccountB.value.amount)).to.be.greaterThan( + values.defaultSupply.sub(values.depositAmountB).toNumber(), + ); + expect(Number(traderTokenAccountB.value.amount)).to.be.lessThan( + values.defaultSupply.sub(values.depositAmountB).add(input).toNumber(), + ); }); }); diff --git a/tokens/token-swap/anchor/tests/utils.ts b/tokens/token-swap/anchor/tests/utils.ts index 44b0b1079..979338266 100644 --- a/tokens/token-swap/anchor/tests/utils.ts +++ b/tokens/token-swap/anchor/tests/utils.ts @@ -1,7 +1,12 @@ -import * as anchor from '@anchor-lang/core'; -import { createMint, getAssociatedTokenAddressSync, getOrCreateAssociatedTokenAccount, mintTo } from '@solana/spl-token'; -import { type Connection, Keypair, PublicKey, type Signer } from '@solana/web3.js'; -import { BN } from 'bn.js'; +import * as anchor from "@anchor-lang/core"; +import { + createMint, + getAssociatedTokenAddressSync, + getOrCreateAssociatedTokenAccount, + mintTo, +} from "@solana/spl-token"; +import { type Connection, Keypair, PublicKey, type Signer } from "@solana/web3.js"; +import { BN } from "bn.js"; export async function sleep(seconds: number) { new Promise((resolve) => setTimeout(resolve, seconds * 1000)); @@ -11,10 +16,11 @@ export const generateSeededKeypair = (seed: string) => { return Keypair.fromSeed(anchor.utils.bytes.utf8.encode(anchor.utils.sha256.hash(seed)).slice(0, 32)); }; +// biome-ignore lint/suspicious/noExplicitAny: TODO: we should fix this, but we also will move these test to LiteSVM for Anchor 1.0 export const expectRevert = async (promise: Promise) => { try { await promise; - throw new Error('Expected a revert'); + throw new Error("Expected a revert"); } catch { return; } @@ -98,11 +104,11 @@ export function createValues(defaults?: TestValuesDefaults): TestValues { } const poolAuthority = PublicKey.findProgramAddressSync( - [ammKey.toBuffer(), mintAKeypair.publicKey.toBuffer(), mintBKeypair.publicKey.toBuffer(), Buffer.from('authority')], + [ammKey.toBuffer(), mintAKeypair.publicKey.toBuffer(), mintBKeypair.publicKey.toBuffer(), Buffer.from("authority")], anchor.workspace.SwapExample.programId, )[0]; const mintLiquidity = PublicKey.findProgramAddressSync( - [ammKey.toBuffer(), mintAKeypair.publicKey.toBuffer(), mintBKeypair.publicKey.toBuffer(), Buffer.from('liquidity')], + [ammKey.toBuffer(), mintAKeypair.publicKey.toBuffer(), mintBKeypair.publicKey.toBuffer(), Buffer.from("liquidity")], anchor.workspace.SwapExample.programId, )[0]; const poolKey = PublicKey.findProgramAddressSync( diff --git a/tokens/token-swap/anchor/tests/withdraw-liquidity.ts b/tokens/token-swap/anchor/tests/withdraw-liquidity.ts index e2f5ac7f0..33df6ee92 100644 --- a/tokens/token-swap/anchor/tests/withdraw-liquidity.ts +++ b/tokens/token-swap/anchor/tests/withdraw-liquidity.ts @@ -1,10 +1,10 @@ -import type { Program } from '@anchor-lang/core'; -import * as anchor from '@anchor-lang/core'; -import { expect } from 'chai'; -import type { SwapExample } from '../target/types/swap_example'; -import { createValues, mintingTokens, type TestValues } from './utils'; +import type { Program } from "@anchor-lang/core"; +import * as anchor from "@anchor-lang/core"; +import { expect } from "chai"; +import type { SwapExample } from "../target/types/swap_example"; +import { createValues, mintingTokens, type TestValues } from "./utils"; -describe('Withdraw liquidity', () => { +describe("Withdraw liquidity", () => { const provider = anchor.AnchorProvider.env(); const connection = provider.connection; anchor.setProvider(provider); @@ -16,7 +16,10 @@ describe('Withdraw liquidity', () => { beforeEach(async () => { values = createValues(); - await program.methods.createAmm(values.id, values.fee).accounts({ amm: values.ammKey, admin: values.admin.publicKey }).rpc(); + await program.methods + .createAmm(values.id, values.fee) + .accounts({ amm: values.ammKey, admin: values.admin.publicKey }) + .rpc(); await mintingTokens({ connection, @@ -58,7 +61,7 @@ describe('Withdraw liquidity', () => { .rpc({ skipPreflight: true }); }); - it('Withdraw everything', async () => { + it("Withdraw everything", async () => { await program.methods .withdrawLiquidity(values.depositAmountA.sub(values.minimumLiquidity)) .accounts({ @@ -81,10 +84,14 @@ describe('Withdraw liquidity', () => { const liquidityTokenAccount = await connection.getTokenAccountBalance(values.liquidityAccount); const depositTokenAccountA = await connection.getTokenAccountBalance(values.holderAccountA); const depositTokenAccountB = await connection.getTokenAccountBalance(values.holderAccountB); - expect(liquidityTokenAccount.value.amount).to.equal('0'); + expect(liquidityTokenAccount.value.amount).to.equal("0"); expect(Number(depositTokenAccountA.value.amount)).to.be.lessThan(values.defaultSupply.toNumber()); - expect(Number(depositTokenAccountA.value.amount)).to.be.greaterThan(values.defaultSupply.sub(values.depositAmountA).toNumber()); + expect(Number(depositTokenAccountA.value.amount)).to.be.greaterThan( + values.defaultSupply.sub(values.depositAmountA).toNumber(), + ); expect(Number(depositTokenAccountB.value.amount)).to.be.lessThan(values.defaultSupply.toNumber()); - expect(Number(depositTokenAccountB.value.amount)).to.be.greaterThan(values.defaultSupply.sub(values.depositAmountA).toNumber()); + expect(Number(depositTokenAccountB.value.amount)).to.be.greaterThan( + values.defaultSupply.sub(values.depositAmountA).toNumber(), + ); }); }); diff --git a/tokens/transfer-tokens/anchor/package.json b/tokens/transfer-tokens/anchor/package.json index 5fce1099c..bead3eb65 100644 --- a/tokens/transfer-tokens/anchor/package.json +++ b/tokens/transfer-tokens/anchor/package.json @@ -1,23 +1,23 @@ { - "type": "module", - "dependencies": { - "@anchor-lang/core": "1.0.0-rc.5", - "@solana/spl-token": "^0.3.8", - "bn.js": "^5.2.1" - }, - "scripts": { - "postinstall": "zx prepare.mjs" - }, - "devDependencies": { - "@types/bn.js": "^5.1.0", - "@types/chai": "^4.3.0", - "@types/mocha": "^9.0.0", - "anchor-bankrun": "^0.4.0", - "chai": "^4.3.4", - "mocha": "^9.0.3", - "solana-bankrun": "^0.3.0", - "ts-mocha": "^10.0.0", - "typescript": "^5.3.3", - "zx": "^8.1.4" - } + "type": "module", + "dependencies": { + "@anchor-lang/core": "1.0.0-rc.5", + "@solana/spl-token": "^0.3.8", + "bn.js": "^5.2.1" + }, + "scripts": { + "postinstall": "zx prepare.mjs" + }, + "devDependencies": { + "@types/bn.js": "^5.1.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^9.0.0", + "anchor-bankrun": "^0.4.0", + "chai": "^4.3.4", + "mocha": "^9.0.3", + "solana-bankrun": "^0.3.0", + "ts-mocha": "^10.0.0", + "typescript": "^5.3.3", + "zx": "^8.1.4" + } } diff --git a/tokens/transfer-tokens/anchor/prepare.mjs b/tokens/transfer-tokens/anchor/prepare.mjs index 7c5ec464b..fb6b26225 100644 --- a/tokens/transfer-tokens/anchor/prepare.mjs +++ b/tokens/transfer-tokens/anchor/prepare.mjs @@ -1,17 +1,17 @@ #!/usr/bin/env zx -import { mkdir, rm } from 'node:fs/promises'; -import { join } from 'node:path'; -import { $ } from 'zx'; +import { mkdir, rm } from "node:fs/promises"; +import { join } from "node:path"; +import { $ } from "zx"; const programs = [ { - id: 'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s', - name: 'token_metadata.so', + id: "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s", + name: "token_metadata.so", }, ]; -const outputDir = 'tests/fixtures'; +const outputDir = "tests/fixtures"; const overwrite = true; try { diff --git a/tokens/transfer-tokens/anchor/tests/bankrun.test.ts b/tokens/transfer-tokens/anchor/tests/bankrun.test.ts index 175cda746..a0bc25050 100644 --- a/tokens/transfer-tokens/anchor/tests/bankrun.test.ts +++ b/tokens/transfer-tokens/anchor/tests/bankrun.test.ts @@ -8,9 +8,7 @@ import IDL from "../target/idl/transfer_tokens.json"; import type { TransferTokens } from "../target/types/transfer_tokens"; const PROGRAM_ID = new PublicKey(IDL.address); -const METADATA_PROGRAM_ID = new PublicKey( - "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s", -); +const METADATA_PROGRAM_ID = new PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"); describe("Transfer Tokens Bankrun", async () => { const context = await startAnchor( @@ -39,16 +37,10 @@ describe("Transfer Tokens Bankrun", async () => { const recipient = new Keypair(); // Derive the associated token address account for the mint and payer. - const senderTokenAddress = getAssociatedTokenAddressSync( - mintKeypair.publicKey, - payer.publicKey, - ); + const senderTokenAddress = getAssociatedTokenAddressSync(mintKeypair.publicKey, payer.publicKey); // Derive the associated token address account for the mint and recipient. - const recepientTokenAddress = getAssociatedTokenAddressSync( - mintKeypair.publicKey, - recipient.publicKey, - ); + const recepientTokenAddress = getAssociatedTokenAddressSync(mintKeypair.publicKey, recipient.publicKey); it("Create an SPL Token!", async () => { const transactionSignature = await program.methods diff --git a/tokens/transfer-tokens/anchor/tests/test.ts b/tokens/transfer-tokens/anchor/tests/test.ts index 4bc0c8213..77a1b0a6d 100644 --- a/tokens/transfer-tokens/anchor/tests/test.ts +++ b/tokens/transfer-tokens/anchor/tests/test.ts @@ -5,87 +5,80 @@ import { BN } from "bn.js"; import type { TransferTokens } from "../target/types/transfer_tokens"; describe("Transfer Tokens", () => { - const provider = anchor.AnchorProvider.env(); - anchor.setProvider(provider); - const payer = provider.wallet as anchor.Wallet; - const program = anchor.workspace - .TransferTokens as anchor.Program; + const provider = anchor.AnchorProvider.env(); + anchor.setProvider(provider); + const payer = provider.wallet as anchor.Wallet; + const program = anchor.workspace.TransferTokens as anchor.Program; - const metadata = { - name: "Solana Gold", - symbol: "GOLDSOL", - uri: "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json", - }; + const metadata = { + name: "Solana Gold", + symbol: "GOLDSOL", + uri: "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json", + }; - // Generate new keypair to use as address for mint account. - const mintKeypair = new Keypair(); + // Generate new keypair to use as address for mint account. + const mintKeypair = new Keypair(); - // Generate new keypair to use as address for recipient wallet. - const recipient = new Keypair(); + // Generate new keypair to use as address for recipient wallet. + const recipient = new Keypair(); - // Derive the associated token address account for the mint and payer. - const senderTokenAddress = getAssociatedTokenAddressSync( - mintKeypair.publicKey, - payer.publicKey, - ); + // Derive the associated token address account for the mint and payer. + const senderTokenAddress = getAssociatedTokenAddressSync(mintKeypair.publicKey, payer.publicKey); - // Derive the associated token address account for the mint and recipient. - const recepientTokenAddress = getAssociatedTokenAddressSync( - mintKeypair.publicKey, - recipient.publicKey, - ); + // Derive the associated token address account for the mint and recipient. + const recepientTokenAddress = getAssociatedTokenAddressSync(mintKeypair.publicKey, recipient.publicKey); - it("Create an SPL Token!", async () => { - const transactionSignature = await program.methods - .createToken(metadata.name, metadata.symbol, metadata.uri) - .accounts({ - payer: payer.publicKey, - mintAccount: mintKeypair.publicKey, - }) - .signers([mintKeypair]) - .rpc(); + it("Create an SPL Token!", async () => { + const transactionSignature = await program.methods + .createToken(metadata.name, metadata.symbol, metadata.uri) + .accounts({ + payer: payer.publicKey, + mintAccount: mintKeypair.publicKey, + }) + .signers([mintKeypair]) + .rpc(); - console.log("Success!"); - console.log(` Mint Address: ${mintKeypair.publicKey}`); - console.log(` Transaction Signature: ${transactionSignature}`); - }); + console.log("Success!"); + console.log(` Mint Address: ${mintKeypair.publicKey}`); + console.log(` Transaction Signature: ${transactionSignature}`); + }); - it("Mint tokens!", async () => { - // Amount of tokens to mint. - const amount = new BN(100); + it("Mint tokens!", async () => { + // Amount of tokens to mint. + const amount = new BN(100); - // Mint the tokens to the associated token account. - const transactionSignature = await program.methods - .mintToken(amount) - .accounts({ - mintAuthority: payer.publicKey, - recipient: payer.publicKey, - mintAccount: mintKeypair.publicKey, - associatedTokenAccount: senderTokenAddress, - }) - .rpc(); + // Mint the tokens to the associated token account. + const transactionSignature = await program.methods + .mintToken(amount) + .accounts({ + mintAuthority: payer.publicKey, + recipient: payer.publicKey, + mintAccount: mintKeypair.publicKey, + associatedTokenAccount: senderTokenAddress, + }) + .rpc(); - console.log("Success!"); - console.log(` Associated Token Account Address: ${senderTokenAddress}`); - console.log(` Transaction Signature: ${transactionSignature}`); - }); + console.log("Success!"); + console.log(` Associated Token Account Address: ${senderTokenAddress}`); + console.log(` Transaction Signature: ${transactionSignature}`); + }); - it("Transfer tokens!", async () => { - // Amount of tokens to transfer. - const amount = new BN(50); + it("Transfer tokens!", async () => { + // Amount of tokens to transfer. + const amount = new BN(50); - const transactionSignature = await program.methods - .transferTokens(amount) - .accounts({ - sender: payer.publicKey, - recipient: recipient.publicKey, - mintAccount: mintKeypair.publicKey, - senderTokenAccount: senderTokenAddress, - recipientTokenAccount: recepientTokenAddress, - }) - .rpc(); + const transactionSignature = await program.methods + .transferTokens(amount) + .accounts({ + sender: payer.publicKey, + recipient: recipient.publicKey, + mintAccount: mintKeypair.publicKey, + senderTokenAccount: senderTokenAddress, + recipientTokenAccount: recepientTokenAddress, + }) + .rpc(); - console.log("Success!"); - console.log(` Transaction Signature: ${transactionSignature}`); - }); + console.log("Success!"); + console.log(` Transaction Signature: ${transactionSignature}`); + }); }); diff --git a/tokens/transfer-tokens/native/tests/instructions.ts b/tokens/transfer-tokens/native/tests/instructions.ts index c9fa9b36d..6a3d92b20 100644 --- a/tokens/transfer-tokens/native/tests/instructions.ts +++ b/tokens/transfer-tokens/native/tests/instructions.ts @@ -1,4 +1,4 @@ -import * as borsh from 'borsh'; +import * as borsh from "borsh"; export enum MyInstruction { Create = 0, @@ -9,27 +9,27 @@ export enum MyInstruction { export const CreateTokenArgsSchema = { struct: { - instruction: 'u8', - token_title: 'string', - token_symbol: 'string', - token_uri: 'string', - decimals: 'u8', + instruction: "u8", + token_title: "string", + token_symbol: "string", + token_uri: "string", + decimals: "u8", }, }; -export const MintNftArgsSchema = { struct: { instruction: 'u8' } }; +export const MintNftArgsSchema = { struct: { instruction: "u8" } }; export const MintSplArgsSchema = { struct: { - instruction: 'u8', - quantity: 'u64', + instruction: "u8", + quantity: "u64", }, }; export const TransferTokensArgsSchema = { struct: { - instruction: 'u8', - quantity: 'u64', + instruction: "u8", + quantity: "u64", }, }; diff --git a/tokens/transfer-tokens/native/tests/test.ts b/tokens/transfer-tokens/native/tests/test.ts index 10a225c23..cfa947842 100644 --- a/tokens/transfer-tokens/native/tests/test.ts +++ b/tokens/transfer-tokens/native/tests/test.ts @@ -1,6 +1,6 @@ -import { Buffer } from 'node:buffer'; -import { PROGRAM_ID as TOKEN_METADATA_PROGRAM_ID } from '@metaplex-foundation/mpl-token-metadata'; -import { ASSOCIATED_TOKEN_PROGRAM_ID, getAssociatedTokenAddress, TOKEN_PROGRAM_ID } from '@solana/spl-token'; +import { Buffer } from "node:buffer"; +import { PROGRAM_ID as TOKEN_METADATA_PROGRAM_ID } from "@metaplex-foundation/mpl-token-metadata"; +import { ASSOCIATED_TOKEN_PROGRAM_ID, getAssociatedTokenAddress, TOKEN_PROGRAM_ID } from "@solana/spl-token"; import { Connection, Keypair, @@ -10,36 +10,44 @@ import { sendAndConfirmTransaction, Transaction, TransactionInstruction, -} from '@solana/web3.js'; -import { BN } from 'bn.js'; -import { borshSerialize, CreateTokenArgsSchema, MintNftArgsSchema, MintSplArgsSchema, TransferTokensArgsSchema, MyInstruction } from './instructions'; +} from "@solana/web3.js"; +import { BN } from "bn.js"; +import { + borshSerialize, + CreateTokenArgsSchema, + MintNftArgsSchema, + MintSplArgsSchema, + MyInstruction, + TransferTokensArgsSchema, +} from "./instructions"; function createKeypairFromFile(path: string): Keypair { - return Keypair.fromSecretKey(Uint8Array.from(JSON.parse(require('node:fs').readFileSync(path, 'utf-8')))); + return Keypair.fromSecretKey(Uint8Array.from(JSON.parse(require("node:fs").readFileSync(path, "utf-8")))); } -describe('Transferring Tokens', async () => { +describe("Transferring Tokens", async () => { // const connection = new Connection(`http://localhost:8899`, 'confirmed'); - const connection = new Connection('https://api.devnet.solana.com/', 'confirmed'); - const payer = createKeypairFromFile(`${require('node:os').homedir()}/.config/solana/id.json`); - const program = createKeypairFromFile('./program/target/deploy/program-keypair.json'); + const connection = new Connection("https://api.devnet.solana.com/", "confirmed"); + const payer = createKeypairFromFile(`${require("node:os").homedir()}/.config/solana/id.json`); + const program = createKeypairFromFile("./program/target/deploy/program-keypair.json"); const tokenMintKeypair: Keypair = Keypair.generate(); const nftMintKeypair: Keypair = Keypair.generate(); const recipientWallet = Keypair.generate(); - it('Create an SPL Token!', async () => { + it("Create an SPL Token!", async () => { const metadataAddress = PublicKey.findProgramAddressSync( - [Buffer.from('metadata'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), tokenMintKeypair.publicKey.toBuffer()], + [Buffer.from("metadata"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), tokenMintKeypair.publicKey.toBuffer()], TOKEN_METADATA_PROGRAM_ID, )[0]; const instructionData = borshSerialize(CreateTokenArgsSchema, { instruction: MyInstruction.Create, - token_title: 'Solana Gold', - token_symbol: 'GOLDSOL', - token_uri: 'https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json', + token_title: "Solana Gold", + token_symbol: "GOLDSOL", + token_uri: + "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json", decimals: 9, }); @@ -68,22 +76,23 @@ describe('Transferring Tokens', async () => { const sx = await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer, tokenMintKeypair]); - console.log('Success!'); + console.log("Success!"); console.log(` Mint Address: ${tokenMintKeypair.publicKey}`); console.log(` Tx Signature: ${sx}`); }); - it('Create an NFT!', async () => { + it("Create an NFT!", async () => { const metadataAddress = PublicKey.findProgramAddressSync( - [Buffer.from('metadata'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), nftMintKeypair.publicKey.toBuffer()], + [Buffer.from("metadata"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), nftMintKeypair.publicKey.toBuffer()], TOKEN_METADATA_PROGRAM_ID, )[0]; const instructionData = borshSerialize(CreateTokenArgsSchema, { instruction: MyInstruction.Create, - token_title: 'Homer NFT', - token_symbol: 'HOMR', - token_uri: 'https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/nft.json', + token_title: "Homer NFT", + token_symbol: "HOMR", + token_uri: + "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/nft.json", decimals: 0, }); @@ -108,12 +117,12 @@ describe('Transferring Tokens', async () => { const sx = await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer, nftMintKeypair]); - console.log('Success!'); + console.log("Success!"); console.log(` Mint Address: ${nftMintKeypair.publicKey}`); console.log(` Tx Signature: ${sx}`); }); - it('Mint some tokens to your wallet!', async () => { + it("Mint some tokens to your wallet!", async () => { const associatedTokenAccountAddress = await getAssociatedTokenAddress(tokenMintKeypair.publicKey, payer.publicKey); const instructionData = borshSerialize(MintSplArgsSchema, { @@ -149,19 +158,24 @@ describe('Transferring Tokens', async () => { const sx = await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer]); - console.log('Success!'); + console.log("Success!"); console.log(` ATA Address: ${associatedTokenAccountAddress}`); console.log(` Tx Signature: ${sx}`); }); - it('Mint the NFT to your wallet!', async () => { + it("Mint the NFT to your wallet!", async () => { const metadataAddress = PublicKey.findProgramAddressSync( - [Buffer.from('metadata'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), nftMintKeypair.publicKey.toBuffer()], + [Buffer.from("metadata"), TOKEN_METADATA_PROGRAM_ID.toBuffer(), nftMintKeypair.publicKey.toBuffer()], TOKEN_METADATA_PROGRAM_ID, )[0]; const editionAddress = PublicKey.findProgramAddressSync( - [Buffer.from('metadata'), TOKEN_METADATA_PROGRAM_ID.toBuffer(), nftMintKeypair.publicKey.toBuffer(), Buffer.from('edition')], + [ + Buffer.from("metadata"), + TOKEN_METADATA_PROGRAM_ID.toBuffer(), + nftMintKeypair.publicKey.toBuffer(), + Buffer.from("edition"), + ], TOKEN_METADATA_PROGRAM_ID, )[0]; @@ -203,22 +217,25 @@ describe('Transferring Tokens', async () => { const sx = await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer]); - console.log('Success!'); + console.log("Success!"); console.log(` ATA Address: ${associatedTokenAccountAddress}`); console.log(` Tx Signature: ${sx}`); }); - it('Prep a new test wallet for transfers', async () => { + it("Prep a new test wallet for transfers", async () => { await connection.confirmTransaction( await connection.requestAirdrop(recipientWallet.publicKey, await connection.getMinimumBalanceForRentExemption(0)), ); console.log(`Recipient Pubkey: ${recipientWallet.publicKey}`); }); - it('Transfer tokens to another wallet!', async () => { + it("Transfer tokens to another wallet!", async () => { const fromAssociatedTokenAddress = await getAssociatedTokenAddress(tokenMintKeypair.publicKey, payer.publicKey); console.log(`Owner Token Address: ${fromAssociatedTokenAddress}`); - const toAssociatedTokenAddress = await getAssociatedTokenAddress(tokenMintKeypair.publicKey, recipientWallet.publicKey); + const toAssociatedTokenAddress = await getAssociatedTokenAddress( + tokenMintKeypair.publicKey, + recipientWallet.publicKey, + ); console.log(`Recipient Token Address: ${toAssociatedTokenAddress}`); const transferToInstructionData = borshSerialize(TransferTokensArgsSchema, { @@ -254,13 +271,18 @@ describe('Transferring Tokens', async () => { data: transferToInstructionData, }); - await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer, recipientWallet], { skipPreflight: true }); + await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer, recipientWallet], { + skipPreflight: true, + }); }); - it('Transfer NFT to another wallet!', async () => { + it("Transfer NFT to another wallet!", async () => { const fromAssociatedTokenAddress = await getAssociatedTokenAddress(nftMintKeypair.publicKey, payer.publicKey); console.log(`Owner Token Address: ${fromAssociatedTokenAddress}`); - const toAssociatedTokenAddress = await getAssociatedTokenAddress(nftMintKeypair.publicKey, recipientWallet.publicKey); + const toAssociatedTokenAddress = await getAssociatedTokenAddress( + nftMintKeypair.publicKey, + recipientWallet.publicKey, + ); console.log(`Recipient Token Address: ${toAssociatedTokenAddress}`); const transferToInstructionData = borshSerialize(TransferTokensArgsSchema, { @@ -292,6 +314,8 @@ describe('Transferring Tokens', async () => { data: transferToInstructionData, }); - await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer, recipientWallet], { skipPreflight: true }); + await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer, recipientWallet], { + skipPreflight: true, + }); }); }); diff --git a/tools/shank-and-solita/native/.solitarc.js b/tools/shank-and-solita/native/.solitarc.js index e42bad663..a02dc623f 100644 --- a/tools/shank-and-solita/native/.solitarc.js +++ b/tools/shank-and-solita/native/.solitarc.js @@ -1,12 +1,12 @@ -const path = require('node:path'); -const programDir = path.join(__dirname, 'program'); -const idlDir = path.join(programDir, 'idl'); -const sdkDir = path.join(__dirname, 'tests', 'generated'); -const binaryInstallDir = path.join(__dirname, '.crates'); +const path = require("node:path"); +const programDir = path.join(__dirname, "program"); +const idlDir = path.join(programDir, "idl"); +const sdkDir = path.join(__dirname, "tests", "generated"); +const binaryInstallDir = path.join(__dirname, ".crates"); module.exports = { - idlGenerator: 'shank', - programName: 'car_rental_service', + idlGenerator: "shank", + programName: "car_rental_service", idlDir, sdkDir, binaryInstallDir, diff --git a/tools/shank-and-solita/native/tests/generated/accounts/Car.ts b/tools/shank-and-solita/native/tests/generated/accounts/Car.ts index 5d67a76f2..9b046922d 100644 --- a/tools/shank-and-solita/native/tests/generated/accounts/Car.ts +++ b/tools/shank-and-solita/native/tests/generated/accounts/Car.ts @@ -5,9 +5,9 @@ * See: https://github.com/metaplex-foundation/solita */ -import * as beet from '@metaplex-foundation/beet'; -import * as beetSolana from '@metaplex-foundation/beet-solana'; -import * as web3 from '@solana/web3.js'; +import * as beet from "@metaplex-foundation/beet"; +import * as beetSolana from "@metaplex-foundation/beet-solana"; +import * as web3 from "@solana/web3.js"; /** * Arguments used to create {@link Car} @@ -72,7 +72,7 @@ export class Car implements CarArgs { * * @param programId - the program that owns the accounts we are filtering */ - static gpaBuilder(programId: web3.PublicKey = new web3.PublicKey('8avNGHVXDwsELJaWMSoUZ44CirQd4zyU9Ez4ZmP4jNjZ')) { + static gpaBuilder(programId: web3.PublicKey = new web3.PublicKey("8avNGHVXDwsELJaWMSoUZ44CirQd4zyU9Ez4ZmP4jNjZ")) { return beetSolana.GpaBuilder.fromStruct(programId, carBeet); } @@ -112,7 +112,11 @@ export class Car implements CarArgs { * depends on them * @param connection used to retrieve the rent exemption information */ - static async getMinimumBalanceForRentExemption(args: CarArgs, connection: web3.Connection, commitment?: web3.Commitment): Promise { + static async getMinimumBalanceForRentExemption( + args: CarArgs, + connection: web3.Connection, + commitment?: web3.Commitment, + ): Promise { return connection.getMinimumBalanceForRentExemption(Car.byteSize(args), commitment); } @@ -135,10 +139,10 @@ export class Car implements CarArgs { */ export const carBeet = new beet.FixableBeetStruct( [ - ['year', beet.u16], - ['make', beet.utf8String], - ['model', beet.utf8String], + ["year", beet.u16], + ["make", beet.utf8String], + ["model", beet.utf8String], ], Car.fromArgs, - 'Car', + "Car", ); diff --git a/tools/shank-and-solita/native/tests/generated/accounts/RentalOrder.ts b/tools/shank-and-solita/native/tests/generated/accounts/RentalOrder.ts index ea2923a74..458861608 100644 --- a/tools/shank-and-solita/native/tests/generated/accounts/RentalOrder.ts +++ b/tools/shank-and-solita/native/tests/generated/accounts/RentalOrder.ts @@ -5,10 +5,10 @@ * See: https://github.com/metaplex-foundation/solita */ -import * as beet from '@metaplex-foundation/beet'; -import * as beetSolana from '@metaplex-foundation/beet-solana'; -import * as web3 from '@solana/web3.js'; -import { RentalOrderStatus, rentalOrderStatusBeet } from '../types/RentalOrderStatus'; +import * as beet from "@metaplex-foundation/beet"; +import * as beetSolana from "@metaplex-foundation/beet-solana"; +import * as web3 from "@solana/web3.js"; +import { RentalOrderStatus, rentalOrderStatusBeet } from "../types/RentalOrderStatus"; /** * Arguments used to create {@link RentalOrder} @@ -79,7 +79,7 @@ export class RentalOrder implements RentalOrderArgs { * * @param programId - the program that owns the accounts we are filtering */ - static gpaBuilder(programId: web3.PublicKey = new web3.PublicKey('8avNGHVXDwsELJaWMSoUZ44CirQd4zyU9Ez4ZmP4jNjZ')) { + static gpaBuilder(programId: web3.PublicKey = new web3.PublicKey("8avNGHVXDwsELJaWMSoUZ44CirQd4zyU9Ez4ZmP4jNjZ")) { return beetSolana.GpaBuilder.fromStruct(programId, rentalOrderBeet); } @@ -119,7 +119,11 @@ export class RentalOrder implements RentalOrderArgs { * depends on them * @param connection used to retrieve the rent exemption information */ - static async getMinimumBalanceForRentExemption(args: RentalOrderArgs, connection: web3.Connection, commitment?: web3.Commitment): Promise { + static async getMinimumBalanceForRentExemption( + args: RentalOrderArgs, + connection: web3.Connection, + commitment?: web3.Commitment, + ): Promise { return connection.getMinimumBalanceForRentExemption(RentalOrder.byteSize(args), commitment); } @@ -135,7 +139,7 @@ export class RentalOrder implements RentalOrderArgs { returnDate: this.returnDate, price: (() => { const x = <{ toNumber: () => number }>this.price; - if (typeof x.toNumber === 'function') { + if (typeof x.toNumber === "function") { try { return x.toNumber(); } catch (_) { @@ -155,13 +159,13 @@ export class RentalOrder implements RentalOrderArgs { */ export const rentalOrderBeet = new beet.FixableBeetStruct( [ - ['car', beetSolana.publicKey], - ['name', beet.utf8String], - ['pickUpDate', beet.utf8String], - ['returnDate', beet.utf8String], - ['price', beet.u64], - ['status', rentalOrderStatusBeet], + ["car", beetSolana.publicKey], + ["name", beet.utf8String], + ["pickUpDate", beet.utf8String], + ["returnDate", beet.utf8String], + ["price", beet.u64], + ["status", rentalOrderStatusBeet], ], RentalOrder.fromArgs, - 'RentalOrder', + "RentalOrder", ); diff --git a/tools/shank-and-solita/native/tests/generated/accounts/index.ts b/tools/shank-and-solita/native/tests/generated/accounts/index.ts index 7c593175c..6b514469d 100644 --- a/tools/shank-and-solita/native/tests/generated/accounts/index.ts +++ b/tools/shank-and-solita/native/tests/generated/accounts/index.ts @@ -1,7 +1,7 @@ -export * from './Car'; -export * from './RentalOrder'; +export * from "./Car"; +export * from "./RentalOrder"; -import { Car } from './Car'; -import { RentalOrder } from './RentalOrder'; +import { Car } from "./Car"; +import { RentalOrder } from "./RentalOrder"; export const accountProviders = { Car, RentalOrder }; diff --git a/tools/shank-and-solita/native/tests/generated/index.ts b/tools/shank-and-solita/native/tests/generated/index.ts index 046f79c19..deb4a0914 100644 --- a/tools/shank-and-solita/native/tests/generated/index.ts +++ b/tools/shank-and-solita/native/tests/generated/index.ts @@ -1,8 +1,8 @@ -import { PublicKey } from '@solana/web3.js'; +import { PublicKey } from "@solana/web3.js"; -export * from './accounts'; -export * from './instructions'; -export * from './types'; +export * from "./accounts"; +export * from "./instructions"; +export * from "./types"; /** * Program address @@ -10,7 +10,7 @@ export * from './types'; * @category constants * @category generated */ -export const PROGRAM_ADDRESS = '8avNGHVXDwsELJaWMSoUZ44CirQd4zyU9Ez4ZmP4jNjZ'; +export const PROGRAM_ADDRESS = "8avNGHVXDwsELJaWMSoUZ44CirQd4zyU9Ez4ZmP4jNjZ"; /** * Program public key diff --git a/tools/shank-and-solita/native/tests/generated/instructions/AddCar.ts b/tools/shank-and-solita/native/tests/generated/instructions/AddCar.ts index d5cd995da..38a644edb 100644 --- a/tools/shank-and-solita/native/tests/generated/instructions/AddCar.ts +++ b/tools/shank-and-solita/native/tests/generated/instructions/AddCar.ts @@ -5,9 +5,9 @@ * See: https://github.com/metaplex-foundation/solita */ -import * as beet from '@metaplex-foundation/beet'; -import * as web3 from '@solana/web3.js'; -import { type AddCarArgs, addCarArgsBeet } from '../types/AddCarArgs'; +import * as beet from "@metaplex-foundation/beet"; +import * as web3 from "@solana/web3.js"; +import { type AddCarArgs, addCarArgsBeet } from "../types/AddCarArgs"; /** * @category Instructions @@ -28,10 +28,10 @@ export const AddCarStruct = new beet.FixableBeetArgsStruct< } >( [ - ['instructionDiscriminator', beet.u8], - ['addCarArgs', addCarArgsBeet], + ["instructionDiscriminator", beet.u8], + ["addCarArgs", addCarArgsBeet], ], - 'AddCarInstructionArgs', + "AddCarInstructionArgs", ); /** * Accounts required by the _AddCar_ instruction @@ -63,7 +63,7 @@ export const addCarInstructionDiscriminator = 0; export function createAddCarInstruction( accounts: AddCarInstructionAccounts, args: AddCarInstructionArgs, - programId = new web3.PublicKey('8avNGHVXDwsELJaWMSoUZ44CirQd4zyU9Ez4ZmP4jNjZ'), + programId = new web3.PublicKey("8avNGHVXDwsELJaWMSoUZ44CirQd4zyU9Ez4ZmP4jNjZ"), ) { const [data] = AddCarStruct.serialize({ instructionDiscriminator: addCarInstructionDiscriminator, diff --git a/tools/shank-and-solita/native/tests/generated/instructions/BookRental.ts b/tools/shank-and-solita/native/tests/generated/instructions/BookRental.ts index 1e6bb23de..4b2ec9e2a 100644 --- a/tools/shank-and-solita/native/tests/generated/instructions/BookRental.ts +++ b/tools/shank-and-solita/native/tests/generated/instructions/BookRental.ts @@ -5,9 +5,9 @@ * See: https://github.com/metaplex-foundation/solita */ -import * as beet from '@metaplex-foundation/beet'; -import * as web3 from '@solana/web3.js'; -import { type BookRentalArgs, bookRentalArgsBeet } from '../types/BookRentalArgs'; +import * as beet from "@metaplex-foundation/beet"; +import * as web3 from "@solana/web3.js"; +import { type BookRentalArgs, bookRentalArgsBeet } from "../types/BookRentalArgs"; /** * @category Instructions @@ -28,10 +28,10 @@ export const BookRentalStruct = new beet.FixableBeetArgsStruct< } >( [ - ['instructionDiscriminator', beet.u8], - ['bookRentalArgs', bookRentalArgsBeet], + ["instructionDiscriminator", beet.u8], + ["bookRentalArgs", bookRentalArgsBeet], ], - 'BookRentalInstructionArgs', + "BookRentalInstructionArgs", ); /** * Accounts required by the _BookRental_ instruction @@ -65,7 +65,7 @@ export const bookRentalInstructionDiscriminator = 1; export function createBookRentalInstruction( accounts: BookRentalInstructionAccounts, args: BookRentalInstructionArgs, - programId = new web3.PublicKey('8avNGHVXDwsELJaWMSoUZ44CirQd4zyU9Ez4ZmP4jNjZ'), + programId = new web3.PublicKey("8avNGHVXDwsELJaWMSoUZ44CirQd4zyU9Ez4ZmP4jNjZ"), ) { const [data] = BookRentalStruct.serialize({ instructionDiscriminator: bookRentalInstructionDiscriminator, diff --git a/tools/shank-and-solita/native/tests/generated/instructions/PickUpCar.ts b/tools/shank-and-solita/native/tests/generated/instructions/PickUpCar.ts index f0fced5fa..329a6fce7 100644 --- a/tools/shank-and-solita/native/tests/generated/instructions/PickUpCar.ts +++ b/tools/shank-and-solita/native/tests/generated/instructions/PickUpCar.ts @@ -5,8 +5,8 @@ * See: https://github.com/metaplex-foundation/solita */ -import * as beet from '@metaplex-foundation/beet'; -import * as web3 from '@solana/web3.js'; +import * as beet from "@metaplex-foundation/beet"; +import * as web3 from "@solana/web3.js"; /** * @category Instructions @@ -15,7 +15,7 @@ import * as web3 from '@solana/web3.js'; */ export const PickUpCarStruct = new beet.BeetArgsStruct<{ instructionDiscriminator: number; -}>([['instructionDiscriminator', beet.u8]], 'PickUpCarInstructionArgs'); +}>([["instructionDiscriminator", beet.u8]], "PickUpCarInstructionArgs"); /** * Accounts required by the _PickUpCar_ instruction * @@ -44,7 +44,7 @@ export const pickUpCarInstructionDiscriminator = 2; */ export function createPickUpCarInstruction( accounts: PickUpCarInstructionAccounts, - programId = new web3.PublicKey('8avNGHVXDwsELJaWMSoUZ44CirQd4zyU9Ez4ZmP4jNjZ'), + programId = new web3.PublicKey("8avNGHVXDwsELJaWMSoUZ44CirQd4zyU9Ez4ZmP4jNjZ"), ) { const [data] = PickUpCarStruct.serialize({ instructionDiscriminator: pickUpCarInstructionDiscriminator, diff --git a/tools/shank-and-solita/native/tests/generated/instructions/ReturnCar.ts b/tools/shank-and-solita/native/tests/generated/instructions/ReturnCar.ts index db3d7f303..1a7dc0e00 100644 --- a/tools/shank-and-solita/native/tests/generated/instructions/ReturnCar.ts +++ b/tools/shank-and-solita/native/tests/generated/instructions/ReturnCar.ts @@ -5,8 +5,8 @@ * See: https://github.com/metaplex-foundation/solita */ -import * as beet from '@metaplex-foundation/beet'; -import * as web3 from '@solana/web3.js'; +import * as beet from "@metaplex-foundation/beet"; +import * as web3 from "@solana/web3.js"; /** * @category Instructions @@ -15,7 +15,7 @@ import * as web3 from '@solana/web3.js'; */ export const ReturnCarStruct = new beet.BeetArgsStruct<{ instructionDiscriminator: number; -}>([['instructionDiscriminator', beet.u8]], 'ReturnCarInstructionArgs'); +}>([["instructionDiscriminator", beet.u8]], "ReturnCarInstructionArgs"); /** * Accounts required by the _ReturnCar_ instruction * @@ -44,7 +44,7 @@ export const returnCarInstructionDiscriminator = 3; */ export function createReturnCarInstruction( accounts: ReturnCarInstructionAccounts, - programId = new web3.PublicKey('8avNGHVXDwsELJaWMSoUZ44CirQd4zyU9Ez4ZmP4jNjZ'), + programId = new web3.PublicKey("8avNGHVXDwsELJaWMSoUZ44CirQd4zyU9Ez4ZmP4jNjZ"), ) { const [data] = ReturnCarStruct.serialize({ instructionDiscriminator: returnCarInstructionDiscriminator, diff --git a/tools/shank-and-solita/native/tests/generated/instructions/index.ts b/tools/shank-and-solita/native/tests/generated/instructions/index.ts index 86e06563b..f15225432 100644 --- a/tools/shank-and-solita/native/tests/generated/instructions/index.ts +++ b/tools/shank-and-solita/native/tests/generated/instructions/index.ts @@ -1,4 +1,4 @@ -export * from './AddCar'; -export * from './BookRental'; -export * from './PickUpCar'; -export * from './ReturnCar'; +export * from "./AddCar"; +export * from "./BookRental"; +export * from "./PickUpCar"; +export * from "./ReturnCar"; diff --git a/tools/shank-and-solita/native/tests/generated/types/AddCarArgs.ts b/tools/shank-and-solita/native/tests/generated/types/AddCarArgs.ts index ba0f0fae2..72be60649 100644 --- a/tools/shank-and-solita/native/tests/generated/types/AddCarArgs.ts +++ b/tools/shank-and-solita/native/tests/generated/types/AddCarArgs.ts @@ -5,7 +5,7 @@ * See: https://github.com/metaplex-foundation/solita */ -import * as beet from '@metaplex-foundation/beet'; +import * as beet from "@metaplex-foundation/beet"; export type AddCarArgs = { year: number; make: string; @@ -18,9 +18,9 @@ export type AddCarArgs = { */ export const addCarArgsBeet = new beet.FixableBeetArgsStruct( [ - ['year', beet.u16], - ['make', beet.utf8String], - ['model', beet.utf8String], + ["year", beet.u16], + ["make", beet.utf8String], + ["model", beet.utf8String], ], - 'AddCarArgs', + "AddCarArgs", ); diff --git a/tools/shank-and-solita/native/tests/generated/types/BookRentalArgs.ts b/tools/shank-and-solita/native/tests/generated/types/BookRentalArgs.ts index b1088ead6..f236b7efa 100644 --- a/tools/shank-and-solita/native/tests/generated/types/BookRentalArgs.ts +++ b/tools/shank-and-solita/native/tests/generated/types/BookRentalArgs.ts @@ -5,7 +5,7 @@ * See: https://github.com/metaplex-foundation/solita */ -import * as beet from '@metaplex-foundation/beet'; +import * as beet from "@metaplex-foundation/beet"; export type BookRentalArgs = { name: string; pickUpDate: string; @@ -19,10 +19,10 @@ export type BookRentalArgs = { */ export const bookRentalArgsBeet = new beet.FixableBeetArgsStruct( [ - ['name', beet.utf8String], - ['pickUpDate', beet.utf8String], - ['returnDate', beet.utf8String], - ['price', beet.u64], + ["name", beet.utf8String], + ["pickUpDate", beet.utf8String], + ["returnDate", beet.utf8String], + ["price", beet.u64], ], - 'BookRentalArgs', + "BookRentalArgs", ); diff --git a/tools/shank-and-solita/native/tests/generated/types/RentalOrderStatus.ts b/tools/shank-and-solita/native/tests/generated/types/RentalOrderStatus.ts index 52a96ab23..66d5f5a15 100644 --- a/tools/shank-and-solita/native/tests/generated/types/RentalOrderStatus.ts +++ b/tools/shank-and-solita/native/tests/generated/types/RentalOrderStatus.ts @@ -5,7 +5,7 @@ * See: https://github.com/metaplex-foundation/solita */ -import * as beet from '@metaplex-foundation/beet'; +import * as beet from "@metaplex-foundation/beet"; /** * @category enums * @category generated @@ -20,4 +20,7 @@ export enum RentalOrderStatus { * @category userTypes * @category generated */ -export const rentalOrderStatusBeet = beet.fixedScalarEnum(RentalOrderStatus) as beet.FixedSizeBeet; +export const rentalOrderStatusBeet = beet.fixedScalarEnum(RentalOrderStatus) as beet.FixedSizeBeet< + RentalOrderStatus, + RentalOrderStatus +>; diff --git a/tools/shank-and-solita/native/tests/generated/types/index.ts b/tools/shank-and-solita/native/tests/generated/types/index.ts index 2e86601ee..dc2300b8e 100644 --- a/tools/shank-and-solita/native/tests/generated/types/index.ts +++ b/tools/shank-and-solita/native/tests/generated/types/index.ts @@ -1,3 +1,3 @@ -export * from './AddCarArgs'; -export * from './BookRentalArgs'; -export * from './RentalOrderStatus'; +export * from "./AddCarArgs"; +export * from "./BookRentalArgs"; +export * from "./RentalOrderStatus"; diff --git a/tools/shank-and-solita/native/tests/test.ts b/tools/shank-and-solita/native/tests/test.ts index 3fa66a96f..b1ab61acf 100644 --- a/tools/shank-and-solita/native/tests/test.ts +++ b/tools/shank-and-solita/native/tests/test.ts @@ -1,5 +1,5 @@ -import { Connection, Keypair, PublicKey, SystemProgram, sendAndConfirmTransaction, Transaction } from '@solana/web3.js'; -import { describe, it } from 'mocha'; +import { Connection, Keypair, PublicKey, SystemProgram, sendAndConfirmTransaction, Transaction } from "@solana/web3.js"; +import { describe, it } from "mocha"; import { type AddCarArgs, Car, @@ -9,42 +9,42 @@ import { createReturnCarInstruction, RentalOrder, RentalOrderStatus, -} from './generated'; +} from "./generated"; function loadKeypairFromFile(path: string): Keypair { - return Keypair.fromSecretKey(Buffer.from(JSON.parse(require('node:fs').readFileSync(path, 'utf-8')))); + return Keypair.fromSecretKey(Buffer.from(JSON.parse(require("node:fs").readFileSync(path, "utf-8")))); } const carBmw: AddCarArgs = { year: 2020, - make: 'BMW', - model: 'iX1', + make: "BMW", + model: "iX1", }; const carMercedes: AddCarArgs = { year: 2019, - make: 'Mercedes-Benz', - model: 'EQS', + make: "Mercedes-Benz", + model: "EQS", }; const rentalInfo = { - name: 'Fred Flinstone', - pickUpDate: '01/28/2023 8:00 AM', - returnDate: '01/28/2023 10:00 PM', + name: "Fred Flinstone", + pickUpDate: "01/28/2023 8:00 AM", + returnDate: "01/28/2023 10:00 PM", price: 300, }; -describe('Car Rental Service', () => { - const connection = new Connection('https://api.devnet.solana.com', 'confirmed'); - const payer = loadKeypairFromFile(`${require('node:os').homedir()}/.config/solana/id.json`); - const program = loadKeypairFromFile('./program/target/deploy/car_rental_service-keypair.json'); +describe("Car Rental Service", () => { + const connection = new Connection("https://api.devnet.solana.com", "confirmed"); + const payer = loadKeypairFromFile(`${require("node:os").homedir()}/.config/solana/id.json`); + const program = loadKeypairFromFile("./program/target/deploy/car_rental_service-keypair.json"); let bmwPublicKey: PublicKey; let _mercedesPublicKey: PublicKey; async function createCar(car: AddCarArgs): Promise { const carAccountPublicKey = PublicKey.findProgramAddressSync( - [Buffer.from('car'), Buffer.from(car.make), Buffer.from(car.model)], + [Buffer.from("car"), Buffer.from(car.make), Buffer.from(car.model)], program.publicKey, )[0]; const ix = createAddCarInstruction( @@ -58,31 +58,31 @@ describe('Car Rental Service', () => { const sx = await sendAndConfirmTransaction(connection, new Transaction().add(ix), [payer], { skipPreflight: true }); await connection.confirmTransaction(sx); const carData = await Car.fromAccountAddress(connection, carAccountPublicKey); - console.log('New car created:'); + console.log("New car created:"); console.log(` Year : ${carData.year}`); console.log(` Make : ${carData.make}`); console.log(` Model : ${carData.model}`); return carAccountPublicKey; } - it('Create a car that can be rented', async () => { + it("Create a car that can be rented", async () => { bmwPublicKey = await createCar(carBmw); }); - it('Create another car that can be rented', async () => { + it("Create another car that can be rented", async () => { _mercedesPublicKey = await createCar(carMercedes); }); const evaluateStatus = (status: RentalOrderStatus): string => { - if (status === RentalOrderStatus.Created) return 'Created'; - if (status === RentalOrderStatus.PickedUp) return 'Picked Up'; - return 'Returned'; + if (status === RentalOrderStatus.Created) return "Created"; + if (status === RentalOrderStatus.PickedUp) return "Picked Up"; + return "Returned"; }; async function printRentalDetails(rentalPublicKey: PublicKey, carPublicKey: PublicKey) { const rentalData = await RentalOrder.fromAccountAddress(connection, rentalPublicKey); const carData = await Car.fromAccountAddress(connection, carPublicKey); - console.log('Rental booked:'); - console.log(' Vehicle details:'); + console.log("Rental booked:"); + console.log(" Vehicle details:"); console.log(` Year : ${carData.year}`); console.log(` Make : ${carData.make}`); console.log(` Model : ${carData.model}`); @@ -93,9 +93,9 @@ describe('Car Rental Service', () => { console.log(` Status : ${evaluateStatus(rentalData.status)}`); } - it('Book a new rental', async () => { + it("Book a new rental", async () => { const rentalAccountPublicKey = PublicKey.findProgramAddressSync( - [Buffer.from('rental_order'), bmwPublicKey.toBuffer(), payer.publicKey.toBuffer()], + [Buffer.from("rental_order"), bmwPublicKey.toBuffer(), payer.publicKey.toBuffer()], program.publicKey, )[0]; const ix = createBookRentalInstruction( @@ -114,9 +114,9 @@ describe('Car Rental Service', () => { await printRentalDetails(rentalAccountPublicKey, bmwPublicKey); }); - it('Pick up your rental car', async () => { + it("Pick up your rental car", async () => { const rentalAccountPublicKey = PublicKey.findProgramAddressSync( - [Buffer.from('rental_order'), bmwPublicKey.toBuffer(), payer.publicKey.toBuffer()], + [Buffer.from("rental_order"), bmwPublicKey.toBuffer(), payer.publicKey.toBuffer()], program.publicKey, )[0]; const ix = createPickUpCarInstruction({ @@ -129,9 +129,9 @@ describe('Car Rental Service', () => { await printRentalDetails(rentalAccountPublicKey, bmwPublicKey); }); - it('Return your rental car', async () => { + it("Return your rental car", async () => { const rentalAccountPublicKey = PublicKey.findProgramAddressSync( - [Buffer.from('rental_order'), bmwPublicKey.toBuffer(), payer.publicKey.toBuffer()], + [Buffer.from("rental_order"), bmwPublicKey.toBuffer(), payer.publicKey.toBuffer()], program.publicKey, )[0]; const ix = createReturnCarInstruction({ From eb3eaa0cb10aeb51338ebe324bc2ddbab9a84748 Mon Sep 17 00:00:00 2001 From: Mike MacCana Date: Wed, 1 Apr 2026 15:32:20 -0400 Subject: [PATCH 4/6] Fix: add pnpm/action-setup before setup-node in Native and Pinocchio workflows packageManager field in package.json causes setup-node to look for pnpm before it is installed, failing with "Unable to locate executable file: pnpm". Co-Authored-By: Claude Sonnet 4.6 --- .github/workflows/solana-native.yml | 4 ++-- .github/workflows/solana-pinocchio.yml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/solana-native.yml b/.github/workflows/solana-native.yml index f1f030f8e..8433af85f 100644 --- a/.github/workflows/solana-native.yml +++ b/.github/workflows/solana-native.yml @@ -108,6 +108,7 @@ jobs: failed_projects: ${{ steps.set-failed.outputs.failed_projects }} steps: - uses: actions/checkout@v5 + - uses: pnpm/action-setup@v4 - name: Use Node.js uses: actions/setup-node@v5 with: @@ -193,8 +194,7 @@ jobs: # Make the script executable chmod +x build_and_test.sh - # Install pnpm - npm install --global pnpm + # pnpm is already installed via pnpm/action-setup - name: Setup Solana Stable uses: heyAyushh/setup-solana@v5.9 with: diff --git a/.github/workflows/solana-pinocchio.yml b/.github/workflows/solana-pinocchio.yml index d534656c2..2ec668298 100644 --- a/.github/workflows/solana-pinocchio.yml +++ b/.github/workflows/solana-pinocchio.yml @@ -108,6 +108,7 @@ jobs: failed_projects: ${{ steps.set-failed.outputs.failed_projects }} steps: - uses: actions/checkout@v5 + - uses: pnpm/action-setup@v4 - name: Use Node.js uses: actions/setup-node@v5 with: @@ -193,8 +194,7 @@ jobs: # Make the script executable chmod +x build_and_test.sh - # Install pnpm - npm install --global pnpm + # pnpm is already installed via pnpm/action-setup - name: Setup Solana Stable uses: heyAyushh/setup-solana@v5.9 with: From cf4c1085bf4aa9b9447aefe174a0c2aec3efafba Mon Sep 17 00:00:00 2001 From: Mike MacCana Date: Wed, 1 Apr 2026 15:43:06 -0400 Subject: [PATCH 5/6] Fix: upgrade litesvm from 0.8.1 to 0.11.0 to fix compilation against current Solana stable litesvm 0.8.1 failed to compile against current Solana stable because internal Solana APIs changed (ProgramCacheForTxBatch.environments field removed, TransactionError lifetime added). litesvm 0.11.0 has been updated for these API changes. Co-Authored-By: Claude Sonnet 4.6 --- Cargo.lock | 275 +++--------------- Cargo.toml | 2 +- basics/account-data/native/program/Cargo.toml | 2 +- .../account-data/pinocchio/program/Cargo.toml | 2 +- .../native/program/Cargo.toml | 2 +- .../pinocchio/program/Cargo.toml | 2 +- .../close-account/native/program/Cargo.toml | 2 +- .../pinocchio/program/Cargo.toml | 2 +- basics/counter/native/program/Cargo.toml | 2 +- basics/counter/pinocchio/program/Cargo.toml | 2 +- .../create-account/native/program/Cargo.toml | 2 +- .../pinocchio/program/Cargo.toml | 2 +- .../native/programs/hand/Cargo.toml | 2 +- basics/favorites/native/program/Cargo.toml | 2 +- basics/favorites/pinocchio/program/Cargo.toml | 2 +- basics/hello-solana/native/program/Cargo.toml | 2 +- .../native/program/Cargo.toml | 2 +- .../pinocchio/program/Cargo.toml | 2 +- .../native/program/Cargo.toml | 2 +- .../pinocchio/program/Cargo.toml | 2 +- basics/realloc/native/program/Cargo.toml | 2 +- basics/realloc/pinocchio/program/Cargo.toml | 2 +- basics/rent/native/program/Cargo.toml | 2 +- basics/rent/pinocchio/program/Cargo.toml | 2 +- .../native/program/Cargo.toml | 2 +- basics/transfer-sol/native/program/Cargo.toml | 2 +- .../transfer-sol/pinocchio/program/Cargo.toml | 2 +- 27 files changed, 70 insertions(+), 257 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 27895f8ef..26cac9b1c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -93,28 +93,6 @@ dependencies = [ "solana-svm-feature-set", ] -[[package]] -name = "agave-precompiles" -version = "3.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58acc95455da4ba868f723d2170af9bb3009a3f430580aae359eecc9b057fb3f" -dependencies = [ - "agave-feature-set", - "bincode", - "digest 0.10.7", - "ed25519-dalek 1.0.1", - "libsecp256k1", - "openssl", - "sha3", - "solana-ed25519-program", - "solana-message 3.1.0", - "solana-precompile-error", - "solana-pubkey 3.0.0", - "solana-sdk-ids 3.1.0", - "solana-secp256k1-program", - "solana-secp256r1-program", -] - [[package]] name = "agave-reserved-account-keys" version = "3.1.11" @@ -1259,16 +1237,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "crypto-mac" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b584a330336237c1eecd3e94266efb216c56ed91225d634cb2991c5f3fd1aeab" -dependencies = [ - "generic-array", - "subtle", -] - [[package]] name = "ctr" version = "0.9.2" @@ -1278,19 +1246,6 @@ dependencies = [ "cipher", ] -[[package]] -name = "curve25519-dalek" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b9fdf9972b2bd6af2d913799d9ebc165ea4d2e65878e329d9c6b372c4491b61" -dependencies = [ - "byteorder", - "digest 0.9.0", - "rand_core 0.5.1", - "subtle", - "zeroize", -] - [[package]] name = "curve25519-dalek" version = "4.1.3" @@ -1453,19 +1408,10 @@ dependencies = [ "digest 0.10.7", "elliptic-curve", "rfc6979", - "signature 2.2.0", + "signature", "spki", ] -[[package]] -name = "ed25519" -version = "1.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91cff35c70bba8a626e3185d8cd48cc11b5437e1a5bcd15b9b5fa3c64b6dfee7" -dependencies = [ - "signature 1.6.4", -] - [[package]] name = "ed25519" version = "2.2.3" @@ -1473,21 +1419,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" dependencies = [ "pkcs8", - "signature 2.2.0", -] - -[[package]] -name = "ed25519-dalek" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c762bae6dcaf24c4c84667b8579785430908723d5c889f469d76a41d59cc7a9d" -dependencies = [ - "curve25519-dalek 3.2.0", - "ed25519 1.5.3", - "rand 0.7.3", - "serde", - "sha2 0.9.9", - "zeroize", + "signature", ] [[package]] @@ -1496,8 +1428,8 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" dependencies = [ - "curve25519-dalek 4.1.3", - "ed25519 2.2.3", + "curve25519-dalek", + "ed25519", "rand_core 0.6.4", "serde", "sha2 0.10.9", @@ -1512,8 +1444,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b49a684b133c4980d7ee783936af771516011c8cd15f429dbda77245e282f03" dependencies = [ "derivation-path", - "ed25519-dalek 2.2.0", - "hmac 0.12.1", + "ed25519-dalek", + "hmac", "sha2 0.10.9", ] @@ -1715,21 +1647,6 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" -[[package]] -name = "foreign-types" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" -dependencies = [ - "foreign-types-shared", -] - -[[package]] -name = "foreign-types-shared" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" - [[package]] name = "generic-array" version = "0.14.7" @@ -1874,16 +1791,6 @@ dependencies = [ "pinocchio-log", ] -[[package]] -name = "hmac" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "126888268dcc288495a26bf004b38c5fdbb31682f992c84ceb046a1f0fe38840" -dependencies = [ - "crypto-mac", - "digest 0.9.0", -] - [[package]] name = "hmac" version = "0.12.1" @@ -1893,17 +1800,6 @@ dependencies = [ "digest 0.10.7", ] -[[package]] -name = "hmac-drbg" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17ea0a1394df5b6574da6e0c1ade9e78868c9fb0a4e5ef4428e32da4676b85b1" -dependencies = [ - "digest 0.9.0", - "generic-array", - "hmac 0.8.1", -] - [[package]] name = "ident_case" version = "1.0.1" @@ -1992,7 +1888,7 @@ dependencies = [ "elliptic-curve", "once_cell", "sha2 0.10.9", - "signature 2.2.0", + "signature", ] [[package]] @@ -2038,14 +1934,12 @@ dependencies = [ "arrayref", "base64 0.12.3", "digest 0.9.0", - "hmac-drbg", "libsecp256k1-core", "libsecp256k1-gen-ecmult", "libsecp256k1-gen-genmult", "rand 0.7.3", "serde", "sha2 0.9.9", - "typenum", ] [[package]] @@ -2103,12 +1997,11 @@ dependencies = [ [[package]] name = "litesvm" -version = "0.8.1" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a22c52e9daf4680aee15e84c877808d94bbd4f3f66cdd32e0ba059d930d581e4" +checksum = "347d8c652d592c618ac996f2ab21f8c0b0f2da3fbbca227a6887ee61bb75f2de" dependencies = [ "agave-feature-set", - "agave-precompiles", "agave-reserved-account-keys", "agave-syscalls", "ansi_term", @@ -2118,6 +2011,7 @@ dependencies = [ "log", "serde", "solana-account 3.4.0", + "solana-address 2.4.0", "solana-address-lookup-table-interface 3.0.1", "solana-bpf-loader-program", "solana-builtins", @@ -2126,6 +2020,7 @@ dependencies = [ "solana-compute-budget-instruction", "solana-epoch-rewards 3.0.1", "solana-epoch-schedule 3.0.0", + "solana-feature-gate-interface 3.1.0", "solana-fee", "solana-fee-structure", "solana-hash 3.1.0", @@ -2142,7 +2037,6 @@ dependencies = [ "solana-precompile-error", "solana-program-error 3.0.1", "solana-program-runtime", - "solana-pubkey 3.0.0", "solana-rent 3.1.0", "solana-sdk-ids 3.1.0", "solana-sha256-hasher 3.1.0", @@ -2338,54 +2232,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" -[[package]] -name = "openssl" -version = "0.10.76" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "951c002c75e16ea2c65b8c7e4d3d51d5530d8dfa7d060b4776828c88cfb18ecf" -dependencies = [ - "bitflags", - "cfg-if", - "foreign-types", - "libc", - "once_cell", - "openssl-macros", - "openssl-sys", -] - -[[package]] -name = "openssl-macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "openssl-src" -version = "300.5.5+3.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f1787d533e03597a7934fd0a765f0d28e94ecc5fb7789f8053b1e699a56f709" -dependencies = [ - "cc", -] - -[[package]] -name = "openssl-sys" -version = "0.9.112" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57d55af3b3e226502be1526dfdba67ab0e9c96fc293004e79576b2b9edb0dbdb" -dependencies = [ - "cc", - "libc", - "openssl-src", - "pkg-config", - "vcpkg", -] - [[package]] name = "parking_lot" version = "0.12.5" @@ -2555,12 +2401,6 @@ dependencies = [ "spki", ] -[[package]] -name = "pkg-config" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" - [[package]] name = "polyval" version = "0.6.2" @@ -2952,7 +2792,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" dependencies = [ - "hmac 0.12.1", + "hmac", "subtle", ] @@ -3188,12 +3028,6 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" -[[package]] -name = "signature" -version = "1.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c" - [[package]] name = "signature" version = "2.2.0" @@ -3301,7 +3135,7 @@ dependencies = [ "borsh 1.6.1", "bytemuck", "bytemuck_derive", - "curve25519-dalek 4.1.3", + "curve25519-dalek", "five8 1.0.0", "five8_const 1.0.0", "rand 0.9.2", @@ -3651,7 +3485,7 @@ checksum = "9a9eaec815ed773919bc7269c027933fc2472d7b9876f68ea6f1281c7daa5278" dependencies = [ "bytemuck", "bytemuck_derive", - "curve25519-dalek 4.1.3", + "curve25519-dalek", "solana-define-syscall 3.0.0", "subtle", "thiserror 2.0.18", @@ -3701,18 +3535,6 @@ dependencies = [ "uriparse", ] -[[package]] -name = "solana-ed25519-program" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1419197f1c06abf760043f6d64ba9d79a03ad5a43f18c7586471937122094da" -dependencies = [ - "bytemuck", - "bytemuck_derive", - "solana-instruction 3.3.0", - "solana-sdk-ids 3.1.0", -] - [[package]] name = "solana-epoch-info" version = "3.1.0" @@ -3865,9 +3687,17 @@ version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75ca9b5cbb6f500f7fd73db5bd95640f71a83f04d6121a0e59a43b202dca2731" dependencies = [ + "bincode", + "serde", + "serde_derive", + "solana-account 3.4.0", + "solana-account-info 3.1.1", + "solana-instruction 3.3.0", "solana-program-error 3.0.1", "solana-pubkey 4.1.0", + "solana-rent 4.1.0", "solana-sdk-ids 3.1.0", + "solana-system-interface 3.1.0", ] [[package]] @@ -4108,7 +3938,7 @@ version = "3.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "263d614c12aa267a3278703175fd6440552ca61bc960b5a02a4482720c53438b" dependencies = [ - "ed25519-dalek 2.2.0", + "ed25519-dalek", "ed25519-dalek-bip32", "five8 1.0.0", "five8_core 1.0.0", @@ -4707,7 +4537,7 @@ dependencies = [ "borsh 1.6.1", "bytemuck", "bytemuck_derive", - "curve25519-dalek 4.1.3", + "curve25519-dalek", "five8 0.2.1", "five8_const 0.1.4", "getrandom 0.2.17", @@ -4886,20 +4716,6 @@ dependencies = [ "syn 2.0.117", ] -[[package]] -name = "solana-secp256k1-program" -version = "3.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad4cf8232f7aef9ff2dd95d701f63e3c11909dec2400def5c361be29d24291e7" -dependencies = [ - "digest 0.10.7", - "k256", - "serde", - "serde_derive", - "sha3", - "solana-signature", -] - [[package]] name = "solana-secp256k1-recover" version = "2.2.1" @@ -4922,18 +4738,6 @@ dependencies = [ "thiserror 2.0.18", ] -[[package]] -name = "solana-secp256r1-program" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "445d8e12592631d76fc4dc57858bae66c9fd7cc838c306c62a472547fc9d0ce6" -dependencies = [ - "bytemuck", - "openssl", - "solana-instruction 3.3.0", - "solana-sdk-ids 3.1.0", -] - [[package]] name = "solana-seed-derivable" version = "3.0.0" @@ -4949,7 +4753,7 @@ version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc905b200a95f2ea9146e43f2a7181e3aeb55de6bc12afb36462d00a3c7310de" dependencies = [ - "hmac 0.12.1", + "hmac", "pbkdf2", "sha2 0.10.9", ] @@ -5060,7 +4864,7 @@ version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "132a93134f1262aa832f1849b83bec6c9945669b866da18661a427943b9e801e" dependencies = [ - "ed25519-dalek 2.2.0", + "ed25519-dalek", "five8 1.0.0", "rand 0.9.2", "serde", @@ -5291,6 +5095,21 @@ dependencies = [ "solana-pubkey 3.0.0", ] +[[package]] +name = "solana-system-interface" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a95a6f2e23ed861d6444ad4a6d6896c418d7d101b960787e65a8e33157cee81b" +dependencies = [ + "num-traits", + "serde", + "serde_derive", + "solana-address 2.4.0", + "solana-instruction 3.3.0", + "solana-msg 3.1.0", + "solana-program-error 3.0.1", +] + [[package]] name = "solana-system-program" version = "3.1.11" @@ -5595,7 +5414,7 @@ dependencies = [ "bincode", "bytemuck", "bytemuck_derive", - "curve25519-dalek 4.1.3", + "curve25519-dalek", "getrandom 0.2.17", "itertools 0.12.1", "js-sys", @@ -5649,7 +5468,7 @@ dependencies = [ "bincode", "bytemuck", "bytemuck_derive", - "curve25519-dalek 4.1.3", + "curve25519-dalek", "itertools 0.12.1", "merlin", "num-derive", @@ -5801,7 +5620,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a0cd59fce3dc00f563c6fa364d67c3f200d278eae681f4dc250240afcfe044b1" dependencies = [ - "curve25519-dalek 4.1.3", + "curve25519-dalek", "solana-zk-sdk", "thiserror 2.0.18", ] @@ -6192,12 +6011,6 @@ dependencies = [ "lazy_static", ] -[[package]] -name = "vcpkg" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" - [[package]] name = "version_check" version = "0.9.5" diff --git a/Cargo.toml b/Cargo.toml index 66c8b33cb..a0a7bcb2f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -83,7 +83,7 @@ pinocchio-system = "0.5.0" pinocchio-pubkey = "0.3.0" # testing -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-pubkey = "3.0.0" diff --git a/basics/account-data/native/program/Cargo.toml b/basics/account-data/native/program/Cargo.toml index 968f41b7f..acdb1be45 100644 --- a/basics/account-data/native/program/Cargo.toml +++ b/basics/account-data/native/program/Cargo.toml @@ -20,7 +20,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-keypair = "3.0.1" solana-message = "3.0.1" solana-native-token = "3.0.0" diff --git a/basics/account-data/pinocchio/program/Cargo.toml b/basics/account-data/pinocchio/program/Cargo.toml index c79283770..4239753c5 100644 --- a/basics/account-data/pinocchio/program/Cargo.toml +++ b/basics/account-data/pinocchio/program/Cargo.toml @@ -9,7 +9,7 @@ pinocchio-log.workspace = true pinocchio-system.workspace = true [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-keypair = "3.0.1" solana-message = "3.0.1" solana-native-token = "3.0.0" diff --git a/basics/checking-accounts/native/program/Cargo.toml b/basics/checking-accounts/native/program/Cargo.toml index 214ea7856..4ee029de8 100644 --- a/basics/checking-accounts/native/program/Cargo.toml +++ b/basics/checking-accounts/native/program/Cargo.toml @@ -19,7 +19,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-keypair = "3.0.1" solana-native-token = "3.0.0" solana-pubkey = "3.0.0" diff --git a/basics/checking-accounts/pinocchio/program/Cargo.toml b/basics/checking-accounts/pinocchio/program/Cargo.toml index 5eebeb583..f03a6369b 100644 --- a/basics/checking-accounts/pinocchio/program/Cargo.toml +++ b/basics/checking-accounts/pinocchio/program/Cargo.toml @@ -9,7 +9,7 @@ pinocchio-system.workspace = true pinocchio-log.workspace = true [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-keypair = "3.0.1" solana-native-token = "3.0.0" solana-pubkey = "3.0.0" diff --git a/basics/close-account/native/program/Cargo.toml b/basics/close-account/native/program/Cargo.toml index 5bedf0754..ca3d566e6 100644 --- a/basics/close-account/native/program/Cargo.toml +++ b/basics/close-account/native/program/Cargo.toml @@ -20,7 +20,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-native-token = "3.0.0" diff --git a/basics/close-account/pinocchio/program/Cargo.toml b/basics/close-account/pinocchio/program/Cargo.toml index e1c7f3307..3c6d7e48f 100644 --- a/basics/close-account/pinocchio/program/Cargo.toml +++ b/basics/close-account/pinocchio/program/Cargo.toml @@ -10,7 +10,7 @@ pinocchio-pubkey.workspace = true pinocchio-system.workspace = true [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-keypair = "3.0.1" solana-message = "3.0.1" solana-native-token = "3.0.0" diff --git a/basics/counter/native/program/Cargo.toml b/basics/counter/native/program/Cargo.toml index 0180bb481..c928d7806 100644 --- a/basics/counter/native/program/Cargo.toml +++ b/basics/counter/native/program/Cargo.toml @@ -22,7 +22,7 @@ solana-program.workspace = true unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-native-token = "3.0.0" diff --git a/basics/counter/pinocchio/program/Cargo.toml b/basics/counter/pinocchio/program/Cargo.toml index 54ffc5008..2df97c688 100644 --- a/basics/counter/pinocchio/program/Cargo.toml +++ b/basics/counter/pinocchio/program/Cargo.toml @@ -22,7 +22,7 @@ pinocchio-pubkey.workspace = true unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-native-token = "3.0.0" diff --git a/basics/create-account/native/program/Cargo.toml b/basics/create-account/native/program/Cargo.toml index 3bd473717..bde26597a 100644 --- a/basics/create-account/native/program/Cargo.toml +++ b/basics/create-account/native/program/Cargo.toml @@ -18,7 +18,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-native-token = "3.0.0" diff --git a/basics/create-account/pinocchio/program/Cargo.toml b/basics/create-account/pinocchio/program/Cargo.toml index d6d61991a..609d465c2 100644 --- a/basics/create-account/pinocchio/program/Cargo.toml +++ b/basics/create-account/pinocchio/program/Cargo.toml @@ -20,7 +20,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-native-token = "3.0.0" diff --git a/basics/cross-program-invocation/native/programs/hand/Cargo.toml b/basics/cross-program-invocation/native/programs/hand/Cargo.toml index 26bc992a4..c74aab0f4 100644 --- a/basics/cross-program-invocation/native/programs/hand/Cargo.toml +++ b/basics/cross-program-invocation/native/programs/hand/Cargo.toml @@ -19,7 +19,7 @@ cross-program-invocatio-native-lever = { path = "../lever", features = ["cpi"] } crate-type = ["cdylib", "lib"] [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-native-token = "3.0.0" diff --git a/basics/favorites/native/program/Cargo.toml b/basics/favorites/native/program/Cargo.toml index fab1cd066..416af7197 100644 --- a/basics/favorites/native/program/Cargo.toml +++ b/basics/favorites/native/program/Cargo.toml @@ -20,7 +20,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-native-token = "3.0.0" diff --git a/basics/favorites/pinocchio/program/Cargo.toml b/basics/favorites/pinocchio/program/Cargo.toml index 576a8c916..2842e5f8c 100644 --- a/basics/favorites/pinocchio/program/Cargo.toml +++ b/basics/favorites/pinocchio/program/Cargo.toml @@ -21,7 +21,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-native-token = "3.0.0" diff --git a/basics/hello-solana/native/program/Cargo.toml b/basics/hello-solana/native/program/Cargo.toml index 6467e0684..a51e82ffa 100644 --- a/basics/hello-solana/native/program/Cargo.toml +++ b/basics/hello-solana/native/program/Cargo.toml @@ -17,7 +17,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-native-token = "3.0.0" diff --git a/basics/processing-instructions/native/program/Cargo.toml b/basics/processing-instructions/native/program/Cargo.toml index 2855d519d..d3af395c4 100644 --- a/basics/processing-instructions/native/program/Cargo.toml +++ b/basics/processing-instructions/native/program/Cargo.toml @@ -19,7 +19,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-pubkey = "3.0.0" diff --git a/basics/processing-instructions/pinocchio/program/Cargo.toml b/basics/processing-instructions/pinocchio/program/Cargo.toml index 96beaced7..5e202b590 100644 --- a/basics/processing-instructions/pinocchio/program/Cargo.toml +++ b/basics/processing-instructions/pinocchio/program/Cargo.toml @@ -18,7 +18,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-pubkey = "3.0.0" diff --git a/basics/program-derived-addresses/native/program/Cargo.toml b/basics/program-derived-addresses/native/program/Cargo.toml index 097ef4d8a..1251e8d8a 100644 --- a/basics/program-derived-addresses/native/program/Cargo.toml +++ b/basics/program-derived-addresses/native/program/Cargo.toml @@ -20,7 +20,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-pubkey = "3.0.0" diff --git a/basics/program-derived-addresses/pinocchio/program/Cargo.toml b/basics/program-derived-addresses/pinocchio/program/Cargo.toml index 4b255c5eb..e803884e6 100644 --- a/basics/program-derived-addresses/pinocchio/program/Cargo.toml +++ b/basics/program-derived-addresses/pinocchio/program/Cargo.toml @@ -19,7 +19,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-pubkey = "3.0.0" diff --git a/basics/realloc/native/program/Cargo.toml b/basics/realloc/native/program/Cargo.toml index 3c8672f61..8a763a8e1 100644 --- a/basics/realloc/native/program/Cargo.toml +++ b/basics/realloc/native/program/Cargo.toml @@ -20,7 +20,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-native-token = "3.0.0" diff --git a/basics/realloc/pinocchio/program/Cargo.toml b/basics/realloc/pinocchio/program/Cargo.toml index 0a475abf2..35d0043d1 100644 --- a/basics/realloc/pinocchio/program/Cargo.toml +++ b/basics/realloc/pinocchio/program/Cargo.toml @@ -20,7 +20,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-native-token = "3.0.0" diff --git a/basics/rent/native/program/Cargo.toml b/basics/rent/native/program/Cargo.toml index 018875285..dcbff7dc9 100644 --- a/basics/rent/native/program/Cargo.toml +++ b/basics/rent/native/program/Cargo.toml @@ -20,7 +20,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-native-token = "3.0.0" diff --git a/basics/rent/pinocchio/program/Cargo.toml b/basics/rent/pinocchio/program/Cargo.toml index f58109e0b..486190ede 100644 --- a/basics/rent/pinocchio/program/Cargo.toml +++ b/basics/rent/pinocchio/program/Cargo.toml @@ -19,7 +19,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-native-token = "3.0.0" diff --git a/basics/repository-layout/native/program/Cargo.toml b/basics/repository-layout/native/program/Cargo.toml index 049e72758..61290f9ff 100644 --- a/basics/repository-layout/native/program/Cargo.toml +++ b/basics/repository-layout/native/program/Cargo.toml @@ -19,7 +19,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-native-token = "3.0.0" diff --git a/basics/transfer-sol/native/program/Cargo.toml b/basics/transfer-sol/native/program/Cargo.toml index 821c85031..9202a2596 100644 --- a/basics/transfer-sol/native/program/Cargo.toml +++ b/basics/transfer-sol/native/program/Cargo.toml @@ -20,7 +20,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-native-token = "3.0.0" diff --git a/basics/transfer-sol/pinocchio/program/Cargo.toml b/basics/transfer-sol/pinocchio/program/Cargo.toml index aec50f992..570467285 100644 --- a/basics/transfer-sol/pinocchio/program/Cargo.toml +++ b/basics/transfer-sol/pinocchio/program/Cargo.toml @@ -18,7 +18,7 @@ custom-panic = [] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("solana"))'] } [dev-dependencies] -litesvm = "0.8.1" +litesvm = "0.11.0" solana-instruction = "3.0.0" solana-keypair = "3.0.1" solana-native-token = "3.0.0" From 3b74ffb38e873e59458c2068c2e3c80ef76e8a12 Mon Sep 17 00:00:00 2001 From: Mike MacCana Date: Wed, 1 Apr 2026 16:45:38 -0400 Subject: [PATCH 6/6] =?UTF-8?q?Fix:=20use=20=F0=9F=A4=A5=20emoji=20for=20P?= =?UTF-8?q?inocchio=20(lying=20face=20/=20growing=20nose)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 4.6 Fix: use inline emoji instead of GitHub shortcodes in README Co-Authored-By: Claude Sonnet 4.6 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fbf57e865..e19d4b286 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Program Examples -## Onchain program examples for :anchor: Anchor, :crab: Native Rust, and :boy: Pinocchio. +## Onchain program examples for ⚓ Anchor, 🦀 Native Rust, and 🤥 Pinocchio. [![Anchor](https://github.com/solana-developers/program-examples/actions/workflows/anchor.yml/badge.svg?event=schedule)](https://github.com/solana-developers/program-examples/actions/workflows/anchor.yml) [![Native](https://github.com/solana-developers/program-examples/actions/workflows/solana-native.yml/badge.svg?event=schedule)](https://github.com/solana-developers/program-examples/actions/workflows/solana-native.yml) [![Pinocchio](https://github.com/solana-developers/program-examples/actions/workflows/solana-pinocchio.yml/badge.svg?event=schedule)](https://github.com/solana-developers/program-examples/actions/workflows/solana-pinocchio.yml)