From bfc7961d378f2c33a838b4fbe2c79235f30ced41 Mon Sep 17 00:00:00 2001 From: wphan Date: Fri, 13 Dec 2024 10:49:19 -0800 Subject: [PATCH 01/32] add browser preid to npm build --- .github/workflows/main.yml | 9 +++++++++ sdk/README.md | 1 + 2 files changed, 10 insertions(+) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 1c83fb1b5..92091ba29 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -243,6 +243,15 @@ jobs: run: npm publish --access=public env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + - name: Build sdk for browser + run: yarn + - run: yarn build:browser + - name: Update browser package version + run: | + VERSION=$(node -e "console.log(require('./package.json').version);") + [[ "$VERSION" == *beta* ]] && npm version prerelease --preid=beta.browser || npm version preminor --preid=beta.browser + - name: Publish browser version to npm + run: npm publish --access=public emit-dispatch-events: runs-on: ubicloud needs: [release, check-for-sdk-changes] diff --git a/sdk/README.md b/sdk/README.md index 3d4f658f2..0e1c1a34d 100644 --- a/sdk/README.md +++ b/sdk/README.md @@ -273,3 +273,4 @@ Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Drift SDK by you, as defined in the Apache-2.0 license, shall be licensed as above, without any additional terms or conditions. + From f0cdb7e6f70035dd6bc3a968a9a1897d5a98cc59 Mon Sep 17 00:00:00 2001 From: GitHub Actions <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 13 Dec 2024 18:52:24 +0000 Subject: [PATCH 02/32] sdk: release v2.104.0-beta.17 --- sdk/VERSION | 2 +- sdk/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/VERSION b/sdk/VERSION index f3daa0ff4..c3af9ebae 100644 --- a/sdk/VERSION +++ b/sdk/VERSION @@ -1 +1 @@ -2.104.0-beta.16 \ No newline at end of file +2.104.0-beta.17 \ No newline at end of file diff --git a/sdk/package.json b/sdk/package.json index fa20edd60..6425e50dc 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@drift-labs/sdk", - "version": "2.104.0-beta.16", + "version": "2.104.0-beta.17", "main": "lib/node/index.js", "types": "lib/node/index.d.ts", "browser": "./lib/browser/index.js", From 55e787238fa7d50326d7a2b65cbebea5c5fb0828 Mon Sep 17 00:00:00 2001 From: wphan Date: Fri, 13 Dec 2024 11:04:07 -0800 Subject: [PATCH 03/32] add browser dist-tag --- .github/workflows/main.yml | 4 ++-- sdk/README.md | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 92091ba29..623ca8c45 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -249,9 +249,9 @@ jobs: - name: Update browser package version run: | VERSION=$(node -e "console.log(require('./package.json').version);") - [[ "$VERSION" == *beta* ]] && npm version prerelease --preid=beta.browser || npm version preminor --preid=beta.browser + [[ "$VERSION" == *beta* ]] && npm version prerelease --preid=beta || npm version preminor --preid=beta - name: Publish browser version to npm - run: npm publish --access=public + run: npm publish --access=public --tag browser emit-dispatch-events: runs-on: ubicloud needs: [release, check-for-sdk-changes] diff --git a/sdk/README.md b/sdk/README.md index 0e1c1a34d..3d4f658f2 100644 --- a/sdk/README.md +++ b/sdk/README.md @@ -273,4 +273,3 @@ Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Drift SDK by you, as defined in the Apache-2.0 license, shall be licensed as above, without any additional terms or conditions. - From 7ca6a50d18a8ab63c4252df125f8582dea5fb53e Mon Sep 17 00:00:00 2001 From: GitHub Actions <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 13 Dec 2024 19:07:32 +0000 Subject: [PATCH 04/32] sdk: release v2.104.0-beta.18 --- sdk/VERSION | 2 +- sdk/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/VERSION b/sdk/VERSION index c3af9ebae..8345e846e 100644 --- a/sdk/VERSION +++ b/sdk/VERSION @@ -1 +1 @@ -2.104.0-beta.17 \ No newline at end of file +2.104.0-beta.18 \ No newline at end of file diff --git a/sdk/package.json b/sdk/package.json index 6425e50dc..f3a7810a4 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@drift-labs/sdk", - "version": "2.104.0-beta.17", + "version": "2.104.0-beta.18", "main": "lib/node/index.js", "types": "lib/node/index.d.ts", "browser": "./lib/browser/index.js", From e4a2343bbf809168f0a11955ff94bf0da7a92135 Mon Sep 17 00:00:00 2001 From: wphan Date: Fri, 13 Dec 2024 11:08:47 -0800 Subject: [PATCH 05/32] fix github workflow --- .github/workflows/main.yml | 2 ++ sdk/README.md | 1 + 2 files changed, 3 insertions(+) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 623ca8c45..17ce2c2c8 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -252,6 +252,8 @@ jobs: [[ "$VERSION" == *beta* ]] && npm version prerelease --preid=beta || npm version preminor --preid=beta - name: Publish browser version to npm run: npm publish --access=public --tag browser + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} emit-dispatch-events: runs-on: ubicloud needs: [release, check-for-sdk-changes] diff --git a/sdk/README.md b/sdk/README.md index 3d4f658f2..0e1c1a34d 100644 --- a/sdk/README.md +++ b/sdk/README.md @@ -273,3 +273,4 @@ Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Drift SDK by you, as defined in the Apache-2.0 license, shall be licensed as above, without any additional terms or conditions. + From 766e85b25f1912844a44522ca2297f2bc7d6d12d Mon Sep 17 00:00:00 2001 From: GitHub Actions <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 13 Dec 2024 19:13:02 +0000 Subject: [PATCH 06/32] sdk: release v2.104.0-beta.19 --- sdk/VERSION | 2 +- sdk/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/VERSION b/sdk/VERSION index 8345e846e..a67df2759 100644 --- a/sdk/VERSION +++ b/sdk/VERSION @@ -1 +1 @@ -2.104.0-beta.18 \ No newline at end of file +2.104.0-beta.19 \ No newline at end of file diff --git a/sdk/package.json b/sdk/package.json index f3a7810a4..3a38c554d 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@drift-labs/sdk", - "version": "2.104.0-beta.18", + "version": "2.104.0-beta.19", "main": "lib/node/index.js", "types": "lib/node/index.d.ts", "browser": "./lib/browser/index.js", From aa8b4d28bf8c9ec3fb97dfaac309a2beda0b258b Mon Sep 17 00:00:00 2001 From: wphan Date: Fri, 13 Dec 2024 11:31:02 -0800 Subject: [PATCH 07/32] add @drift-labs/sdk-browser --- .github/workflows/main.yml | 16 +++++++--------- sdk/README.md | 1 - 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 17ce2c2c8..fd1b8d72e 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -224,15 +224,14 @@ jobs: run: | VERSION=$(node -e "console.log(require('./package.json').version);") [[ "$VERSION" == *beta* ]] && npm version prerelease --preid=beta || npm version preminor --preid=beta + echo "PACKAGE_VERSION=$(node -e "console.log(require('./package.json').version);")" >> $GITHUB_ENV - name: Git commit id: git-commit run: | - VERSION=$(node -e "console.log(require('./package.json').version);") - echo "version=$VERSION" >> $GITHUB_OUTPUT git config user.name "GitHub Actions" git config user.email 41898282+github-actions[bot]@users.noreply.github.com git add .. - git commit -a -m "sdk: release v$VERSION" + git commit -a -m "sdk: release v$PACKAGE_VERSION" git pull --rebase origin master git push origin HEAD || { echo "Push failed. Retrying after pulling latest changes..." @@ -244,14 +243,13 @@ jobs: env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - name: Build sdk for browser - run: yarn - - run: yarn build:browser - - name: Update browser package version run: | - VERSION=$(node -e "console.log(require('./package.json').version);") - [[ "$VERSION" == *beta* ]] && npm version prerelease --preid=beta || npm version preminor --preid=beta + yarn + yarn build:browser + # Update package name for browser version while keeping the same version + node -e "const pkg = require('./package.json'); pkg.name = pkg.name + '-browser'; require('fs').writeFileSync('package.json', JSON.stringify(pkg, null, 2));" - name: Publish browser version to npm - run: npm publish --access=public --tag browser + run: npm publish --access=public env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} emit-dispatch-events: diff --git a/sdk/README.md b/sdk/README.md index 0e1c1a34d..3d4f658f2 100644 --- a/sdk/README.md +++ b/sdk/README.md @@ -273,4 +273,3 @@ Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Drift SDK by you, as defined in the Apache-2.0 license, shall be licensed as above, without any additional terms or conditions. - From ae2ea00d7b77e4e8172bc133610c8dcf170b36b1 Mon Sep 17 00:00:00 2001 From: GitHub Actions <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 13 Dec 2024 19:34:30 +0000 Subject: [PATCH 08/32] sdk: release v2.104.0-beta.20 --- sdk/VERSION | 2 +- sdk/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/VERSION b/sdk/VERSION index a67df2759..df40642cb 100644 --- a/sdk/VERSION +++ b/sdk/VERSION @@ -1 +1 @@ -2.104.0-beta.19 \ No newline at end of file +2.104.0-beta.20 \ No newline at end of file diff --git a/sdk/package.json b/sdk/package.json index 3a38c554d..885c35e53 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@drift-labs/sdk", - "version": "2.104.0-beta.19", + "version": "2.104.0-beta.20", "main": "lib/node/index.js", "types": "lib/node/index.d.ts", "browser": "./lib/browser/index.js", From 41bc7b897eeb3650ff4dc23a8540eeee4957d25e Mon Sep 17 00:00:00 2001 From: wphan Date: Fri, 13 Dec 2024 11:39:01 -0800 Subject: [PATCH 09/32] sdk: bump version --- sdk/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/README.md b/sdk/README.md index 3d4f658f2..0e1c1a34d 100644 --- a/sdk/README.md +++ b/sdk/README.md @@ -273,3 +273,4 @@ Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Drift SDK by you, as defined in the Apache-2.0 license, shall be licensed as above, without any additional terms or conditions. + From 1ea6bcaa63eda9bc9c47f9e103ee9089c88e4cbf Mon Sep 17 00:00:00 2001 From: GitHub Actions <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 13 Dec 2024 19:42:02 +0000 Subject: [PATCH 10/32] sdk: release v2.104.0-beta.21 --- sdk/VERSION | 2 +- sdk/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/VERSION b/sdk/VERSION index df40642cb..6603b3de7 100644 --- a/sdk/VERSION +++ b/sdk/VERSION @@ -1 +1 @@ -2.104.0-beta.20 \ No newline at end of file +2.104.0-beta.21 \ No newline at end of file diff --git a/sdk/package.json b/sdk/package.json index 885c35e53..5a36b5d7e 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@drift-labs/sdk", - "version": "2.104.0-beta.20", + "version": "2.104.0-beta.21", "main": "lib/node/index.js", "types": "lib/node/index.d.ts", "browser": "./lib/browser/index.js", From 687436a1062f8c8f8a30cf22af7aba135240d3fc Mon Sep 17 00:00:00 2001 From: lowkeynicc <85139158+lowkeynicc@users.noreply.github.com> Date: Fri, 13 Dec 2024 15:40:05 -0500 Subject: [PATCH 11/32] update constants to POL (#1382) --- sdk/src/constants/perpMarkets.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/constants/perpMarkets.ts b/sdk/src/constants/perpMarkets.ts index 9bcadcdbe..9b2f89aec 100644 --- a/sdk/src/constants/perpMarkets.ts +++ b/sdk/src/constants/perpMarkets.ts @@ -78,8 +78,8 @@ export const DevnetPerpMarkets: PerpMarketConfig[] = [ { fullName: 'Polygon', category: ['L2', 'Infra'], - symbol: 'MATIC-PERP', - baseAssetSymbol: 'MATIC', + symbol: 'POL-PERP', + baseAssetSymbol: 'POL', marketIndex: 5, oracle: new PublicKey('BrzyDgwELy4jjjsqLQpBeUxzrsueYyMhuWpYBaUYcXvi'), launchTs: 1677690149000, //todo From a6b6eb8d97e49f3164ca7de03805dc7084c25f46 Mon Sep 17 00:00:00 2001 From: GitHub Actions <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 13 Dec 2024 20:43:41 +0000 Subject: [PATCH 12/32] sdk: release v2.104.0-beta.22 --- sdk/VERSION | 2 +- sdk/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/VERSION b/sdk/VERSION index 6603b3de7..e04cd4f31 100644 --- a/sdk/VERSION +++ b/sdk/VERSION @@ -1 +1 @@ -2.104.0-beta.21 \ No newline at end of file +2.104.0-beta.22 \ No newline at end of file diff --git a/sdk/package.json b/sdk/package.json index 5a36b5d7e..d8d47729d 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@drift-labs/sdk", - "version": "2.104.0-beta.21", + "version": "2.104.0-beta.22", "main": "lib/node/index.js", "types": "lib/node/index.d.ts", "browser": "./lib/browser/index.js", From f6de932b9d85a3ac6c749967b149231c950c942a Mon Sep 17 00:00:00 2001 From: lowkeynicc Date: Fri, 13 Dec 2024 16:38:47 -0500 Subject: [PATCH 13/32] sdk: matic -> pol for mainnet --- sdk/src/constants/perpMarkets.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/constants/perpMarkets.ts b/sdk/src/constants/perpMarkets.ts index 9b2f89aec..cad7b4cfe 100644 --- a/sdk/src/constants/perpMarkets.ts +++ b/sdk/src/constants/perpMarkets.ts @@ -423,8 +423,8 @@ export const MainnetPerpMarkets: PerpMarketConfig[] = [ { fullName: 'Polygon', category: ['L2', 'Infra'], - symbol: 'MATIC-PERP', - baseAssetSymbol: 'MATIC', + symbol: 'POL-PERP', + baseAssetSymbol: 'POL', marketIndex: 5, oracle: new PublicKey('BrzyDgwELy4jjjsqLQpBeUxzrsueYyMhuWpYBaUYcXvi'), launchTs: 1677690149000, //todo From 0e10baa77566f8ba2d109fe47c5af58fda5b078b Mon Sep 17 00:00:00 2001 From: GitHub Actions <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 13 Dec 2024 21:41:40 +0000 Subject: [PATCH 14/32] sdk: release v2.104.0-beta.23 --- sdk/VERSION | 2 +- sdk/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/VERSION b/sdk/VERSION index e04cd4f31..5f4cde65a 100644 --- a/sdk/VERSION +++ b/sdk/VERSION @@ -1 +1 @@ -2.104.0-beta.22 \ No newline at end of file +2.104.0-beta.23 \ No newline at end of file diff --git a/sdk/package.json b/sdk/package.json index d8d47729d..307369b24 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@drift-labs/sdk", - "version": "2.104.0-beta.22", + "version": "2.104.0-beta.23", "main": "lib/node/index.js", "types": "lib/node/index.d.ts", "browser": "./lib/browser/index.js", From 54a2bd148675ac7fd296141ea3486c5f68cdd25c Mon Sep 17 00:00:00 2001 From: Chester Sim Date: Tue, 17 Dec 2024 00:39:55 +0800 Subject: [PATCH 15/32] refactor(sdk): concurrently fetch user stats and user accounts --- sdk/src/driftClient.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/sdk/src/driftClient.ts b/sdk/src/driftClient.ts index 29abf5d2f..2df2efc25 100644 --- a/sdk/src/driftClient.ts +++ b/sdk/src/driftClient.ts @@ -776,16 +776,23 @@ export class DriftClient { accountSubscription: this.userStatsAccountSubscriptionConfig, }); - await this.userStats.subscribe(); + const subscriptionPromises: Promise[] = [this.userStats.subscribe()]; + let success = true; if (this.isSubscribed) { - await Promise.all(this.unsubscribeUsers()); - this.users.clear(); - success = await this.addAndSubscribeToUsers(); + const reSubscribeUsersPromise = async () => { + await Promise.all(this.unsubscribeUsers()); + this.users.clear(); + success = await this.addAndSubscribeToUsers(); + }; + + subscriptionPromises.push(reSubscribeUsersPromise()); } + await Promise.all(subscriptionPromises); + return success; } From 38bf5fbbed208812d5a77c5b3129ef720a231534 Mon Sep 17 00:00:00 2001 From: Chris Heaney Date: Mon, 16 Dec 2024 12:06:54 -0500 Subject: [PATCH 16/32] sdk: add methods to init pmm --- sdk/src/addresses/pda.ts | 13 ++++++++ sdk/src/adminClient.ts | 72 ++++++++++++++++++++++++++++++++++++++++ sdk/src/driftClient.ts | 1 - 3 files changed, 85 insertions(+), 1 deletion(-) diff --git a/sdk/src/addresses/pda.ts b/sdk/src/addresses/pda.ts index fe188faf3..793ade9c7 100644 --- a/sdk/src/addresses/pda.ts +++ b/sdk/src/addresses/pda.ts @@ -353,3 +353,16 @@ export function getHighLeverageModeConfigPublicKey( programId )[0]; } + +export function getProtectedMakerModeConfigPublicKey( + programId: PublicKey +): PublicKey { + return PublicKey.findProgramAddressSync( + [ + Buffer.from( + anchor.utils.bytes.utf8.encode('protected_maker_mode_config') + ), + ], + programId + )[0]; +} diff --git a/sdk/src/adminClient.ts b/sdk/src/adminClient.ts index 58080e844..1d665c634 100644 --- a/sdk/src/adminClient.ts +++ b/sdk/src/adminClient.ts @@ -34,6 +34,7 @@ import { getUserStatsAccountPublicKey, getHighLeverageModeConfigPublicKey, getPythLazerOraclePublicKey, + getProtectedMakerModeConfigPublicKey, } from './addresses/pda'; import { squareRootBN } from './math/utils'; import { TOKEN_PROGRAM_ID } from '@solana/spl-token'; @@ -4027,4 +4028,75 @@ export class AdminClient extends DriftClient { } ); } + + public async initializeProtectedMakerModeConfig( + maxUsers: number + ): Promise { + const initializeProtectedMakerModeConfigIx = + await this.getInitializeProtectedMakerModeConfigIx(maxUsers); + + const tx = await this.buildTransaction( + initializeProtectedMakerModeConfigIx + ); + + const { txSig } = await this.sendTransaction(tx, [], this.opts); + + return txSig; + } + + public async getInitializeProtectedMakerModeConfigIx( + maxUsers: number + ): Promise { + return await this.program.instruction.initializeProtectedMakerModeConfig( + maxUsers, + { + accounts: { + admin: this.isSubscribed + ? this.getStateAccount().admin + : this.wallet.publicKey, + state: await this.getStatePublicKey(), + rent: SYSVAR_RENT_PUBKEY, + systemProgram: anchor.web3.SystemProgram.programId, + protectedMakerModeConfig: getProtectedMakerModeConfigPublicKey( + this.program.programId + ), + }, + } + ); + } + + public async updateProtectedMakerModeConfig( + maxUsers: number, + reduceOnly: boolean + ): Promise { + const updateProtectedMakerModeConfigIx = + await this.getUpdateProtectedMakerModeConfigIx(maxUsers, reduceOnly); + + const tx = await this.buildTransaction(updateProtectedMakerModeConfigIx); + + const { txSig } = await this.sendTransaction(tx, [], this.opts); + + return txSig; + } + + public async getUpdateProtectedMakerModeConfigIx( + maxUsers: number, + reduceOnly: boolean + ): Promise { + return await this.program.instruction.updateProtectedMakerModeConfig( + maxUsers, + reduceOnly, + { + accounts: { + admin: this.isSubscribed + ? this.getStateAccount().admin + : this.wallet.publicKey, + state: await this.getStatePublicKey(), + protectedMakerModeConfig: getProtectedMakerModeConfigPublicKey( + this.program.programId + ), + }, + } + ); + } } diff --git a/sdk/src/driftClient.ts b/sdk/src/driftClient.ts index 2df2efc25..a0c433eb6 100644 --- a/sdk/src/driftClient.ts +++ b/sdk/src/driftClient.ts @@ -778,7 +778,6 @@ export class DriftClient { const subscriptionPromises: Promise[] = [this.userStats.subscribe()]; - let success = true; if (this.isSubscribed) { From 38bde2e36bb2392513d6257297216e78f60c287e Mon Sep 17 00:00:00 2001 From: GitHub Actions <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 16 Dec 2024 17:09:46 +0000 Subject: [PATCH 17/32] sdk: release v2.104.0-beta.24 --- sdk/VERSION | 2 +- sdk/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/VERSION b/sdk/VERSION index 5f4cde65a..2f7814ce7 100644 --- a/sdk/VERSION +++ b/sdk/VERSION @@ -1 +1 @@ -2.104.0-beta.23 \ No newline at end of file +2.104.0-beta.24 \ No newline at end of file diff --git a/sdk/package.json b/sdk/package.json index 307369b24..4bf7daadb 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@drift-labs/sdk", - "version": "2.104.0-beta.23", + "version": "2.104.0-beta.24", "main": "lib/node/index.js", "types": "lib/node/index.d.ts", "browser": "./lib/browser/index.js", From 24ed43251302c4de90059551b2ae94cc5b1028a4 Mon Sep 17 00:00:00 2001 From: Chris Heaney Date: Mon, 16 Dec 2024 14:03:14 -0500 Subject: [PATCH 18/32] sdk: add updateUserProtectedMakerOrders --- sdk/src/driftClient.ts | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/sdk/src/driftClient.ts b/sdk/src/driftClient.ts index a0c433eb6..63388bfb9 100644 --- a/sdk/src/driftClient.ts +++ b/sdk/src/driftClient.ts @@ -93,6 +93,7 @@ import { getOpenbookV2FulfillmentConfigPublicKey, getPerpMarketPublicKey, getPhoenixFulfillmentConfigPublicKey, + getProtectedMakerModeConfigPublicKey, getPythLazerOraclePublicKey, getPythPullOraclePublicKey, getReferrerNamePublicKeySync, @@ -8896,6 +8897,45 @@ export class DriftClient { return config as HighLeverageModeConfig; } + public async updateUserProtectedMakerOrders( + subAccountId: number, + txParams?: TxParams + ): Promise { + const { txSig } = await this.sendTransaction( + await this.buildTransaction( + await this.getUpdateUserProtectedMakerOrdersIx(subAccountId), + txParams + ), + [], + this.opts + ); + return txSig; + } + + public async getUpdateUserProtectedMakerOrdersIx( + subAccountId: number + ): Promise { + const ix = await this.program.instruction.updateUserProtectedMakerOrders( + subAccountId, + { + accounts: { + state: await this.getStatePublicKey(), + user: getUserAccountPublicKeySync( + this.program.programId, + this.wallet.publicKey, + subAccountId + ), + authority: this.wallet.publicKey, + protectedMakerModeConfig: getProtectedMakerModeConfigPublicKey( + this.program.programId + ), + }, + } + ); + + return ix; + } + private handleSignedTransaction(signedTxs: SignedTxData[]) { if (this.enableMetricsEvents && this.metricsEventEmitter) { this.metricsEventEmitter.emit('txSigned', signedTxs); From 28090f7aff8d0e73145dc0a5ce4077258c115bf4 Mon Sep 17 00:00:00 2001 From: GitHub Actions <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 16 Dec 2024 19:06:51 +0000 Subject: [PATCH 19/32] sdk: release v2.104.0-beta.25 --- sdk/VERSION | 2 +- sdk/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/VERSION b/sdk/VERSION index 2f7814ce7..55b5d683e 100644 --- a/sdk/VERSION +++ b/sdk/VERSION @@ -1 +1 @@ -2.104.0-beta.24 \ No newline at end of file +2.104.0-beta.25 \ No newline at end of file diff --git a/sdk/package.json b/sdk/package.json index 4bf7daadb..e514f531e 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@drift-labs/sdk", - "version": "2.104.0-beta.24", + "version": "2.104.0-beta.25", "main": "lib/node/index.js", "types": "lib/node/index.d.ts", "browser": "./lib/browser/index.js", From 70f3da20e783825723cc9a4d0eb4879a30c036ca Mon Sep 17 00:00:00 2001 From: moosecat Date: Mon, 16 Dec 2024 12:32:57 -0800 Subject: [PATCH 20/32] remove swift messages from swift (#1386) * remove swift messages from swift * revert Anchor.toml changes * add slot sanity check --- programs/drift/src/error.rs | 2 +- programs/drift/src/instructions/keeper.rs | 51 ++--- programs/drift/src/lib.rs | 3 +- programs/drift/src/state/order_params.rs | 9 +- sdk/src/config.ts | 3 - sdk/src/driftClient.ts | 79 +------ sdk/src/driftClientConfig.ts | 1 - sdk/src/idl/drift.json | 43 +--- sdk/src/types.ts | 8 +- sdk/src/util/digest.ts | 5 + .../run-anchor-local-validator-tests.sh | 4 +- tests/placeAndMakeSwiftPerp.ts | 215 ++---------------- tests/placeAndMakeSwiftPerpBankrun.ts | 178 +++------------ 13 files changed, 93 insertions(+), 508 deletions(-) diff --git a/programs/drift/src/error.rs b/programs/drift/src/error.rs index 7a0705188..5c2d229ab 100644 --- a/programs/drift/src/error.rs +++ b/programs/drift/src/error.rs @@ -581,7 +581,7 @@ pub enum ErrorCode { SigVerificationFailed, #[msg("Market index mismatched b/w taker and maker swift order params")] MismatchedSwiftOrderParamsMarketIndex, - #[msg("Swift only available for market/oracle perp orders")] + #[msg("Invalid swift order param")] InvalidSwiftOrderParam, #[msg("Place and take order success condition failed")] PlaceAndTakeOrderSuccessConditionFailed, diff --git a/programs/drift/src/instructions/keeper.rs b/programs/drift/src/instructions/keeper.rs index c45c82d23..811777cd5 100644 --- a/programs/drift/src/instructions/keeper.rs +++ b/programs/drift/src/instructions/keeper.rs @@ -40,9 +40,7 @@ use crate::state::fulfillment_params::serum::SerumFulfillmentParams; use crate::state::high_leverage_mode_config::HighLeverageModeConfig; use crate::state::insurance_fund_stake::InsuranceFundStake; use crate::state::oracle_map::OracleMap; -use crate::state::order_params::{ - OrderParams, PlaceOrderOptions, SwiftOrderParamsMessage, SwiftServerMessage, -}; +use crate::state::order_params::{OrderParams, PlaceOrderOptions, SwiftOrderParamsMessage}; use crate::state::paused_operations::PerpOperation; use crate::state::perp_market::{ContractType, MarketStatus, PerpMarket}; use crate::state::perp_market_map::{ @@ -603,11 +601,8 @@ pub fn handle_update_user_open_orders_count<'info>(ctx: Context) pub fn handle_place_swift_taker_order<'c: 'info, 'info>( ctx: Context<'_, '_, 'c, 'info, PlaceSwiftTakerOrder<'info>>, - swift_message_bytes: Vec, swift_order_params_message_bytes: Vec, ) -> Result<()> { - let swift_message: SwiftServerMessage = - SwiftServerMessage::deserialize(&mut &swift_message_bytes[..]).unwrap(); let taker_order_params_message: SwiftOrderParamsMessage = SwiftOrderParamsMessage::deserialize(&mut &swift_order_params_message_bytes[..]).unwrap(); @@ -634,7 +629,6 @@ pub fn handle_place_swift_taker_order<'c: 'info, 'info>( taker_key, &mut taker, &mut swift_taker, - swift_message, taker_order_params_message, &ctx.accounts.ix_sysvar.to_account_info(), &perp_market_map, @@ -649,7 +643,6 @@ pub fn place_swift_taker_order<'c: 'info, 'info>( taker_key: Pubkey, taker: &mut RefMut, swift_account: &mut SwiftUserOrdersZeroCopyMut, - swift_message: SwiftServerMessage, taker_order_params_message: SwiftOrderParamsMessage, ix_sysvar: &AccountInfo<'info>, perp_market_map: &PerpMarketMap, @@ -665,20 +658,12 @@ pub fn place_swift_taker_order<'c: 'info, 'info>( // Authenticate the swift param message let ix_idx = load_current_index_checked(ix_sysvar)?; validate!( - ix_idx > 1, + ix_idx > 0, ErrorCode::InvalidVerificationIxIndex, - "instruction index must be greater than 1 for two sig verifies" + "instruction index must be greater than 0 for one sig verifies" )?; - // Verify data from first verify ix - let ix: Instruction = load_instruction_at_checked(ix_idx as usize - 2, ix_sysvar)?; - verify_ed25519_msg( - &ix, - &swift_server::id().to_bytes(), - &digest_struct!(swift_message), - )?; - - // Verify data from second verify ix + // Verify data from verify ix let digest_hex = digest_struct_hex!(taker_order_params_message); let ix: Instruction = load_instruction_at_checked(ix_idx as usize - 1, ix_sysvar)?; verify_ed25519_msg( @@ -687,12 +672,7 @@ pub fn place_swift_taker_order<'c: 'info, 'info>( arrayref::array_ref!(digest_hex, 0, 64), )?; - // Verify that sig from swift server corresponds to order message - if swift_message.swift_order_signature != extract_ed25519_ix_signature(&ix.data)? { - msg!("Swift order signature does not match the order signature"); - return Err(ErrorCode::SigVerificationFailed.into()); - } - + let signature = extract_ed25519_ix_signature(&ix.data)?; let clock = &Clock::get()?; // First order must be a taker order @@ -715,7 +695,14 @@ pub fn place_swift_taker_order<'c: 'info, 'info>( } // Set max slot for the order early so we set correct swift order id - let order_slot = swift_message.slot; + let order_slot = taker_order_params_message.slot; + if order_slot < clock.slot - 500 { + msg!( + "Swift order slot {} is too old: must be within 500 slots of current slot", + order_slot + ); + return Err(print_error!(ErrorCode::InvalidSwiftOrderParam)().into()); + } let market_index = matching_taker_order_params.market_index; let max_slot = order_slot.safe_add( matching_taker_order_params @@ -735,7 +722,11 @@ pub fn place_swift_taker_order<'c: 'info, 'info>( } // Dont place order if swift order already exists - let swift_order_id = SwiftOrderId::new(swift_message.uuid, max_slot, taker.next_order_id); + let swift_order_id = SwiftOrderId::new( + taker_order_params_message.uuid, + max_slot, + taker.next_order_id, + ); if swift_account.check_exists_and_prune_stale_swift_order_ids(swift_order_id, clock.slot) { msg!("Swift order already exists for taker {}"); return Ok(()); @@ -757,10 +748,8 @@ pub fn place_swift_taker_order<'c: 'info, 'info>( }, )?; - let order_params_hash = base64::encode( - solana_program::hash::hash(&swift_message.swift_order_signature.try_to_vec().unwrap()) - .as_ref(), - ); + let order_params_hash = + base64::encode(solana_program::hash::hash(&signature.try_to_vec().unwrap()).as_ref()); emit!(SwiftOrderRecord { user: taker_key, diff --git a/programs/drift/src/lib.rs b/programs/drift/src/lib.rs index 444b11117..cde40ba8d 100644 --- a/programs/drift/src/lib.rs +++ b/programs/drift/src/lib.rs @@ -191,10 +191,9 @@ pub mod drift { pub fn place_swift_taker_order<'c: 'info, 'info>( ctx: Context<'_, '_, 'c, 'info, PlaceSwiftTakerOrder<'info>>, - swift_message_bytes: Vec, swift_order_params_message_bytes: Vec, ) -> Result<()> { - handle_place_swift_taker_order(ctx, swift_message_bytes, swift_order_params_message_bytes) + handle_place_swift_taker_order(ctx, swift_order_params_message_bytes) } pub fn place_and_match_rfq_orders<'c: 'info, 'info>( diff --git a/programs/drift/src/state/order_params.rs b/programs/drift/src/state/order_params.rs index 1564ed800..edad8fa02 100644 --- a/programs/drift/src/state/order_params.rs +++ b/programs/drift/src/state/order_params.rs @@ -706,17 +706,12 @@ impl OrderParams { } } -#[derive(AnchorSerialize, AnchorDeserialize, Clone, Eq, PartialEq, Debug)] -pub struct SwiftServerMessage { - pub uuid: [u8; 8], - pub swift_order_signature: [u8; 64], - pub slot: u64, -} - #[derive(AnchorSerialize, AnchorDeserialize, Clone, Default, Eq, PartialEq, Debug)] pub struct SwiftOrderParamsMessage { pub swift_order_params: OrderParams, pub sub_account_id: u16, + pub slot: u64, + pub uuid: [u8; 8], pub take_profit_order_params: Option, pub stop_loss_order_params: Option, } diff --git a/sdk/src/config.ts b/sdk/src/config.ts index bf4eea392..e32fced8d 100644 --- a/sdk/src/config.ts +++ b/sdk/src/config.ts @@ -44,9 +44,6 @@ export type DriftEnv = 'devnet' | 'mainnet-beta'; export const DRIFT_PROGRAM_ID = 'dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH'; export const DRIFT_ORACLE_RECEIVER_ID = 'G6EoTTTgpkNBtVXo96EQp2m6uwwVh2Kt6YidjkmQqoha'; -export const SWIFT_ID = 'SW1fThqrxLzVprnCMpiybiqYQfoNCdduC5uWsSUKChS'; -export const ANCHOR_TEST_SWIFT_ID = - 'DpaEdAPW3ZX67fnczT14AoX12Lx9VMkxvtT81nCHy3Nv'; export const PTYH_LAZER_PROGRAM_ID = 'pytd2yyk641x7ak7mkaasSJVXh6YYZnC7wTmtgAyxPt'; export const PYTH_LAZER_STORAGE_ACCOUNT_KEY = new PublicKey( diff --git a/sdk/src/driftClient.ts b/sdk/src/driftClient.ts index 63388bfb9..75a4b5c11 100644 --- a/sdk/src/driftClient.ts +++ b/sdk/src/driftClient.ts @@ -54,7 +54,6 @@ import { StateAccount, SwapReduceOnly, SwiftOrderParamsMessage, - SwiftServerMessage, TakerInfo, TxParams, UserAccount, @@ -136,7 +135,6 @@ import { DRIFT_ORACLE_RECEIVER_ID, DEFAULT_CONFIRMATION_OPTS, DRIFT_PROGRAM_ID, - SWIFT_ID, DriftEnv, PYTH_LAZER_STORAGE_ACCOUNT_KEY, } from './config'; @@ -202,7 +200,6 @@ export class DriftClient { connection: Connection; wallet: IWallet; public program: Program; - public swiftID: PublicKey; provider: AnchorProvider; opts?: ConfirmOptions; users = new Map(); @@ -270,7 +267,6 @@ export class DriftClient { config.programID ?? new PublicKey(DRIFT_PROGRAM_ID), this.provider ); - this.swiftID = config.swiftID ?? new PublicKey(SWIFT_ID); this.authority = config.authority ?? this.wallet.publicKey; this.activeSubAccountId = config.activeSubAccountId ?? 0; @@ -5847,29 +5843,6 @@ export class DriftClient { ); } - public encodeSwiftServerMessage(message: SwiftServerMessage): Buffer { - return this.program.coder.types.encode('SwiftServerMessage', message); - } - - public decodeSwiftServerMessage(encodedMessage: Buffer): SwiftServerMessage { - const decodedSwiftMessage = this.program.coder.types.decode( - 'SwiftServerMessage', - encodedMessage - ); - return { - uuid: decodedSwiftMessage.uuid, - slot: decodedSwiftMessage.slot, - swiftOrderSignature: decodedSwiftMessage.swiftSignature, - }; - } - - public signSwiftServerMessage(message: SwiftServerMessage): Buffer { - const swiftServerMessage = Uint8Array.from( - digest(this.encodeSwiftServerMessage(message)) - ); - return this.signMessage(swiftServerMessage); - } - public signSwiftOrderParamsMessage( orderParamsMessage: SwiftOrderParamsMessage ): Buffer { @@ -5906,8 +5879,6 @@ export class DriftClient { } public async placeSwiftTakerOrder( - swiftServerMessage: Buffer, - swiftSignature: Buffer, swiftOrderParamsMessage: Buffer, swiftOrderParamsSignature: Buffer, marketIndex: number, @@ -5919,8 +5890,6 @@ export class DriftClient { txParams?: TxParams ): Promise { const ixs = await this.getPlaceSwiftTakerPerpOrderIxs( - swiftServerMessage, - swiftSignature, swiftOrderParamsMessage, swiftOrderParamsSignature, marketIndex, @@ -5935,8 +5904,6 @@ export class DriftClient { } public async getPlaceSwiftTakerPerpOrderIxs( - encodedSwiftServerMessage: Buffer, - swiftSignature: Buffer, encodedSwiftOrderParamsMessage: Buffer, swiftOrderParamsSignature: Buffer, marketIndex: number, @@ -5957,13 +5924,6 @@ export class DriftClient { readablePerpMarketIndex: marketIndex, }); - const swiftServerSignatureIx = - Ed25519Program.createInstructionWithPublicKey({ - publicKey: new PublicKey(this.swiftID).toBytes(), - signature: Uint8Array.from(swiftSignature), - message: Uint8Array.from(digest(encodedSwiftServerMessage)), - }); - const authorityToUse = authority || takerInfo.takerUserAccount.authority; const swiftOrderParamsSignatureIx = Ed25519Program.createInstructionWithPublicKey({ @@ -5976,7 +5936,6 @@ export class DriftClient { const placeTakerSwiftPerpOrderIx = await this.program.instruction.placeSwiftTakerOrder( - encodedSwiftServerMessage, encodedSwiftOrderParamsMessage, { accounts: { @@ -5994,16 +5953,10 @@ export class DriftClient { } ); - return [ - swiftServerSignatureIx, - swiftOrderParamsSignatureIx, - placeTakerSwiftPerpOrderIx, - ]; + return [swiftOrderParamsSignatureIx, placeTakerSwiftPerpOrderIx]; } public async placeAndMakeSwiftPerpOrder( - encodedSwiftMessage: Buffer, - swiftSignature: Buffer, encodedSwiftOrderParamsMessage: Buffer, swiftOrderParamsSignature: Buffer, swiftOrderUuid: Uint8Array, @@ -6018,8 +5971,6 @@ export class DriftClient { subAccountId?: number ): Promise { const ixs = await this.getPlaceAndMakeSwiftPerpOrderIxs( - encodedSwiftMessage, - swiftSignature, encodedSwiftOrderParamsMessage, swiftOrderParamsSignature, swiftOrderUuid, @@ -6039,8 +5990,6 @@ export class DriftClient { } public async getPlaceAndMakeSwiftPerpOrderIxs( - encodedSwiftMessage: Buffer, - swiftSignature: Buffer, encodedSwiftOrderParamsMessage: Buffer, swiftOrderParamsSignature: Buffer, swiftOrderUuid: Uint8Array, @@ -6053,18 +6002,13 @@ export class DriftClient { referrerInfo?: ReferrerInfo, subAccountId?: number ): Promise { - const [ - swiftServerSignatureIx, - swiftOrderSignatureIx, - placeTakerSwiftPerpOrderIx, - ] = await this.getPlaceSwiftTakerPerpOrderIxs( - encodedSwiftMessage, - swiftSignature, - encodedSwiftOrderParamsMessage, - swiftOrderParamsSignature, - orderParams.marketIndex, - takerInfo - ); + const [swiftOrderSignatureIx, placeTakerSwiftPerpOrderIx] = + await this.getPlaceSwiftTakerPerpOrderIxs( + encodedSwiftOrderParamsMessage, + swiftOrderParamsSignature, + orderParams.marketIndex, + takerInfo + ); orderParams = getOrderParams(orderParams, { marketType: MarketType.PERP }); const userStatsPublicKey = this.getUserStatsAccountPublicKey(); @@ -6113,12 +6057,7 @@ export class DriftClient { } ); - return [ - swiftServerSignatureIx, - swiftOrderSignatureIx, - placeTakerSwiftPerpOrderIx, - placeAndMakeIx, - ]; + return [swiftOrderSignatureIx, placeTakerSwiftPerpOrderIx, placeAndMakeIx]; } public encodeRFQMakerOrderParams(message: RFQMakerOrderParams): Buffer { diff --git a/sdk/src/driftClientConfig.ts b/sdk/src/driftClientConfig.ts index 5cf7f88ed..1b74de6ec 100644 --- a/sdk/src/driftClientConfig.ts +++ b/sdk/src/driftClientConfig.ts @@ -18,7 +18,6 @@ export type DriftClientConfig = { wallet: IWallet; env?: DriftEnv; programID?: PublicKey; - swiftID?: PublicKey; accountSubscription?: DriftClientSubscriptionConfig; opts?: ConfirmOptions; txSender?: TxSender; diff --git a/sdk/src/idl/drift.json b/sdk/src/idl/drift.json index 62b9efe71..22561a49b 100644 --- a/sdk/src/idl/drift.json +++ b/sdk/src/idl/drift.json @@ -813,10 +813,6 @@ } ], "args": [ - { - "name": "swiftMessageBytes", - "type": "bytes" - }, { "name": "swiftOrderParamsMessageBytes", "type": "bytes" @@ -9002,50 +8998,33 @@ } }, { - "name": "SwiftServerMessage", + "name": "SwiftOrderParamsMessage", "type": { "kind": "struct", "fields": [ { - "name": "uuid", + "name": "swiftOrderParams", "type": { - "array": [ - "u8", - 8 - ] + "defined": "OrderParams" } }, { - "name": "swiftOrderSignature", - "type": { - "array": [ - "u8", - 64 - ] - } + "name": "subAccountId", + "type": "u16" }, { "name": "slot", "type": "u64" - } - ] - } - }, - { - "name": "SwiftOrderParamsMessage", - "type": { - "kind": "struct", - "fields": [ + }, { - "name": "swiftOrderParams", + "name": "uuid", "type": { - "defined": "OrderParams" + "array": [ + "u8", + 8 + ] } }, - { - "name": "subAccountId", - "type": "u16" - }, { "name": "takeProfitOrderParams", "type": { diff --git a/sdk/src/types.ts b/sdk/src/types.ts index a61f6917e..055478e3f 100644 --- a/sdk/src/types.ts +++ b/sdk/src/types.ts @@ -1105,15 +1105,11 @@ export const DefaultOrderParams: OrderParams = { auctionEndPrice: null, }; -export type SwiftServerMessage = { - slot: BN; - swiftOrderSignature: Uint8Array; - uuid: Uint8Array; // From buffer of standard UUID string -}; - export type SwiftOrderParamsMessage = { swiftOrderParams: OptionalOrderParams; subAccountId: number; + uuid: Uint8Array; + slot: BN; takeProfitOrderParams: SwiftTriggerOrderParams | null; stopLossOrderParams: SwiftTriggerOrderParams | null; }; diff --git a/sdk/src/util/digest.ts b/sdk/src/util/digest.ts index fdb7f54fa..7a16c0143 100644 --- a/sdk/src/util/digest.ts +++ b/sdk/src/util/digest.ts @@ -1,4 +1,5 @@ import { createHash } from 'crypto'; +import { nanoid } from 'nanoid'; export function digest(data: Buffer): Buffer { const hash = createHash('sha256'); @@ -9,3 +10,7 @@ export function digest(data: Buffer): Buffer { export function digestSignature(signature: Uint8Array): string { return createHash('sha256').update(signature).digest('base64'); } + +export function generateSwiftUuid(): Uint8Array { + return Uint8Array.from(Buffer.from(nanoid(8))); +} diff --git a/test-scripts/run-anchor-local-validator-tests.sh b/test-scripts/run-anchor-local-validator-tests.sh index be7464abb..5678eb24c 100644 --- a/test-scripts/run-anchor-local-validator-tests.sh +++ b/test-scripts/run-anchor-local-validator-tests.sh @@ -6,8 +6,8 @@ fi export ANCHOR_WALLET=~/.config/solana/id.json test_files=( - #placeAndMakeSwiftPerp.ts, - pythLazer.ts + placeAndMakeSwiftPerp.ts + # pythLazer.ts ) diff --git a/tests/placeAndMakeSwiftPerp.ts b/tests/placeAndMakeSwiftPerp.ts index b9b4673cd..1b197c5bb 100644 --- a/tests/placeAndMakeSwiftPerp.ts +++ b/tests/placeAndMakeSwiftPerp.ts @@ -6,7 +6,6 @@ import { Program } from '@coral-xyz/anchor'; import { ComputeBudgetProgram, Keypair, - PublicKey, SendTransactionError, Transaction, TransactionMessage, @@ -26,12 +25,10 @@ import { OracleSource, BulkAccountLoader, SwiftOrderParamsMessage, - SwiftServerMessage, loadKeypair, getMarketOrderParams, MarketType, DriftClient, - ANCHOR_TEST_SWIFT_ID, } from '../sdk/src'; import { @@ -43,21 +40,14 @@ import { } from './testHelpersLocalValidator'; import { PEG_PRECISION, PostOnlyParams } from '../sdk/src'; import dotenv from 'dotenv'; -import { digest } from '../sdk/src/util/digest'; import { nanoid } from 'nanoid'; dotenv.config(); describe('place and make swift order', () => { - if (!process.env.SWIFT_PRIVATE_KEY) { - throw new Error('SWIFT_PRIVATE_KEY not set'); - } - if (!process.env.ANCHOR_WALLET) { throw new Error('ANCHOR_WALLET not set'); } - const swiftKeypair = loadKeypair(process.env.SWIFT_PRIVATE_KEY); - const provider = anchor.AnchorProvider.local(undefined, { commitment: 'confirmed', preflightCommitment: 'confirmed', @@ -128,7 +118,6 @@ describe('place and make swift order', () => { type: 'polling', accountLoader: bulkAccountLoader, }, - swiftID: new PublicKey(ANCHOR_TEST_SWIFT_ID), }); await makerDriftClient.initialize(usdcMint.publicKey, true); await makerDriftClient.subscribe(); @@ -193,7 +182,6 @@ describe('place and make swift order', () => { type: 'polling', accountLoader: bulkAccountLoader, }, - swiftID: new PublicKey(ANCHOR_TEST_SWIFT_ID), }); await takerDriftClient.subscribe(); @@ -230,9 +218,12 @@ describe('place and make swift order', () => { postOnly: PostOnlyParams.NONE, marketType: MarketType.PERP, }); + const uuid = Uint8Array.from(Buffer.from(nanoid(8))); const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, subAccountId: 0, + slot: new BN(await connection.getSlot()), + uuid, takeProfitOrderParams: null, stopLossOrderParams: null, }; @@ -253,26 +244,10 @@ describe('place and make swift order', () => { takerOrderParamsMessage ); - const swiftServerMessage: SwiftServerMessage = { - slot: new BN(await connection.getSlot()), - swiftOrderSignature: takerOrderParamsSig, - uuid: Uint8Array.from(Buffer.from(nanoid(8))), - }; - - const encodedSwiftServerMessage = - makerDriftClient.encodeSwiftServerMessage(swiftServerMessage); - - const swiftSignature = makerDriftClient.signMessage( - digest(encodedSwiftServerMessage), - swiftKeypair - ); - let ixs = await makerDriftClient.getPlaceAndMakeSwiftPerpOrderIxs( - encodedSwiftServerMessage, - swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, - swiftServerMessage.uuid, + uuid, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), @@ -374,37 +349,24 @@ describe('place and make swift order', () => { immediateOrCancel: true, }); + const uuid = Uint8Array.from(Buffer.from(nanoid(8))); const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, takeProfitOrderParams: null, subAccountId: 0, + slot: new BN(await connection.getSlot()), + uuid, stopLossOrderParams: null, }; const takerOrderParamsSig = makerDriftClient.signSwiftOrderParamsMessage( takerOrderParamsMessage ); - const swiftServerMessage: SwiftServerMessage = { - slot: new BN(await connection.getSlot()), - swiftOrderSignature: takerOrderParamsSig, - uuid: Uint8Array.from(Buffer.from(nanoid(8))), - }; - - const encodedSwiftServerMessage = - makerDriftClient.encodeSwiftServerMessage(swiftServerMessage); - - const swiftSignature = makerDriftClient.signMessage( - digest(encodedSwiftServerMessage), - swiftKeypair - ); - try { let ixs = await makerDriftClient.getPlaceAndMakeSwiftPerpOrderIxs( - encodedSwiftServerMessage, - swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, - swiftServerMessage.uuid, + uuid, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), @@ -428,122 +390,6 @@ describe('place and make swift order', () => { } }); - it('should fail on swift impersonator', async () => { - const keypair = new Keypair(); - await provider.connection.requestAirdrop(keypair.publicKey, 10 ** 9); - await sleep(1000); - const wallet = new Wallet(keypair); - const userUSDCAccount = await mockUserUSDCAccount( - usdcMint, - usdcAmount, - provider, - keypair.publicKey - ); - const takerDriftClient = new TestClient({ - connection, - wallet, - programID: chProgram.programId, - opts: { - commitment: 'confirmed', - }, - activeSubAccountId: 0, - perpMarketIndexes: marketIndexes, - spotMarketIndexes: spotMarketIndexes, - oracleInfos, - userStats: true, - accountSubscription: { - type: 'polling', - accountLoader: bulkAccountLoader, - }, - }); - await takerDriftClient.subscribe(); - await takerDriftClient.initializeUserAccountAndDepositCollateral( - usdcAmount, - userUSDCAccount.publicKey - ); - const takerDriftClientUser = new User({ - driftClient: takerDriftClient, - userAccountPublicKey: await takerDriftClient.getUserAccountPublicKey(), - accountSubscription: { - type: 'polling', - accountLoader: bulkAccountLoader, - }, - }); - await takerDriftClientUser.subscribe(); - await takerDriftClient.initializeSwiftUserOrders( - takerDriftClientUser.userAccountPublicKey, - 32 - ); - - const marketIndex = 0; - const baseAssetAmount = BASE_PRECISION; - const takerOrderParams = getLimitOrderParams({ - marketIndex, - direction: PositionDirection.LONG, - baseAssetAmount, - price: new BN(34).mul(PRICE_PRECISION), - auctionStartPrice: new BN(33).mul(PRICE_PRECISION), - auctionEndPrice: new BN(34).mul(PRICE_PRECISION), - auctionDuration: 10, - userOrderId: 1, - postOnly: PostOnlyParams.NONE, - }); - - await takerDriftClientUser.fetchAccounts(); - - // Auth part begins - const takerOrderParamsMessage: SwiftOrderParamsMessage = { - swiftOrderParams: takerOrderParams, - subAccountId: 0, - takeProfitOrderParams: null, - stopLossOrderParams: null, - }; - const takerOrderParamsSig = takerDriftClient.signSwiftOrderParamsMessage( - takerOrderParamsMessage - ); - - const swiftServerMessage: SwiftServerMessage = { - slot: new BN(await connection.getSlot()), - swiftOrderSignature: takerOrderParamsSig, - uuid: Uint8Array.from(Buffer.from(nanoid(8))), - }; - - const encodedSwiftServerMessage = - takerDriftClient.encodeSwiftServerMessage(swiftServerMessage); - - const swiftSignature = takerDriftClient.signMessage( - digest(encodedSwiftServerMessage) - ); - - try { - let ixs = await makerDriftClient.getPlaceSwiftTakerPerpOrderIxs( - encodedSwiftServerMessage, - swiftSignature, - takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), - takerOrderParamsSig, - marketIndex, - { - taker: await takerDriftClient.getUserAccountPublicKey(), - takerUserAccount: takerDriftClient.getUserAccount(), - takerStats: takerDriftClient.getUserStatsAccountPublicKey(), - } - ); - ixs = [ - ComputeBudgetProgram.setComputeUnitLimit({ - units: 10_000_000, - }), - ...ixs, - ]; - await makerDriftClient.sendTransaction(new Transaction().add(...ixs)); - assert.fail('Should have failed'); - } catch (error) { - assert.equal( - error.transactionMessage, - 'Transaction precompile verification failure InvalidAccountIndex' - ); - } - }); - it('should fail if diff signed message to verify ixs vs drift ixs', async () => { const keypair = new Keypair(); await provider.connection.requestAirdrop(keypair.publicKey, 10 ** 9); @@ -571,7 +417,6 @@ describe('place and make swift order', () => { type: 'polling', accountLoader: bulkAccountLoader, }, - swiftID: new PublicKey(ANCHOR_TEST_SWIFT_ID), }); await takerDriftClient.subscribe(); @@ -611,6 +456,8 @@ describe('place and make swift order', () => { const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, subAccountId: 0, + uuid: Uint8Array.from(Buffer.from(nanoid(8))), + slot: new BN(await connection.getSlot()), takeProfitOrderParams: null, stopLossOrderParams: null, }; @@ -622,20 +469,6 @@ describe('place and make swift order', () => { takerOrderParamsMessage ); - const swiftServerMessage: SwiftServerMessage = { - slot: new BN(await connection.getSlot()), - swiftOrderSignature: takerOrderParamsSig, - uuid: Uint8Array.from(Buffer.from(nanoid(8))), - }; - - const encodedSwiftServerMessage = - makerDriftClient.encodeSwiftServerMessage(swiftServerMessage); - - const swiftSignature = makerDriftClient.signMessage( - digest(encodedSwiftServerMessage), - swiftKeypair - ); - // Auth for non-legit order const takerOrderParamsMessage2: SwiftOrderParamsMessage = { swiftOrderParams: Object.assign({}, takerOrderParams, { @@ -647,33 +480,19 @@ describe('place and make swift order', () => { subAccountId: 0, takeProfitOrderParams: null, stopLossOrderParams: null, + uuid: Uint8Array.from(Buffer.from(nanoid(8))), + slot: new BN(await connection.getSlot()), }; const takerOrderParamsSig2 = takerDriftClient.signSwiftOrderParamsMessage( takerOrderParamsMessage2 ); - const swiftServerMessage2: SwiftServerMessage = { - slot: new BN(await connection.getSlot()), - swiftOrderSignature: takerOrderParamsSig2, - uuid: Uint8Array.from(Buffer.from(nanoid(8))), - }; - - const encodedSwiftServerMessage2 = - makerDriftClient.encodeSwiftServerMessage(swiftServerMessage2); - - const swiftSignature2 = makerDriftClient.signMessage( - digest(encodedSwiftServerMessage2), - swiftKeypair - ); - const computeBudgetIx = ComputeBudgetProgram.setComputeUnitLimit({ units: 10_000_000, }); const ixs = await makerDriftClient.getPlaceSwiftTakerPerpOrderIxs( - encodedSwiftServerMessage, - swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, 0, @@ -685,8 +504,6 @@ describe('place and make swift order', () => { ); const ixsForOrder2 = await makerDriftClient.getPlaceSwiftTakerPerpOrderIxs( - encodedSwiftServerMessage2, - swiftSignature2, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage2), takerOrderParamsSig2, 0, @@ -698,9 +515,7 @@ describe('place and make swift order', () => { ); const badOrderTx = new Transaction(); - badOrderTx.add( - ...[computeBudgetIx, ixs[0], ixsForOrder2[1], ixsForOrder2[2]] - ); + badOrderTx.add(...[computeBudgetIx, ixs[0], ixsForOrder2[1]]); try { await makerDriftClient.sendTransaction(badOrderTx); assert.fail('Should have failed'); @@ -714,9 +529,7 @@ describe('place and make swift order', () => { } const badSwiftTx = new Transaction(); - badSwiftTx.add( - ...[computeBudgetIx, ixsForOrder2[0], ixs[1], ixsForOrder2[2]] - ); + badSwiftTx.add(...[computeBudgetIx, ixsForOrder2[0], ixs[1]]); try { await makerDriftClient.sendTransaction(badSwiftTx); assert.fail('Should have failed'); diff --git a/tests/placeAndMakeSwiftPerpBankrun.ts b/tests/placeAndMakeSwiftPerpBankrun.ts index 88797108a..d94e86519 100644 --- a/tests/placeAndMakeSwiftPerpBankrun.ts +++ b/tests/placeAndMakeSwiftPerpBankrun.ts @@ -33,12 +33,8 @@ import { SwiftOrderParamsMessage, MarketType, getMarketOrderParams, - loadKeypair, - SwiftServerMessage, - ANCHOR_TEST_SWIFT_ID, SwiftOrderRecord, getSwiftUserAccountPublicKey, - digest, PYTH_LAZER_STORAGE_ACCOUNT_KEY, PTYH_LAZER_PROGRAM_ID, OrderType, @@ -80,13 +76,8 @@ const PYTH_STORAGE_ACCOUNT_INFO: AccountInfo = { describe('place and make swift order', () => { const chProgram = anchor.workspace.Drift as Program; - if (!process.env.SWIFT_PRIVATE_KEY) { - throw new Error('SWIFT_PRIVATE_KEY not set'); - } let slot: BN; - const swiftKeypair = loadKeypair(process.env.SWIFT_PRIVATE_KEY); - let makerDriftClient: TestClient; let makerDriftClientUser: User; let eventSubscriber: EventSubscriber; @@ -181,7 +172,6 @@ describe('place and make swift order', () => { type: 'polling', accountLoader: bulkAccountLoader, }, - swiftID: new PublicKey(ANCHOR_TEST_SWIFT_ID), }); await makerDriftClient.initialize(usdcMint.publicKey, true); await makerDriftClient.subscribe(); @@ -250,9 +240,12 @@ describe('place and make swift order', () => { postOnly: PostOnlyParams.NONE, marketType: MarketType.PERP, }); + const uuid = Uint8Array.from(Buffer.from(nanoid(8))); const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, subAccountId: 0, + slot, + uuid, takeProfitOrderParams: null, stopLossOrderParams: null, }; @@ -271,26 +264,10 @@ describe('place and make swift order', () => { takerOrderParamsMessage ); - const swiftServerMessage: SwiftServerMessage = { - slot, - swiftOrderSignature: takerOrderParamsSig, - uuid: Uint8Array.from(Buffer.from(nanoid(8))), - }; - - const encodedSwiftServerMessage = - makerDriftClient.encodeSwiftServerMessage(swiftServerMessage); - - const swiftSignature = makerDriftClient.signMessage( - digest(encodedSwiftServerMessage), - swiftKeypair - ); - const txSig = await makerDriftClient.placeAndMakeSwiftPerpOrder( - encodedSwiftServerMessage, - swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, - swiftServerMessage.uuid, + uuid, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), @@ -317,11 +294,9 @@ describe('place and make swift order', () => { ); await makerDriftClient.placeAndMakeSwiftPerpOrder( - encodedSwiftServerMessage, - swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, - swiftServerMessage.uuid, + uuid, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), @@ -424,9 +399,13 @@ describe('place and make swift order', () => { userOrderId: 1, postOnly: PostOnlyParams.NONE, }); + const uuid = nanoid(8); + const swiftSlot = slot.subn(15); const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, subAccountId: 0, + uuid: Uint8Array.from(Buffer.from(uuid)), + slot: swiftSlot, takeProfitOrderParams: null, stopLossOrderParams: null, }; @@ -434,22 +413,6 @@ describe('place and make swift order', () => { takerOrderParamsMessage ); - const uuid = nanoid(8); - const swiftSlot = slot.subn(15); - const swiftServerMessage: SwiftServerMessage = { - slot: swiftSlot, - swiftOrderSignature: takerOrderParamsSig, - uuid: Uint8Array.from(Buffer.from(uuid)), - }; - - const encodedSwiftServerMessage = - takerDriftClient.encodeSwiftServerMessage(swiftServerMessage); - - const swiftSignature = takerDriftClient.signMessage( - digest(encodedSwiftServerMessage), - swiftKeypair - ); - // Get pyth lazer instruction const pythLazerCrankIxs = makerDriftClient.getPostPythLazerOracleUpdateIxs( [6], @@ -460,8 +423,6 @@ describe('place and make swift order', () => { const placeSwiftTakerOrderIxs = await makerDriftClient.getPlaceSwiftTakerPerpOrderIxs( - encodedSwiftServerMessage, - swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, takerOrderParams.marketIndex, @@ -605,9 +566,12 @@ describe('place and make swift order', () => { marketType: MarketType.PERP, }); + const uuid = Uint8Array.from(Buffer.from(nanoid(8))); const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, subAccountId: 0, + slot, + uuid, stopLossOrderParams: { triggerPrice: stopLossTakerParams.triggerPrice, baseAssetAmount: stopLossTakerParams.baseAssetAmount, @@ -622,45 +586,10 @@ describe('place and make swift order', () => { takerOrderParamsMessage ); - const swiftDriftClient = new TestClient({ - connection: bankrunContextWrapper.connection.toConnection(), - wallet: new Wallet(swiftKeypair), - programID: chProgram.programId, - opts: { - commitment: 'confirmed', - }, - activeSubAccountId: 0, - perpMarketIndexes: marketIndexes, - spotMarketIndexes: spotMarketIndexes, - subAccountIds: [], - oracleInfos, - userStats: true, - accountSubscription: { - type: 'polling', - accountLoader: bulkAccountLoader, - }, - }); - - const swiftServerMessage: SwiftServerMessage = { - slot, - swiftOrderSignature: takerOrderParamsSig, - uuid: Uint8Array.from(Buffer.from(nanoid(8))), - }; - - const encodedSwiftServerMessage = - swiftDriftClient.encodeSwiftServerMessage(swiftServerMessage); - - const swiftSignature = swiftDriftClient.signMessage( - digest(encodedSwiftServerMessage), - swiftKeypair - ); - const ixs = await makerDriftClient.getPlaceAndMakeSwiftPerpOrderIxs( - encodedSwiftServerMessage, - swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, - swiftServerMessage.uuid, + uuid, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), @@ -749,9 +678,12 @@ describe('place and make swift order', () => { immediateOrCancel: true, }); + const uuid = Uint8Array.from(Buffer.from(nanoid(8))); const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, subAccountId: 0, + slot, + uuid, takeProfitOrderParams: null, stopLossOrderParams: null, }; @@ -760,27 +692,11 @@ describe('place and make swift order', () => { takerOrderParamsMessage ); - const swiftServerMessage: SwiftServerMessage = { - slot, - swiftOrderSignature: takerOrderParamsSig, - uuid: Uint8Array.from(Buffer.from(nanoid(8))), - }; - - const encodedSwiftServerMessage = - takerDriftClient.encodeSwiftServerMessage(swiftServerMessage); - - const swiftSignature = takerDriftClient.signMessage( - digest(encodedSwiftServerMessage), - swiftKeypair - ); - try { await makerDriftClient.placeAndMakeSwiftPerpOrder( - encodedSwiftServerMessage, - swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, - swiftServerMessage.uuid, + uuid, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), @@ -829,9 +745,13 @@ describe('place and make swift order', () => { userOrderId: 1, postOnly: PostOnlyParams.NONE, }); + const swiftSlot = slot.subn(5); + const uuid = Uint8Array.from(Buffer.from(nanoid(8))); const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, subAccountId: 0, + slot: swiftSlot, + uuid, takeProfitOrderParams: null, stopLossOrderParams: null, }; @@ -839,23 +759,7 @@ describe('place and make swift order', () => { takerOrderParamsMessage ); - const swiftServerMessage: SwiftServerMessage = { - slot: slot.subn(5), - swiftOrderSignature: takerOrderParamsSig, - uuid: Uint8Array.from(Buffer.from(nanoid(8))), - }; - - const encodedSwiftServerMessage = - takerDriftClient.encodeSwiftServerMessage(swiftServerMessage); - - const swiftSignature = takerDriftClient.signMessage( - digest(encodedSwiftServerMessage), - swiftKeypair - ); - await makerDriftClient.placeSwiftTakerOrder( - encodedSwiftServerMessage, - swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, takerOrderParams.marketIndex, @@ -878,11 +782,9 @@ describe('place and make swift order', () => { immediateOrCancel: true, }); await makerDriftClient.placeAndMakeSwiftPerpOrder( - encodedSwiftServerMessage, - swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, - swiftServerMessage.uuid, + uuid, { taker: await takerDriftClient.getUserAccountPublicKey(), takerUserAccount: takerDriftClient.getUserAccount(), @@ -929,6 +831,8 @@ describe('place and make swift order', () => { const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, subAccountId: 0, + slot, + uuid: Uint8Array.from(Buffer.from(nanoid(8))), takeProfitOrderParams: null, stopLossOrderParams: null, }; @@ -937,24 +841,8 @@ describe('place and make swift order', () => { takerOrderParamsMessage ); - const swiftServerMessage: SwiftServerMessage = { - slot, - swiftOrderSignature: takerOrderParamsSig, - uuid: Uint8Array.from(Buffer.from(nanoid(8))), - }; - - const encodedSwiftServerMessage = - makerDriftClient.encodeSwiftServerMessage(swiftServerMessage); - - const swiftSignature = makerDriftClient.signMessage( - digest(encodedSwiftServerMessage), - swiftKeypair - ); - try { await makerDriftClient.placeSwiftTakerOrder( - encodedSwiftServerMessage, - swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, 0, @@ -1006,6 +894,8 @@ describe('place and make swift order', () => { const takerOrderParamsMessage: SwiftOrderParamsMessage = { swiftOrderParams: takerOrderParams, subAccountId: 0, + slot, + uuid: Uint8Array.from(Buffer.from(nanoid(8))), takeProfitOrderParams: null, stopLossOrderParams: null, }; @@ -1014,23 +904,7 @@ describe('place and make swift order', () => { takerOrderParamsMessage ); - const swiftServerMessage: SwiftServerMessage = { - slot, - swiftOrderSignature: takerOrderParamsSig, - uuid: Uint8Array.from(Buffer.from(nanoid(8))), - }; - - const encodedSwiftServerMessage = - makerDriftClient.encodeSwiftServerMessage(swiftServerMessage); - - const swiftSignature = makerDriftClient.signMessage( - digest(encodedSwiftServerMessage), - swiftKeypair - ); - await makerDriftClient.placeSwiftTakerOrder( - encodedSwiftServerMessage, - swiftSignature, takerDriftClient.encodeSwiftOrderParamsMessage(takerOrderParamsMessage), takerOrderParamsSig, 0, From 2225543f4fe96a8aff84660b76c1490630a71227 Mon Sep 17 00:00:00 2001 From: Nour Alharithi Date: Mon, 16 Dec 2024 14:30:36 -0800 Subject: [PATCH 21/32] add nanoid to dependencies --- sdk/package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/package.json b/sdk/package.json index e514f531e..5e66e8b30 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -50,6 +50,7 @@ "@switchboard-xyz/on-demand": "1.2.42", "@triton-one/yellowstone-grpc": "1.3.0", "anchor-bankrun": "0.3.0", + "nanoid": "3.3.4", "node-cache": "5.1.2", "rpc-websockets": "7.5.1", "solana-bankrun": "0.3.1", From 81d6919c73c1df9c2ebf18c4e4b6f38384bb7c17 Mon Sep 17 00:00:00 2001 From: GitHub Actions <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 16 Dec 2024 22:33:23 +0000 Subject: [PATCH 22/32] sdk: release v2.104.0-beta.26 --- sdk/VERSION | 2 +- sdk/package.json | 2 +- sdk/yarn.lock | 5 +++++ 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/sdk/VERSION b/sdk/VERSION index 55b5d683e..a2b1a4b7c 100644 --- a/sdk/VERSION +++ b/sdk/VERSION @@ -1 +1 @@ -2.104.0-beta.25 \ No newline at end of file +2.104.0-beta.26 \ No newline at end of file diff --git a/sdk/package.json b/sdk/package.json index 5e66e8b30..7fef3843b 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@drift-labs/sdk", - "version": "2.104.0-beta.25", + "version": "2.104.0-beta.26", "main": "lib/node/index.js", "types": "lib/node/index.d.ts", "browser": "./lib/browser/index.js", diff --git a/sdk/yarn.lock b/sdk/yarn.lock index ade2f1336..85fb9e30f 100644 --- a/sdk/yarn.lock +++ b/sdk/yarn.lock @@ -2529,6 +2529,11 @@ ms@^2.0.0, ms@^2.1.3: resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== +nanoid@3.3.4: + version "3.3.4" + resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.3.4.tgz#730b67e3cd09e2deacf03c027c81c9d9dbc5e8ab" + integrity sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw== + natural-compare@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" From 7f272be4a19664d63fc420b226b994a1e631e99d Mon Sep 17 00:00:00 2001 From: wphan Date: Mon, 16 Dec 2024 15:18:02 -0800 Subject: [PATCH 23/32] fix github action emit VERSION --- .github/workflows/main.yml | 1 + sdk/README.md | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index fd1b8d72e..1d6bef8ce 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -238,6 +238,7 @@ jobs: git pull --rebase origin master git push origin HEAD } + echo "version=$PACKAGE_VERSION" >> $GITHUB_OUTPUT - name: Publish to npm run: npm publish --access=public env: diff --git a/sdk/README.md b/sdk/README.md index 0e1c1a34d..3d4f658f2 100644 --- a/sdk/README.md +++ b/sdk/README.md @@ -273,4 +273,3 @@ Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Drift SDK by you, as defined in the Apache-2.0 license, shall be licensed as above, without any additional terms or conditions. - From eb049b94d630aff9d203ac5f63a4d043238c03d3 Mon Sep 17 00:00:00 2001 From: GitHub Actions <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 16 Dec 2024 23:21:00 +0000 Subject: [PATCH 24/32] sdk: release v2.104.0-beta.27 --- sdk/VERSION | 2 +- sdk/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/VERSION b/sdk/VERSION index a2b1a4b7c..ffe48201a 100644 --- a/sdk/VERSION +++ b/sdk/VERSION @@ -1 +1 @@ -2.104.0-beta.26 \ No newline at end of file +2.104.0-beta.27 \ No newline at end of file diff --git a/sdk/package.json b/sdk/package.json index 7fef3843b..210667ce3 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@drift-labs/sdk", - "version": "2.104.0-beta.26", + "version": "2.104.0-beta.27", "main": "lib/node/index.js", "types": "lib/node/index.d.ts", "browser": "./lib/browser/index.js", From 4e9f1034b1a682cc4af0937b11e465c281f63bda Mon Sep 17 00:00:00 2001 From: Nour Alharithi Date: Mon, 16 Dec 2024 17:24:31 -0800 Subject: [PATCH 25/32] swift dlob node bug fix --- sdk/src/dlob/DLOBNode.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/dlob/DLOBNode.ts b/sdk/src/dlob/DLOBNode.ts index bd20d2edd..c8b88993f 100644 --- a/sdk/src/dlob/DLOBNode.ts +++ b/sdk/src/dlob/DLOBNode.ts @@ -139,7 +139,7 @@ export class SwiftOrderNode extends OrderNode { previous?: SwiftOrderNode; constructor(order: Order, userAccount: string) { - super(order, userAccount, true); + super(order, userAccount, false, true); } getSortValue(order: Order): BN { From 8c7b0f4642836280c69d744401a39fae65e82f86 Mon Sep 17 00:00:00 2001 From: GitHub Actions <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 17 Dec 2024 01:27:11 +0000 Subject: [PATCH 26/32] sdk: release v2.104.0-beta.28 --- sdk/VERSION | 2 +- sdk/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/VERSION b/sdk/VERSION index ffe48201a..7180943ab 100644 --- a/sdk/VERSION +++ b/sdk/VERSION @@ -1 +1 @@ -2.104.0-beta.27 \ No newline at end of file +2.104.0-beta.28 \ No newline at end of file diff --git a/sdk/package.json b/sdk/package.json index 210667ce3..ceaddddef 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@drift-labs/sdk", - "version": "2.104.0-beta.27", + "version": "2.104.0-beta.28", "main": "lib/node/index.js", "types": "lib/node/index.d.ts", "browser": "./lib/browser/index.js", From c84b731ca5f0d96e26ee40ba4f70e2e5c37c19f2 Mon Sep 17 00:00:00 2001 From: bigz_Pubkey <83473873+0xbigz@users.noreply.github.com> Date: Tue, 17 Dec 2024 10:16:22 -0500 Subject: [PATCH 27/32] sdk: add-market-constants-index-62 (#1388) --- sdk/src/constants/perpMarkets.ts | 12 ++++++++++++ sdk/src/constants/spotMarkets.ts | 12 ++++++++++++ 2 files changed, 24 insertions(+) diff --git a/sdk/src/constants/perpMarkets.ts b/sdk/src/constants/perpMarkets.ts index cad7b4cfe..a67b938f4 100644 --- a/sdk/src/constants/perpMarkets.ts +++ b/sdk/src/constants/perpMarkets.ts @@ -1076,6 +1076,18 @@ export const MainnetPerpMarkets: PerpMarketConfig[] = [ pythFeedId: '0x91519e3e48571e1232a85a938e714da19fe5ce05107f3eebb8a870b2e8020169', }, + { + fullName: 'PENGU', + category: ['Meme'], + symbol: 'PENGU-PERP', + baseAssetSymbol: 'PENGU', + marketIndex: 62, + oracle: new PublicKey('7vGHChuBJyFMYBqMLXRzBmRxWdSuwEmg8RvRm3RWQsxi'), + launchTs: 1734444000000, + oracleSource: OracleSource.PYTH_PULL, + pythFeedId: + '0xbed3097008b9b5e3c93bec20be79cb43986b85a996475589351a21e67bae9b61', + }, ]; export const PerpMarkets: { [key in DriftEnv]: PerpMarketConfig[] } = { diff --git a/sdk/src/constants/spotMarkets.ts b/sdk/src/constants/spotMarkets.ts index 94232bf4e..30f2ac151 100644 --- a/sdk/src/constants/spotMarkets.ts +++ b/sdk/src/constants/spotMarkets.ts @@ -557,6 +557,18 @@ export const MainnetSpotMarkets: SpotMarketConfig[] = [ pythFeedId: '0x91519e3e48571e1232a85a938e714da19fe5ce05107f3eebb8a870b2e8020169', }, + { + symbol: 'PENGU', + marketIndex: 31, + poolId: 0, + oracle: new PublicKey('7vGHChuBJyFMYBqMLXRzBmRxWdSuwEmg8RvRm3RWQsxi'), + oracleSource: OracleSource.PYTH_PULL, + mint: new PublicKey('2zMMhcVQEXDtdE6vsFS7S7D5oUodfJHE8vd1gnBouauv'), + precision: new BN(10).pow(SIX), + precisionExp: SIX, + pythFeedId: + '0xbed3097008b9b5e3c93bec20be79cb43986b85a996475589351a21e67bae9b61', + }, ]; export const SpotMarkets: { [key in DriftEnv]: SpotMarketConfig[] } = { From c3ad298369989bd64f2cdb132215ada0f2c02eda Mon Sep 17 00:00:00 2001 From: GitHub Actions <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 17 Dec 2024 15:20:30 +0000 Subject: [PATCH 28/32] sdk: release v2.104.0-beta.29 --- sdk/VERSION | 2 +- sdk/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/VERSION b/sdk/VERSION index 7180943ab..208fec2d0 100644 --- a/sdk/VERSION +++ b/sdk/VERSION @@ -1 +1 @@ -2.104.0-beta.28 \ No newline at end of file +2.104.0-beta.29 \ No newline at end of file diff --git a/sdk/package.json b/sdk/package.json index ceaddddef..d37eec079 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@drift-labs/sdk", - "version": "2.104.0-beta.28", + "version": "2.104.0-beta.29", "main": "lib/node/index.js", "types": "lib/node/index.d.ts", "browser": "./lib/browser/index.js", From 765dc09b2433f73ae3ff150951112ee217735138 Mon Sep 17 00:00:00 2001 From: Chester Sim Date: Wed, 18 Dec 2024 01:27:57 +0800 Subject: [PATCH 29/32] refactor(sdk): ensure bulkaccountloader fully unsubscribes --- sdk/src/accounts/pollingDriftClientAccountSubscriber.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/src/accounts/pollingDriftClientAccountSubscriber.ts b/sdk/src/accounts/pollingDriftClientAccountSubscriber.ts index 18da8df65..86de3ad65 100644 --- a/sdk/src/accounts/pollingDriftClientAccountSubscriber.ts +++ b/sdk/src/accounts/pollingDriftClientAccountSubscriber.ts @@ -402,6 +402,7 @@ export class PollingDriftClientAccountSubscriber this.accountsToPoll.clear(); this.oraclesToPoll.clear(); this.isSubscribed = false; + this.accountLoader.accountsToLoad = new Map(); } async addSpotMarket(marketIndex: number): Promise { From 6186929c6f082f20aede9da9b959d9d47f98e8d4 Mon Sep 17 00:00:00 2001 From: GitHub Actions <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 17 Dec 2024 17:30:55 +0000 Subject: [PATCH 30/32] sdk: release v2.104.0-beta.30 --- sdk/VERSION | 2 +- sdk/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/VERSION b/sdk/VERSION index 208fec2d0..a9ee2b244 100644 --- a/sdk/VERSION +++ b/sdk/VERSION @@ -1 +1 @@ -2.104.0-beta.29 \ No newline at end of file +2.104.0-beta.30 \ No newline at end of file diff --git a/sdk/package.json b/sdk/package.json index d37eec079..a0c1940f7 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@drift-labs/sdk", - "version": "2.104.0-beta.29", + "version": "2.104.0-beta.30", "main": "lib/node/index.js", "types": "lib/node/index.d.ts", "browser": "./lib/browser/index.js", From 93f3a8d4e19b2c953ae8466b5cc52d757a3522b2 Mon Sep 17 00:00:00 2001 From: Chris Heaney Date: Tue, 17 Dec 2024 18:47:44 -0500 Subject: [PATCH 31/32] program: mv handle begin/end swap above contexts --- programs/drift/src/instructions/user.rs | 1264 +++++++++++------------ 1 file changed, 632 insertions(+), 632 deletions(-) diff --git a/programs/drift/src/instructions/user.rs b/programs/drift/src/instructions/user.rs index 8eca9b8eb..f2ef24ad9 100644 --- a/programs/drift/src/instructions/user.rs +++ b/programs/drift/src/instructions/user.rs @@ -2472,539 +2472,6 @@ pub fn handle_enable_user_high_leverage_mode<'c: 'info, 'info>( Ok(()) } -#[derive(Accounts)] -#[instruction( - sub_account_id: u16, -)] -pub struct InitializeUser<'info> { - #[account( - init, - seeds = [b"user", authority.key.as_ref(), sub_account_id.to_le_bytes().as_ref()], - space = User::SIZE, - bump, - payer = payer - )] - pub user: AccountLoader<'info, User>, - #[account( - mut, - has_one = authority - )] - pub user_stats: AccountLoader<'info, UserStats>, - #[account(mut)] - pub state: Box>, - pub authority: Signer<'info>, - #[account(mut)] - pub payer: Signer<'info>, - pub rent: Sysvar<'info, Rent>, - pub system_program: Program<'info, System>, -} - -#[derive(Accounts)] -pub struct InitializeUserStats<'info> { - #[account( - init, - seeds = [b"user_stats", authority.key.as_ref()], - space = UserStats::SIZE, - bump, - payer = payer - )] - pub user_stats: AccountLoader<'info, UserStats>, - #[account(mut)] - pub state: Box>, - pub authority: Signer<'info>, - #[account(mut)] - pub payer: Signer<'info>, - pub rent: Sysvar<'info, Rent>, - pub system_program: Program<'info, System>, -} - -#[derive(Accounts)] -pub struct InitializeRFQUser<'info> { - #[account( - init, - seeds = [RFQ_PDA_SEED.as_ref(), user.key().as_ref()], - space = RFQUser::SIZE, - bump, - payer = payer - )] - pub rfq_user: AccountLoader<'info, RFQUser>, - pub authority: Signer<'info>, - #[account( - mut, - constraint = can_sign_for_user(&user, &authority)? - )] - pub user: AccountLoader<'info, User>, - #[account(mut)] - pub payer: Signer<'info>, - pub rent: Sysvar<'info, Rent>, - pub system_program: Program<'info, System>, -} - -#[derive(Accounts)] -#[instruction(num_orders: u16)] -pub struct InitializeSwiftUserOrders<'info> { - #[account( - init, - seeds = [SWIFT_PDA_SEED.as_ref(), user.key().as_ref()], - space = SwiftUserOrders::space(num_orders as usize), - bump, - payer = payer - )] - pub swift_user_orders: Box>, - pub authority: Signer<'info>, - #[account( - constraint = can_sign_for_user(&user, &authority)? - )] - pub user: AccountLoader<'info, User>, - #[account(mut)] - pub payer: Signer<'info>, - pub rent: Sysvar<'info, Rent>, - pub system_program: Program<'info, System>, -} - -#[derive(Accounts)] -#[instruction(num_orders: u16)] -pub struct ResizeSwiftUserOrders<'info> { - #[account( - mut, - seeds = [SWIFT_PDA_SEED.as_ref(), user.key().as_ref()], - bump, - realloc = SwiftUserOrders::space(num_orders as usize), - realloc::payer = authority, - realloc::zero = false, - )] - pub swift_user_orders: Box>, - #[account(mut)] - pub authority: Signer<'info>, - #[account( - constraint = can_sign_for_user(&user, &authority)? - )] - pub user: AccountLoader<'info, User>, - pub system_program: Program<'info, System>, -} - -#[derive(Accounts)] -#[instruction( - name: [u8; 32], -)] -pub struct InitializeReferrerName<'info> { - #[account( - init, - seeds = [b"referrer_name", name.as_ref()], - space = ReferrerName::SIZE, - bump, - payer = payer - )] - pub referrer_name: AccountLoader<'info, ReferrerName>, - #[account( - mut, - constraint = can_sign_for_user(&user, &authority)? - )] - pub user: AccountLoader<'info, User>, - #[account( - mut, - constraint = is_stats_for_user(&user, &user_stats)? - )] - pub user_stats: AccountLoader<'info, UserStats>, - pub authority: Signer<'info>, - #[account(mut)] - pub payer: Signer<'info>, - pub rent: Sysvar<'info, Rent>, - pub system_program: Program<'info, System>, -} - -#[derive(Accounts)] -#[instruction(market_index: u16,)] -pub struct Deposit<'info> { - pub state: Box>, - #[account( - mut, - constraint = can_sign_for_user(&user, &authority)? - )] - pub user: AccountLoader<'info, User>, - #[account( - mut, - constraint = is_stats_for_user(&user, &user_stats)? - )] - pub user_stats: AccountLoader<'info, UserStats>, - pub authority: Signer<'info>, - #[account( - mut, - seeds = [b"spot_market_vault".as_ref(), market_index.to_le_bytes().as_ref()], - bump, - )] - pub spot_market_vault: Box>, - #[account( - mut, - constraint = &spot_market_vault.mint.eq(&user_token_account.mint), - token::authority = authority - )] - pub user_token_account: Box>, - pub token_program: Interface<'info, TokenInterface>, -} - -#[derive(Accounts)] -pub struct RevenuePoolDeposit<'info> { - pub state: Box>, - #[account(mut)] - pub spot_market: AccountLoader<'info, SpotMarket>, - #[account(mut)] - pub authority: Signer<'info>, - #[account( - mut, - seeds = [b"spot_market_vault".as_ref(), spot_market.load()?.market_index.to_le_bytes().as_ref()], - bump, - )] - pub spot_market_vault: Box>, - #[account( - mut, - constraint = &spot_market_vault.mint.eq(&user_token_account.mint), - token::authority = authority - )] - pub user_token_account: Box>, - pub token_program: Interface<'info, TokenInterface>, -} - -#[derive(Accounts)] -#[instruction(market_index: u16,)] -pub struct Withdraw<'info> { - pub state: Box>, - #[account( - mut, - has_one = authority, - )] - pub user: AccountLoader<'info, User>, - #[account( - mut, - has_one = authority - )] - pub user_stats: AccountLoader<'info, UserStats>, - pub authority: Signer<'info>, - #[account( - mut, - seeds = [b"spot_market_vault".as_ref(), market_index.to_le_bytes().as_ref()], - bump, - )] - pub spot_market_vault: Box>, - #[account( - constraint = state.signer.eq(&drift_signer.key()) - )] - /// CHECK: forced drift_signer - pub drift_signer: AccountInfo<'info>, - #[account( - mut, - constraint = &spot_market_vault.mint.eq(&user_token_account.mint) - )] - pub user_token_account: Box>, - pub token_program: Interface<'info, TokenInterface>, -} - -#[derive(Accounts)] -#[instruction(market_index: u16,)] -pub struct TransferDeposit<'info> { - #[account( - mut, - has_one = authority, - )] - pub from_user: AccountLoader<'info, User>, - #[account( - mut, - has_one = authority, - )] - pub to_user: AccountLoader<'info, User>, - #[account( - mut, - has_one = authority - )] - pub user_stats: AccountLoader<'info, UserStats>, - pub authority: Signer<'info>, - pub state: Box>, - #[account( - seeds = [b"spot_market_vault".as_ref(), market_index.to_le_bytes().as_ref()], - bump, - )] - pub spot_market_vault: Box>, -} - -#[derive(Accounts)] -pub struct PlaceOrder<'info> { - pub state: Box>, - #[account( - mut, - constraint = can_sign_for_user(&user, &authority)? - )] - pub user: AccountLoader<'info, User>, - pub authority: Signer<'info>, -} - -#[derive(Accounts)] -pub struct CancelOrder<'info> { - pub state: Box>, - #[account( - mut, - constraint = can_sign_for_user(&user, &authority)? - )] - pub user: AccountLoader<'info, User>, - pub authority: Signer<'info>, -} - -#[derive(Accounts)] -pub struct PlaceAndTake<'info> { - pub state: Box>, - #[account( - mut, - constraint = can_sign_for_user(&user, &authority)? - )] - pub user: AccountLoader<'info, User>, - #[account( - mut, - constraint = is_stats_for_user(&user, &user_stats)? - )] - pub user_stats: AccountLoader<'info, UserStats>, - pub authority: Signer<'info>, -} - -#[derive(Accounts)] -pub struct PlaceAndMake<'info> { - pub state: Box>, - #[account( - mut, - constraint = can_sign_for_user(&user, &authority)? - )] - pub user: AccountLoader<'info, User>, - #[account( - mut, - constraint = is_stats_for_user(&user, &user_stats)? - )] - pub user_stats: AccountLoader<'info, UserStats>, - #[account(mut)] - pub taker: AccountLoader<'info, User>, - #[account( - mut, - constraint = is_stats_for_user(&taker, &taker_stats)? - )] - pub taker_stats: AccountLoader<'info, UserStats>, - pub authority: Signer<'info>, -} - -#[derive(Accounts)] -pub struct PlaceAndMakeSwift<'info> { - pub state: Box>, - #[account( - mut, - constraint = can_sign_for_user(&user, &authority)? - )] - pub user: AccountLoader<'info, User>, - #[account( - mut, - constraint = is_stats_for_user(&user, &user_stats)? - )] - pub user_stats: AccountLoader<'info, UserStats>, - #[account(mut)] - pub taker: AccountLoader<'info, User>, - #[account( - mut, - constraint = is_stats_for_user(&taker, &taker_stats)? - )] - pub taker_stats: AccountLoader<'info, UserStats>, - #[account( - seeds = [SWIFT_PDA_SEED.as_ref(), taker.key().as_ref()], - bump, - )] - /// CHECK: checked in SwiftUserOrdersZeroCopy checks - pub taker_swift_user_orders: AccountInfo<'info>, - pub authority: Signer<'info>, -} - -#[derive(Accounts)] -pub struct PlaceAndMatchRFQOrders<'info> { - pub state: Box>, - #[account(mut)] - pub user: AccountLoader<'info, User>, - #[account( - mut, - constraint = is_stats_for_user(&user, &user_stats)? - )] - pub user_stats: AccountLoader<'info, UserStats>, - pub authority: Signer<'info>, - /// CHECK: The address check is needed because otherwise - /// the supplied Sysvar could be anything else. - /// The Instruction Sysvar has not been implemented - /// in the Anchor framework yet, so this is the safe approach. - #[account(address = IX_ID)] - pub ix_sysvar: AccountInfo<'info>, -} - -#[derive(Accounts)] -pub struct AddRemoveLiquidity<'info> { - pub state: Box>, - #[account( - mut, - constraint = can_sign_for_user(&user, &authority)?, - )] - pub user: AccountLoader<'info, User>, - pub authority: Signer<'info>, -} - -#[derive(Accounts)] -pub struct RemoveLiquidityInExpiredMarket<'info> { - pub state: Box>, - #[account(mut)] - pub user: AccountLoader<'info, User>, -} - -#[derive(Accounts)] -#[instruction( - sub_account_id: u16, -)] -pub struct UpdateUser<'info> { - #[account( - mut, - seeds = [b"user", authority.key.as_ref(), sub_account_id.to_le_bytes().as_ref()], - bump, - )] - pub user: AccountLoader<'info, User>, - pub authority: Signer<'info>, -} - -#[derive(Accounts)] -pub struct DeleteUser<'info> { - #[account( - mut, - has_one = authority, - close = authority - )] - pub user: AccountLoader<'info, User>, - #[account( - mut, - has_one = authority - )] - pub user_stats: AccountLoader<'info, UserStats>, - #[account(mut)] - pub state: Box>, - pub authority: Signer<'info>, -} - -#[derive(Accounts)] -pub struct DeleteSwiftUserOrders<'info> { - #[account( - mut, - has_one = authority, - )] - pub user: AccountLoader<'info, User>, - #[account( - mut, - close = user, - seeds = [SWIFT_PDA_SEED.as_ref(), user.key().as_ref()], - bump, - )] - pub swift_user_orders: Box>, - #[account(mut)] - pub state: Box>, - pub authority: Signer<'info>, -} - -#[derive(Accounts)] -pub struct ReclaimRent<'info> { - #[account( - mut, - has_one = authority, - )] - pub user: AccountLoader<'info, User>, - #[account( - mut, - has_one = authority - )] - pub user_stats: AccountLoader<'info, UserStats>, - pub state: Box>, - pub authority: Signer<'info>, - pub rent: Sysvar<'info, Rent>, -} - -#[derive(Accounts)] -#[instruction(in_market_index: u16, out_market_index: u16, )] -pub struct Swap<'info> { - pub state: Box>, - #[account( - mut, - constraint = can_sign_for_user(&user, &authority)? - )] - pub user: AccountLoader<'info, User>, - #[account( - mut, - constraint = is_stats_for_user(&user, &user_stats)? - )] - pub user_stats: AccountLoader<'info, UserStats>, - pub authority: Signer<'info>, - #[account( - mut, - seeds = [b"spot_market_vault".as_ref(), out_market_index.to_le_bytes().as_ref()], - bump, - )] - pub out_spot_market_vault: Box>, - #[account( - mut, - seeds = [b"spot_market_vault".as_ref(), in_market_index.to_le_bytes().as_ref()], - bump, - )] - pub in_spot_market_vault: Box>, - #[account( - mut, - constraint = &out_spot_market_vault.mint.eq(&out_token_account.mint), - token::authority = authority - )] - pub out_token_account: Box>, - #[account( - mut, - constraint = &in_spot_market_vault.mint.eq(&in_token_account.mint), - token::authority = authority - )] - pub in_token_account: Box>, - pub token_program: Interface<'info, TokenInterface>, - #[account( - constraint = state.signer.eq(&drift_signer.key()) - )] - /// CHECK: forced drift_signer - pub drift_signer: AccountInfo<'info>, - /// Instructions Sysvar for instruction introspection - /// CHECK: fixed instructions sysvar account - #[account(address = instructions::ID)] - pub instructions: UncheckedAccount<'info>, -} - -#[derive(Accounts)] -#[instruction( - sub_account_id: u16, -)] -pub struct EnableUserHighLeverageMode<'info> { - pub state: Box>, - #[account( - mut, - constraint = can_sign_for_user(&user, &authority)? - )] - pub user: AccountLoader<'info, User>, - pub authority: Signer<'info>, - #[account(mut)] - pub high_leverage_mode_config: AccountLoader<'info, HighLeverageModeConfig>, -} - -#[derive(Accounts)] -#[instruction( - sub_account_id: u16, -)] -pub struct UpdateUserProtectedMakerMode<'info> { - pub state: Box>, - #[account( - mut, - seeds = [b"user", authority.key.as_ref(), sub_account_id.to_le_bytes().as_ref()], - bump, - )] - pub user: AccountLoader<'info, User>, - pub authority: Signer<'info>, - #[account(mut)] - pub protected_maker_mode_config: AccountLoader<'info, ProtectedMakerModeConfig>, -} - #[access_control( fill_not_paused(&ctx.accounts.state) )] @@ -3527,121 +2994,654 @@ pub fn handle_end_swap<'c: 'info, 'info>( let out_position_is_reduced = out_token_amount_before < 0 && out_token_amount_before.unsigned_abs() >= amount_out_after_fee.cast()?; - if !out_position_is_reduced { - validate!( - !out_spot_market.is_reduce_only(), - ErrorCode::SpotMarketReduceOnly, - "out spot market is reduce only but token amount before ({}) < amount out ({})", - out_token_amount_before, - amount_out - )?; + if !out_position_is_reduced { + validate!( + !out_spot_market.is_reduce_only(), + ErrorCode::SpotMarketReduceOnly, + "out spot market is reduce only but token amount before ({}) < amount out ({})", + out_token_amount_before, + amount_out + )?; + + validate!( + reduce_only != Some(SwapReduceOnly::Out), + ErrorCode::InvalidSwap, + "reduce only violated. Out position before ({}) < amount out ({})", + out_token_amount_before, + amount_out + )?; + + validate!( + !user.is_reduce_only(), + ErrorCode::UserReduceOnly, + "swap lead to increase in deposit for in market {}, can only pay off borrow", + out_market_index + )?; + } + + math::spot_withdraw::validate_spot_market_vault_amount(&out_spot_market, out_vault.amount)?; + + out_spot_market.flash_loan_initial_token_amount = 0; + out_spot_market.flash_loan_amount = 0; + + out_spot_market.validate_max_token_deposits_and_borrows(false)?; + + let in_strict_price = StrictOraclePrice::new( + in_oracle_price, + in_spot_market + .historical_oracle_data + .last_oracle_price_twap_5min, + true, + ); + + let out_strict_price = StrictOraclePrice::new( + out_oracle_price, + out_spot_market + .historical_oracle_data + .last_oracle_price_twap_5min, + true, + ); + + let margin_type = spot_swap::select_margin_type_for_swap( + &in_spot_market, + &out_spot_market, + &in_strict_price, + &out_strict_price, + in_token_amount_before, + out_token_amount_before, + in_token_amount_after, + out_token_amount_after, + MarginRequirementType::Initial, + )?; + + drop(out_spot_market); + drop(in_spot_market); + + meets_withdraw_margin_requirement( + &user, + &perp_market_map, + &spot_market_map, + &mut oracle_map, + margin_type, + )?; + + user.update_last_active_slot(slot); + + let swap_record = SwapRecord { + ts: now, + amount_in, + amount_out, + out_market_index, + in_market_index, + in_oracle_price, + out_oracle_price, + user: user_key, + fee, + }; + emit!(swap_record); + + let out_spot_market = spot_market_map.get_ref_mut(&out_market_index)?; + + validate!( + out_spot_market.flash_loan_initial_token_amount == 0 + && out_spot_market.flash_loan_amount == 0, + ErrorCode::InvalidSwap, + "end_swap ended in invalid state" + )?; + + let in_spot_market = spot_market_map.get_ref_mut(&in_market_index)?; + + validate!( + in_spot_market.flash_loan_initial_token_amount == 0 + && in_spot_market.flash_loan_amount == 0, + ErrorCode::InvalidSwap, + "end_swap ended in invalid state" + )?; + + validate_price_bands_for_swap( + &in_spot_market, + &out_spot_market, + amount_in, + amount_out, + in_oracle_price, + out_oracle_price, + state + .oracle_guard_rails + .max_oracle_twap_5min_percent_divergence(), + )?; + + Ok(()) +} + +#[derive(Accounts)] +#[instruction( + sub_account_id: u16, +)] +pub struct InitializeUser<'info> { + #[account( + init, + seeds = [b"user", authority.key.as_ref(), sub_account_id.to_le_bytes().as_ref()], + space = User::SIZE, + bump, + payer = payer + )] + pub user: AccountLoader<'info, User>, + #[account( + mut, + has_one = authority + )] + pub user_stats: AccountLoader<'info, UserStats>, + #[account(mut)] + pub state: Box>, + pub authority: Signer<'info>, + #[account(mut)] + pub payer: Signer<'info>, + pub rent: Sysvar<'info, Rent>, + pub system_program: Program<'info, System>, +} + +#[derive(Accounts)] +pub struct InitializeUserStats<'info> { + #[account( + init, + seeds = [b"user_stats", authority.key.as_ref()], + space = UserStats::SIZE, + bump, + payer = payer + )] + pub user_stats: AccountLoader<'info, UserStats>, + #[account(mut)] + pub state: Box>, + pub authority: Signer<'info>, + #[account(mut)] + pub payer: Signer<'info>, + pub rent: Sysvar<'info, Rent>, + pub system_program: Program<'info, System>, +} + +#[derive(Accounts)] +pub struct InitializeRFQUser<'info> { + #[account( + init, + seeds = [RFQ_PDA_SEED.as_ref(), user.key().as_ref()], + space = RFQUser::SIZE, + bump, + payer = payer + )] + pub rfq_user: AccountLoader<'info, RFQUser>, + pub authority: Signer<'info>, + #[account( + mut, + constraint = can_sign_for_user(&user, &authority)? + )] + pub user: AccountLoader<'info, User>, + #[account(mut)] + pub payer: Signer<'info>, + pub rent: Sysvar<'info, Rent>, + pub system_program: Program<'info, System>, +} + +#[derive(Accounts)] +#[instruction(num_orders: u16)] +pub struct InitializeSwiftUserOrders<'info> { + #[account( + init, + seeds = [SWIFT_PDA_SEED.as_ref(), user.key().as_ref()], + space = SwiftUserOrders::space(num_orders as usize), + bump, + payer = payer + )] + pub swift_user_orders: Box>, + pub authority: Signer<'info>, + #[account( + constraint = can_sign_for_user(&user, &authority)? + )] + pub user: AccountLoader<'info, User>, + #[account(mut)] + pub payer: Signer<'info>, + pub rent: Sysvar<'info, Rent>, + pub system_program: Program<'info, System>, +} + +#[derive(Accounts)] +#[instruction(num_orders: u16)] +pub struct ResizeSwiftUserOrders<'info> { + #[account( + mut, + seeds = [SWIFT_PDA_SEED.as_ref(), user.key().as_ref()], + bump, + realloc = SwiftUserOrders::space(num_orders as usize), + realloc::payer = authority, + realloc::zero = false, + )] + pub swift_user_orders: Box>, + #[account(mut)] + pub authority: Signer<'info>, + #[account( + constraint = can_sign_for_user(&user, &authority)? + )] + pub user: AccountLoader<'info, User>, + pub system_program: Program<'info, System>, +} + +#[derive(Accounts)] +#[instruction( + name: [u8; 32], +)] +pub struct InitializeReferrerName<'info> { + #[account( + init, + seeds = [b"referrer_name", name.as_ref()], + space = ReferrerName::SIZE, + bump, + payer = payer + )] + pub referrer_name: AccountLoader<'info, ReferrerName>, + #[account( + mut, + constraint = can_sign_for_user(&user, &authority)? + )] + pub user: AccountLoader<'info, User>, + #[account( + mut, + constraint = is_stats_for_user(&user, &user_stats)? + )] + pub user_stats: AccountLoader<'info, UserStats>, + pub authority: Signer<'info>, + #[account(mut)] + pub payer: Signer<'info>, + pub rent: Sysvar<'info, Rent>, + pub system_program: Program<'info, System>, +} - validate!( - reduce_only != Some(SwapReduceOnly::Out), - ErrorCode::InvalidSwap, - "reduce only violated. Out position before ({}) < amount out ({})", - out_token_amount_before, - amount_out - )?; +#[derive(Accounts)] +#[instruction(market_index: u16,)] +pub struct Deposit<'info> { + pub state: Box>, + #[account( + mut, + constraint = can_sign_for_user(&user, &authority)? + )] + pub user: AccountLoader<'info, User>, + #[account( + mut, + constraint = is_stats_for_user(&user, &user_stats)? + )] + pub user_stats: AccountLoader<'info, UserStats>, + pub authority: Signer<'info>, + #[account( + mut, + seeds = [b"spot_market_vault".as_ref(), market_index.to_le_bytes().as_ref()], + bump, + )] + pub spot_market_vault: Box>, + #[account( + mut, + constraint = &spot_market_vault.mint.eq(&user_token_account.mint), + token::authority = authority + )] + pub user_token_account: Box>, + pub token_program: Interface<'info, TokenInterface>, +} - validate!( - !user.is_reduce_only(), - ErrorCode::UserReduceOnly, - "swap lead to increase in deposit for in market {}, can only pay off borrow", - out_market_index - )?; - } +#[derive(Accounts)] +pub struct RevenuePoolDeposit<'info> { + pub state: Box>, + #[account(mut)] + pub spot_market: AccountLoader<'info, SpotMarket>, + #[account(mut)] + pub authority: Signer<'info>, + #[account( + mut, + seeds = [b"spot_market_vault".as_ref(), spot_market.load()?.market_index.to_le_bytes().as_ref()], + bump, + )] + pub spot_market_vault: Box>, + #[account( + mut, + constraint = &spot_market_vault.mint.eq(&user_token_account.mint), + token::authority = authority + )] + pub user_token_account: Box>, + pub token_program: Interface<'info, TokenInterface>, +} - math::spot_withdraw::validate_spot_market_vault_amount(&out_spot_market, out_vault.amount)?; +#[derive(Accounts)] +#[instruction(market_index: u16,)] +pub struct Withdraw<'info> { + pub state: Box>, + #[account( + mut, + has_one = authority, + )] + pub user: AccountLoader<'info, User>, + #[account( + mut, + has_one = authority + )] + pub user_stats: AccountLoader<'info, UserStats>, + pub authority: Signer<'info>, + #[account( + mut, + seeds = [b"spot_market_vault".as_ref(), market_index.to_le_bytes().as_ref()], + bump, + )] + pub spot_market_vault: Box>, + #[account( + constraint = state.signer.eq(&drift_signer.key()) + )] + /// CHECK: forced drift_signer + pub drift_signer: AccountInfo<'info>, + #[account( + mut, + constraint = &spot_market_vault.mint.eq(&user_token_account.mint) + )] + pub user_token_account: Box>, + pub token_program: Interface<'info, TokenInterface>, +} - out_spot_market.flash_loan_initial_token_amount = 0; - out_spot_market.flash_loan_amount = 0; +#[derive(Accounts)] +#[instruction(market_index: u16,)] +pub struct TransferDeposit<'info> { + #[account( + mut, + has_one = authority, + )] + pub from_user: AccountLoader<'info, User>, + #[account( + mut, + has_one = authority, + )] + pub to_user: AccountLoader<'info, User>, + #[account( + mut, + has_one = authority + )] + pub user_stats: AccountLoader<'info, UserStats>, + pub authority: Signer<'info>, + pub state: Box>, + #[account( + seeds = [b"spot_market_vault".as_ref(), market_index.to_le_bytes().as_ref()], + bump, + )] + pub spot_market_vault: Box>, +} - out_spot_market.validate_max_token_deposits_and_borrows(false)?; +#[derive(Accounts)] +pub struct PlaceOrder<'info> { + pub state: Box>, + #[account( + mut, + constraint = can_sign_for_user(&user, &authority)? + )] + pub user: AccountLoader<'info, User>, + pub authority: Signer<'info>, +} - let in_strict_price = StrictOraclePrice::new( - in_oracle_price, - in_spot_market - .historical_oracle_data - .last_oracle_price_twap_5min, - true, - ); +#[derive(Accounts)] +pub struct CancelOrder<'info> { + pub state: Box>, + #[account( + mut, + constraint = can_sign_for_user(&user, &authority)? + )] + pub user: AccountLoader<'info, User>, + pub authority: Signer<'info>, +} - let out_strict_price = StrictOraclePrice::new( - out_oracle_price, - out_spot_market - .historical_oracle_data - .last_oracle_price_twap_5min, - true, - ); +#[derive(Accounts)] +pub struct PlaceAndTake<'info> { + pub state: Box>, + #[account( + mut, + constraint = can_sign_for_user(&user, &authority)? + )] + pub user: AccountLoader<'info, User>, + #[account( + mut, + constraint = is_stats_for_user(&user, &user_stats)? + )] + pub user_stats: AccountLoader<'info, UserStats>, + pub authority: Signer<'info>, +} - let margin_type = spot_swap::select_margin_type_for_swap( - &in_spot_market, - &out_spot_market, - &in_strict_price, - &out_strict_price, - in_token_amount_before, - out_token_amount_before, - in_token_amount_after, - out_token_amount_after, - MarginRequirementType::Initial, - )?; +#[derive(Accounts)] +pub struct PlaceAndMake<'info> { + pub state: Box>, + #[account( + mut, + constraint = can_sign_for_user(&user, &authority)? + )] + pub user: AccountLoader<'info, User>, + #[account( + mut, + constraint = is_stats_for_user(&user, &user_stats)? + )] + pub user_stats: AccountLoader<'info, UserStats>, + #[account(mut)] + pub taker: AccountLoader<'info, User>, + #[account( + mut, + constraint = is_stats_for_user(&taker, &taker_stats)? + )] + pub taker_stats: AccountLoader<'info, UserStats>, + pub authority: Signer<'info>, +} - drop(out_spot_market); - drop(in_spot_market); +#[derive(Accounts)] +pub struct PlaceAndMakeSwift<'info> { + pub state: Box>, + #[account( + mut, + constraint = can_sign_for_user(&user, &authority)? + )] + pub user: AccountLoader<'info, User>, + #[account( + mut, + constraint = is_stats_for_user(&user, &user_stats)? + )] + pub user_stats: AccountLoader<'info, UserStats>, + #[account(mut)] + pub taker: AccountLoader<'info, User>, + #[account( + mut, + constraint = is_stats_for_user(&taker, &taker_stats)? + )] + pub taker_stats: AccountLoader<'info, UserStats>, + #[account( + seeds = [SWIFT_PDA_SEED.as_ref(), taker.key().as_ref()], + bump, + )] + /// CHECK: checked in SwiftUserOrdersZeroCopy checks + pub taker_swift_user_orders: AccountInfo<'info>, + pub authority: Signer<'info>, +} - meets_withdraw_margin_requirement( - &user, - &perp_market_map, - &spot_market_map, - &mut oracle_map, - margin_type, - )?; +#[derive(Accounts)] +pub struct PlaceAndMatchRFQOrders<'info> { + pub state: Box>, + #[account(mut)] + pub user: AccountLoader<'info, User>, + #[account( + mut, + constraint = is_stats_for_user(&user, &user_stats)? + )] + pub user_stats: AccountLoader<'info, UserStats>, + pub authority: Signer<'info>, + /// CHECK: The address check is needed because otherwise + /// the supplied Sysvar could be anything else. + /// The Instruction Sysvar has not been implemented + /// in the Anchor framework yet, so this is the safe approach. + #[account(address = IX_ID)] + pub ix_sysvar: AccountInfo<'info>, +} - user.update_last_active_slot(slot); +#[derive(Accounts)] +pub struct AddRemoveLiquidity<'info> { + pub state: Box>, + #[account( + mut, + constraint = can_sign_for_user(&user, &authority)?, + )] + pub user: AccountLoader<'info, User>, + pub authority: Signer<'info>, +} - let swap_record = SwapRecord { - ts: now, - amount_in, - amount_out, - out_market_index, - in_market_index, - in_oracle_price, - out_oracle_price, - user: user_key, - fee, - }; - emit!(swap_record); +#[derive(Accounts)] +pub struct RemoveLiquidityInExpiredMarket<'info> { + pub state: Box>, + #[account(mut)] + pub user: AccountLoader<'info, User>, +} - let out_spot_market = spot_market_map.get_ref_mut(&out_market_index)?; +#[derive(Accounts)] +#[instruction( + sub_account_id: u16, +)] +pub struct UpdateUser<'info> { + #[account( + mut, + seeds = [b"user", authority.key.as_ref(), sub_account_id.to_le_bytes().as_ref()], + bump, + )] + pub user: AccountLoader<'info, User>, + pub authority: Signer<'info>, +} - validate!( - out_spot_market.flash_loan_initial_token_amount == 0 - && out_spot_market.flash_loan_amount == 0, - ErrorCode::InvalidSwap, - "end_swap ended in invalid state" - )?; +#[derive(Accounts)] +pub struct DeleteUser<'info> { + #[account( + mut, + has_one = authority, + close = authority + )] + pub user: AccountLoader<'info, User>, + #[account( + mut, + has_one = authority + )] + pub user_stats: AccountLoader<'info, UserStats>, + #[account(mut)] + pub state: Box>, + pub authority: Signer<'info>, +} - let in_spot_market = spot_market_map.get_ref_mut(&in_market_index)?; +#[derive(Accounts)] +pub struct DeleteSwiftUserOrders<'info> { + #[account( + mut, + has_one = authority, + )] + pub user: AccountLoader<'info, User>, + #[account( + mut, + close = user, + seeds = [SWIFT_PDA_SEED.as_ref(), user.key().as_ref()], + bump, + )] + pub swift_user_orders: Box>, + #[account(mut)] + pub state: Box>, + pub authority: Signer<'info>, +} - validate!( - in_spot_market.flash_loan_initial_token_amount == 0 - && in_spot_market.flash_loan_amount == 0, - ErrorCode::InvalidSwap, - "end_swap ended in invalid state" - )?; +#[derive(Accounts)] +pub struct ReclaimRent<'info> { + #[account( + mut, + has_one = authority, + )] + pub user: AccountLoader<'info, User>, + #[account( + mut, + has_one = authority + )] + pub user_stats: AccountLoader<'info, UserStats>, + pub state: Box>, + pub authority: Signer<'info>, + pub rent: Sysvar<'info, Rent>, +} - validate_price_bands_for_swap( - &in_spot_market, - &out_spot_market, - amount_in, - amount_out, - in_oracle_price, - out_oracle_price, - state - .oracle_guard_rails - .max_oracle_twap_5min_percent_divergence(), - )?; +#[derive(Accounts)] +#[instruction(in_market_index: u16, out_market_index: u16, )] +pub struct Swap<'info> { + pub state: Box>, + #[account( + mut, + constraint = can_sign_for_user(&user, &authority)? + )] + pub user: AccountLoader<'info, User>, + #[account( + mut, + constraint = is_stats_for_user(&user, &user_stats)? + )] + pub user_stats: AccountLoader<'info, UserStats>, + pub authority: Signer<'info>, + #[account( + mut, + seeds = [b"spot_market_vault".as_ref(), out_market_index.to_le_bytes().as_ref()], + bump, + )] + pub out_spot_market_vault: Box>, + #[account( + mut, + seeds = [b"spot_market_vault".as_ref(), in_market_index.to_le_bytes().as_ref()], + bump, + )] + pub in_spot_market_vault: Box>, + #[account( + mut, + constraint = &out_spot_market_vault.mint.eq(&out_token_account.mint), + token::authority = authority + )] + pub out_token_account: Box>, + #[account( + mut, + constraint = &in_spot_market_vault.mint.eq(&in_token_account.mint), + token::authority = authority + )] + pub in_token_account: Box>, + pub token_program: Interface<'info, TokenInterface>, + #[account( + constraint = state.signer.eq(&drift_signer.key()) + )] + /// CHECK: forced drift_signer + pub drift_signer: AccountInfo<'info>, + /// Instructions Sysvar for instruction introspection + /// CHECK: fixed instructions sysvar account + #[account(address = instructions::ID)] + pub instructions: UncheckedAccount<'info>, +} - Ok(()) +#[derive(Accounts)] +#[instruction( + sub_account_id: u16, +)] +pub struct EnableUserHighLeverageMode<'info> { + pub state: Box>, + #[account( + mut, + constraint = can_sign_for_user(&user, &authority)? + )] + pub user: AccountLoader<'info, User>, + pub authority: Signer<'info>, + #[account(mut)] + pub high_leverage_mode_config: AccountLoader<'info, HighLeverageModeConfig>, } + +#[derive(Accounts)] +#[instruction( + sub_account_id: u16, +)] +pub struct UpdateUserProtectedMakerMode<'info> { + pub state: Box>, + #[account( + mut, + seeds = [b"user", authority.key.as_ref(), sub_account_id.to_le_bytes().as_ref()], + bump, + )] + pub user: AccountLoader<'info, User>, + pub authority: Signer<'info>, + #[account(mut)] + pub protected_maker_mode_config: AccountLoader<'info, ProtectedMakerModeConfig>, +} \ No newline at end of file From 40eb18768731ec1189a2977cc6b36b34ee639773 Mon Sep 17 00:00:00 2001 From: wphan Date: Tue, 17 Dec 2024 21:10:30 -0800 Subject: [PATCH 32/32] sdk: explicitly specify state admin for certain functions (#1389) * sdk: explicitly specify state admin for certain functions * add useHotWalletAdmin to config --- sdk/src/adminClient.ts | 47 +++++++++++++++++++++--------------- sdk/src/driftClient.ts | 2 ++ sdk/src/driftClientConfig.ts | 1 + 3 files changed, 30 insertions(+), 20 deletions(-) diff --git a/sdk/src/adminClient.ts b/sdk/src/adminClient.ts index 1d665c634..dde5aea08 100644 --- a/sdk/src/adminClient.ts +++ b/sdk/src/adminClient.ts @@ -1063,7 +1063,9 @@ export class AdminClient extends DriftClient { const tokenProgram = this.getTokenProgramForSpotMarket(spotMarket); return await this.program.instruction.depositIntoSpotMarketVault(amount, { accounts: { - admin: this.wallet.publicKey, + admin: this.useHotWalletAdmin + ? this.wallet.publicKey + : this.getStateAccount().admin, state: await this.getStatePublicKey(), sourceVault, spotMarket: spotMarket.pubkey, @@ -1192,7 +1194,9 @@ export class AdminClient extends DriftClient { }, { accounts: { - admin: this.wallet.publicKey, + admin: this.useHotWalletAdmin + ? this.wallet.publicKey + : this.getStateAccount().admin, state: await this.getStatePublicKey(), perpMarket: await getPerpMarketPublicKey( this.program.programId, @@ -3885,7 +3889,9 @@ export class AdminClient extends DriftClient { fuelBonusInsurance || null, { accounts: { - admin: this.wallet.publicKey, + admin: this.useHotWalletAdmin + ? this.wallet.publicKey + : this.getStateAccount().admin, state: await this.getStatePublicKey(), user, userStats, @@ -3895,12 +3901,10 @@ export class AdminClient extends DriftClient { } public async initializePythPullOracle( - feedId: string, - isAdmin = false + feedId: string ): Promise { const initializePythPullOracleIx = await this.getInitializePythPullOracleIx( - feedId, - isAdmin + feedId ); const tx = await this.buildTransaction(initializePythPullOracleIx); const { txSig } = await this.sendTransaction(tx, [], this.opts); @@ -3909,15 +3913,16 @@ export class AdminClient extends DriftClient { } public async getInitializePythPullOracleIx( - feedId: string, - isAdmin = false + feedId: string ): Promise { const feedIdBuffer = getFeedIdUint8Array(feedId); return await this.program.instruction.initializePythPullOracle( feedIdBuffer, { accounts: { - admin: isAdmin ? this.getStateAccount().admin : this.wallet.publicKey, + admin: this.useHotWalletAdmin + ? this.wallet.publicKey + : this.getStateAccount().admin, state: await this.getStatePublicKey(), systemProgram: SystemProgram.programId, priceFeed: getPythPullOraclePublicKey( @@ -3931,11 +3936,10 @@ export class AdminClient extends DriftClient { } public async initializePythLazerOracle( - feedId: number, - isAdmin = false + feedId: number ): Promise { const initializePythPullOracleIx = - await this.getInitializePythLazerOracleIx(feedId, isAdmin); + await this.getInitializePythLazerOracleIx(feedId); const tx = await this.buildTransaction(initializePythPullOracleIx); const { txSig } = await this.sendTransaction(tx, [], this.opts); @@ -3943,12 +3947,13 @@ export class AdminClient extends DriftClient { } public async getInitializePythLazerOracleIx( - feedId: number, - isAdmin = false + feedId: number ): Promise { return await this.program.instruction.initializePythLazerOracle(feedId, { accounts: { - admin: isAdmin ? this.getStateAccount().admin : this.wallet.publicKey, + admin: this.useHotWalletAdmin + ? this.wallet.publicKey + : this.getStateAccount().admin, state: await this.getStatePublicKey(), systemProgram: SystemProgram.programId, lazerOracle: getPythLazerOraclePublicKey( @@ -4030,10 +4035,11 @@ export class AdminClient extends DriftClient { } public async initializeProtectedMakerModeConfig( - maxUsers: number + maxUsers: number, + stateAdmin?: boolean ): Promise { const initializeProtectedMakerModeConfigIx = - await this.getInitializeProtectedMakerModeConfigIx(maxUsers); + await this.getInitializeProtectedMakerModeConfigIx(maxUsers, stateAdmin); const tx = await this.buildTransaction( initializeProtectedMakerModeConfigIx @@ -4045,13 +4051,14 @@ export class AdminClient extends DriftClient { } public async getInitializeProtectedMakerModeConfigIx( - maxUsers: number + maxUsers: number, + stateAdmin?: boolean ): Promise { return await this.program.instruction.initializeProtectedMakerModeConfig( maxUsers, { accounts: { - admin: this.isSubscribed + admin: stateAdmin ? this.getStateAccount().admin : this.wallet.publicKey, state: await this.getStatePublicKey(), diff --git a/sdk/src/driftClient.ts b/sdk/src/driftClient.ts index 75a4b5c11..952404037 100644 --- a/sdk/src/driftClient.ts +++ b/sdk/src/driftClient.ts @@ -202,6 +202,7 @@ export class DriftClient { public program: Program; provider: AnchorProvider; opts?: ConfirmOptions; + useHotWalletAdmin?: boolean; users = new Map(); userStats?: UserStats; activeSubAccountId: number; @@ -251,6 +252,7 @@ export class DriftClient { this.opts = config.opts || { ...DEFAULT_CONFIRMATION_OPTS, }; + this.useHotWalletAdmin = config.useHotWalletAdmin ?? false; if (config?.connection?.commitment) { // At the moment this ensures that our transaction simulations (which use Connection object) will use the same commitment level as our Transaction blockhashes (which use these opts) this.opts.commitment = config.connection.commitment; diff --git a/sdk/src/driftClientConfig.ts b/sdk/src/driftClientConfig.ts index 1b74de6ec..6deaf6bbb 100644 --- a/sdk/src/driftClientConfig.ts +++ b/sdk/src/driftClientConfig.ts @@ -38,6 +38,7 @@ export type DriftClientConfig = { enableMetricsEvents?: boolean; txHandlerConfig?: TxHandlerConfig; delistedMarketSetting?: DelistedMarketSetting; + useHotWalletAdmin?: boolean; }; export type DriftClientSubscriptionConfig =