From 70f1972cd9afcc1a914af03383277b902efc3aad Mon Sep 17 00:00:00 2001 From: jeffyanta Date: Thu, 12 Nov 2026 13:49:29 -0500 Subject: [PATCH] Remove Coinbase Stableswapper v1 swaps --- ocp/rpc/transaction/stateful_swap.go | 8 +- ocp/rpc/transaction/stateless_swap.go | 14 +- ocp/rpc/transaction/swap_handler.go | 32 +- ocp/rpc/transaction/swap_test.go | 405 +++++++++--------- ocp/transaction/coinbase_swap.go | 103 +---- ocp/transaction/coinbase_swap_test.go | 69 ++- solana/coinbasestableswapper/address.go | 9 - .../instructions_swap.go | 139 ------ .../instructions_swap_v2.go | 5 +- .../instructions_swap_v2_test.go | 57 +-- .../types_account_type.go | 3 - .../types_instruction_type.go | 3 - 12 files changed, 300 insertions(+), 547 deletions(-) delete mode 100644 solana/coinbasestableswapper/instructions_swap.go diff --git a/ocp/rpc/transaction/stateful_swap.go b/ocp/rpc/transaction/stateful_swap.go index f2f6005..fcd5f98 100644 --- a/ocp/rpc/transaction/stateful_swap.go +++ b/ocp/rpc/transaction/stateful_swap.go @@ -894,6 +894,10 @@ func (s *transactionServer) handleStablecoinStatefulSwap( return handleStatefulSwapError(streamer, err) } + if initiateStablecoinSwapReq.SwapVersion != requiredCoinbaseSwapVersion { + return handleStatefulSwapError(streamer, NewSwapValidationErrorf("swap version must be %d", requiredCoinbaseSwapVersion)) + } + if !common.IsCoreMint(fromMint) { return handleStatefulSwapError(streamer, NewSwapValidationError("source mint must be the core mint")) } @@ -1035,9 +1039,6 @@ func (s *transactionServer) handleStablecoinStatefulSwap( selectedNonce.ReleaseIfNotReserved(ctx) }() - coinbaseSwapVersion := selectCoinbaseSwapVersion(initiateStablecoinSwapReq.SwapVersion) - log = log.With(zap.String("coinbase_swap_version", coinbaseSwapVersion.String())) - transactionVersion := selectSwapTransactionVersion(initiateReq.TransactionVersion) log = log.With(zap.String("selected_transaction_version", transactionVersion.String())) @@ -1052,7 +1053,6 @@ func (s *transactionServer) handleStablecoinStatefulSwap( initiateStablecoinSwapReq.FeeAmount, selectedNonce, transactionVersion, - coinbaseSwapVersion, ) txn, err := makeStatefulSwapTransaction(ctx, swapHandler) diff --git a/ocp/rpc/transaction/stateless_swap.go b/ocp/rpc/transaction/stateless_swap.go index a07ad89..26e83e6 100644 --- a/ocp/rpc/transaction/stateless_swap.go +++ b/ocp/rpc/transaction/stateless_swap.go @@ -123,6 +123,10 @@ func (s *transactionServer) handleStablecoinStatelessSwap( // Section: Validation // + if initiateStablecoinSwapReq.SwapVersion != requiredCoinbaseSwapVersion { + return handleStatelessSwapError(streamer, NewSwapValidationErrorf("swap version must be %d", requiredCoinbaseSwapVersion)) + } + if fromMint.PublicKey().ToBase58() != usdc.Mint { return handleStatelessSwapError(streamer, NewSwapValidationError("source mint must be usdc")) } @@ -242,11 +246,7 @@ func (s *transactionServer) handleStablecoinStatelessSwap( return handleStatelessSwapError(streamer, err) } - coinbaseSwapVersion := selectCoinbaseSwapVersion(initiateStablecoinSwapReq.SwapVersion) - log = log.With(zap.String("coinbase_swap_version", coinbaseSwapVersion.String())) - - coinbaseSwapIxn, err := transaction_util.MakeCoinbaseSwapInstruction( - coinbaseSwapVersion, + coinbaseSwapIxn := transaction_util.MakeCoinbaseSwapInstruction( coinbaseAccounts, owner.PublicKey().ToBytes(), fromMint.PublicKey().ToBytes(), @@ -256,10 +256,6 @@ func (s *transactionServer) handleStablecoinStatelessSwap( initiateStablecoinSwapReq.SwapAmount, initiateStablecoinSwapReq.SwapAmount, ) - if err != nil { - log.With(zap.Error(err)).Warn("failure building coinbase swap instruction") - return handleStatelessSwapError(streamer, err) - } feeRecipient, err := common.NewAccountFromPublicKeyBytes(coinbaseAccounts.FeeRecipient) if err != nil { diff --git a/ocp/rpc/transaction/swap_handler.go b/ocp/rpc/transaction/swap_handler.go index 95f00bc..1b2178d 100644 --- a/ocp/rpc/transaction/swap_handler.go +++ b/ocp/rpc/transaction/swap_handler.go @@ -1380,18 +1380,13 @@ func (h *ReserveTreasuryFundedCreateAndBuySwapHandler) MakeInstructions(ctx cont return ixns, nil } -// selectCoinbaseSwapVersion picks the CoinbaseStableSwapper swap instruction -// version from the client's requested swap_version. Clients rebuild and sign -// the transaction locally, so the server must match what the client builds. -// Only an explicit 2 selects v2. Older clients leave it unset and build v1. -func selectCoinbaseSwapVersion(requested uint32) transaction_util.CoinbaseSwapVersion { - if requested == 2 { - return transaction_util.CoinbaseSwapV2 - } - return transaction_util.CoinbaseSwapV1 -} - const ( + // The only supported CoinbaseStableSwapper swap instruction version is + // swap_v2. Clients rebuild and sign the transaction locally, so a request + // for any other version, including older clients that leave it unset and + // build the deprecated whitelist swap, is rejected. + requiredCoinbaseSwapVersion = 2 + // Measured on mainnet at 62k CU with an existing destination ATA. Creating // the destination ATA adds about 9k, and the swap authority ATA, destination // ATA and VM swap PDA derivations each cost 1,500 CU per bump below 255, for @@ -1418,9 +1413,8 @@ type CoinbaseStableSwapperSwapHandler struct { computeUnitPrice uint64 memoValue string - feeDestination *common.Account - coinbaseSwapVersion transaction_util.CoinbaseSwapVersion - coinbaseAccounts *transaction_util.CoinbaseSwapAccounts + feeDestination *common.Account + coinbaseAccounts *transaction_util.CoinbaseSwapAccounts } func NewCoinbaseStableSwapperSwapHandler( @@ -1434,7 +1428,6 @@ func NewCoinbaseStableSwapperSwapHandler( feeAmount uint64, selectedNonce *transaction_util.Nonce, transactionVersion solana.MessageVersion, - coinbaseSwapVersion transaction_util.CoinbaseSwapVersion, ) *CoinbaseStableSwapperSwapHandler { return &CoinbaseStableSwapperSwapHandler{ data: data, @@ -1453,8 +1446,7 @@ func NewCoinbaseStableSwapperSwapHandler( computeUnitPrice: coinbaseStatefulSwapComputeUnitPrice, memoValue: swapMemoValue("coinbase_stable_swapper", transactionVersion), - feeDestination: common.CoreMintFeesAccount, - coinbaseSwapVersion: coinbaseSwapVersion, + feeDestination: common.CoreMintFeesAccount, } } @@ -1564,8 +1556,7 @@ func (h *CoinbaseStableSwapperSwapHandler) MakeInstructions(ctx context.Context) }, ) - coinbaseSwapIxn, err := transaction_util.MakeCoinbaseSwapInstruction( - h.coinbaseSwapVersion, + coinbaseSwapIxn := transaction_util.MakeCoinbaseSwapInstruction( coinbaseAccounts, h.swapAuthority.PublicKey().ToBytes(), h.fromMint.PublicKey().ToBytes(), @@ -1575,9 +1566,6 @@ func (h *CoinbaseStableSwapperSwapHandler) MakeInstructions(ctx context.Context) h.swapAmount, h.swapAmount, ) - if err != nil { - return nil, err - } closeSwapAuthorityFromMintAtaIxn := token.CloseAccount( swapAuthorityFromMintAta, diff --git a/ocp/rpc/transaction/swap_test.go b/ocp/rpc/transaction/swap_test.go index 92aa9ca..3075edf 100644 --- a/ocp/rpc/transaction/swap_test.go +++ b/ocp/rpc/transaction/swap_test.go @@ -579,7 +579,7 @@ func (e *testEnv) expectedStatefulSwapTransaction(t *testing.T, req *statefulSwa destinationOwner, err := common.NewAccountFromProto(p.DestinationOwner) require.NoError(t, err) - h = NewCoinbaseStableSwapperSwapHandler(e.data, req.owner, req.swapAuthority, destinationOwner, fromMint, toMint, p.SwapAmount, p.FeeAmount, selectedNonce, transactionVersion, selectCoinbaseSwapVersion(p.SwapVersion)) + h = NewCoinbaseStableSwapperSwapHandler(e.data, req.owner, req.swapAuthority, destinationOwner, fromMint, toMint, p.SwapAmount, p.FeeAmount, selectedNonce, transactionVersion) } else { p := req.reserve fromMint, err := common.NewAccountFromProto(p.FromMint) @@ -741,7 +741,7 @@ func (e *testEnv) stablecoinSwapRequest(t *testing.T, owner *common.Account, swa FundingSource: transactionpb.FundingSource_FUNDING_SOURCE_SUBMIT_INTENT, FundingId: testutil.NewRandomAccount(t).PublicKey().ToBase58(), DestinationOwner: testutil.NewRandomAccount(t).ToProto(), - SwapVersion: uint32(transaction_util.CoinbaseSwapV2), + SwapVersion: requiredCoinbaseSwapVersion, }, } } @@ -1038,7 +1038,7 @@ func (e *testEnv) requireClientRebuildMatchesServer(t *testing.T, req *statefulS require.NoError(t, err) toMint, err := common.NewAccountFromProto(p.ToMint) require.NoError(t, err) - requireCoinbaseStatefulClientRebuildMatches(t, e, *result.expectedTxn, typed.Stablecoin, req.owner, req.swapAuthority, destinationOwner, fromMint, toMint, p.SwapAmount, p.FeeAmount, selectCoinbaseSwapVersion(p.SwapVersion)) + requireCoinbaseStatefulClientRebuildMatches(t, e, *result.expectedTxn, typed.Stablecoin, req.owner, req.swapAuthority, destinationOwner, fromMint, toMint, p.SwapAmount, p.FeeAmount) default: require.Fail(t, "unexpected server parameters") } @@ -1749,7 +1749,7 @@ func (e *testEnv) statelessSwapRequest(t *testing.T, owner *common.Account, swap FromMint: usdcMint(t), ToMint: common.CoreMintAccount.ToProto(), SwapAmount: swapAmount, - SwapVersion: uint32(transaction_util.CoinbaseSwapV2), + SwapVersion: requiredCoinbaseSwapVersion, }, } } @@ -1851,8 +1851,7 @@ func (e *testEnv) expectedStatelessSwapTransaction(t *testing.T, req *statelessS coinbaseAccounts, err := transaction_util.GetCoinbaseSwapAccounts(e.ctx, e.data, fromMint.PublicKey().ToBytes(), toMint.PublicKey().ToBytes()) require.NoError(t, err) - coinbaseSwapIxn, err := transaction_util.MakeCoinbaseSwapInstruction( - selectCoinbaseSwapVersion(req.params.SwapVersion), + coinbaseSwapIxn := transaction_util.MakeCoinbaseSwapInstruction( coinbaseAccounts, req.owner.PublicKey().ToBytes(), fromMint.PublicKey().ToBytes(), @@ -1862,7 +1861,6 @@ func (e *testEnv) expectedStatelessSwapTransaction(t *testing.T, req *statelessS req.params.SwapAmount, req.params.SwapAmount, ) - require.NoError(t, err) feeRecipient, err := common.NewAccountFromPublicKeyBytes(coinbaseAccounts.FeeRecipient) require.NoError(t, err) @@ -3173,28 +3171,25 @@ func newStablecoinSwapFixture(t *testing.T, overrides ...func(*testOverrides)) ( func TestStatefulSwap_Stablecoin_HappyPath(t *testing.T) { for _, transactionVersion := range []uint32{0, 1} { - for _, swapVersion := range []transaction_util.CoinbaseSwapVersion{transaction_util.CoinbaseSwapV1, transaction_util.CoinbaseSwapV2} { - t.Run(fmt.Sprintf("txn v%d swap %s", transactionVersion, swapVersion), func(t *testing.T) { - env, owner := newStablecoinSwapFixture(t, withAntispamChecks()) + t.Run(fmt.Sprintf("txn v%d", transactionVersion), func(t *testing.T) { + env, owner := newStablecoinSwapFixture(t, withAntispamChecks()) - req := env.stablecoinSwapRequest(t, owner, common.ToCoreMintQuarks(10)) - req.transactionVersion = transactionVersion - req.stablecoin.SwapVersion = uint32(swapVersion) + req := env.stablecoinSwapRequest(t, owner, common.ToCoreMintQuarks(10)) + req.transactionVersion = transactionVersion - before := env.swapSnapshot(t, []*common.Account{owner}) - result := env.statefulSwap(t, req) - env.requireSwapCreated(t, before, req, result, expectedSwapRecord(t, req, result, swap.StateCreated), nil) + before := env.swapSnapshot(t, []*common.Account{owner}) + result := env.statefulSwap(t, req) + env.requireSwapCreated(t, before, req, result, expectedSwapRecord(t, req, result, swap.StateCreated), nil) - params := result.serverParameters.GetStablecoin() - require.NotNil(t, params) - assert.Equal(t, fmt.Sprintf("coinbase_stable_swapper_v%d", transactionVersion), params.MemoValue) + params := result.serverParameters.GetStablecoin() + require.NotNil(t, params) + assert.Equal(t, fmt.Sprintf("coinbase_stable_swapper_v%d", transactionVersion), params.MemoValue) - assert.Equal(t, []string{ - expectedAntispamSwapCall(swap.KindStablecoin, req.stablecoin.FundingSource, req.stablecoin.FromMint, req.stablecoin.ToMint, req.stablecoin.SwapAmount, req.stablecoin.FeeAmount, false), - }, env.antispamIntegration.getCalls()) - env.requireBalance(t, env.getVault(t, owner, common.CoreMintAccount), common.ToCoreMintQuarks(100)) - }) - } + assert.Equal(t, []string{ + expectedAntispamSwapCall(swap.KindStablecoin, req.stablecoin.FundingSource, req.stablecoin.FromMint, req.stablecoin.ToMint, req.stablecoin.SwapAmount, req.stablecoin.FeeAmount, false), + }, env.antispamIntegration.getCalls()) + env.requireBalance(t, env.getVault(t, owner, common.CoreMintAccount), common.ToCoreMintQuarks(100)) + }) } } @@ -3225,6 +3220,24 @@ func TestStatefulSwap_Stablecoin_Validation(t *testing.T) { result.requireDenied(t, "attempt to reuse swap funding id") }, }, + { + name: "swap version unset", + setup: func(t *testing.T, env *testEnv, req *statefulSwapRequest) { + req.stablecoin.SwapVersion = 0 + }, + verify: func(t *testing.T, result *statefulSwapResult) { + result.requireInvalidSwap(t, "swap version must be 2") + }, + }, + { + name: "swap version 1", + setup: func(t *testing.T, env *testEnv, req *statefulSwapRequest) { + req.stablecoin.SwapVersion = 1 + }, + verify: func(t *testing.T, result *statefulSwapResult) { + result.requireInvalidSwap(t, "swap version must be 2") + }, + }, { name: "source isn't the core mint", setup: func(t *testing.T, env *testEnv, req *statefulSwapRequest) { @@ -3768,7 +3781,10 @@ func requireProtoSwap(t *testing.T, req *statefulSwapRequest, result *statefulSw }, } } else { - params := req.stablecoin + // Swap records don't persist swap_version, so it's omitted from the + // returned metadata + params := proto.Clone(req.stablecoin).(*transactionpb.StatefulSwapRequest_Initiate_CoinbaseStableSwapperClientParameters) + params.SwapVersion = 0 expectedMetadata = &transactionpb.VerifiedSwapMetadata{ Kind: &transactionpb.VerifiedSwapMetadata_Stablecoin{ Stablecoin: &transactionpb.VerifiedCoinbaseStableSwapperSwapMetadata{ClientParameters: params}, @@ -3777,7 +3793,13 @@ func requireProtoSwap(t *testing.T, req *statefulSwapRequest, result *statefulSw } assert.True(t, proto.Equal(expectedMetadata, actual.VerifiedMetadata), "expected %v, got %v", expectedMetadata, actual.VerifiedMetadata) - marshalled, err := proto.Marshal(actual.VerifiedMetadata) + // Clients re-insert the swap_version they signed before verifying, which + // is always the required version + signedMetadata := proto.Clone(actual.VerifiedMetadata).(*transactionpb.VerifiedSwapMetadata) + if stablecoin := signedMetadata.GetStablecoin(); stablecoin != nil { + stablecoin.ClientParameters.SwapVersion = requiredCoinbaseSwapVersion + } + marshalled, err := proto.Marshal(signedMetadata) require.NoError(t, err) assert.True(t, ed25519.Verify(req.owner.PublicKey().ToBytes(), marshalled, actual.Signature.Value), "proof signature doesn't verify against the returned metadata") } @@ -3790,10 +3812,7 @@ func TestGetSwap(t *testing.T) { reserveResult := f.env.statefulSwap(t, reserveReq) reserveResult.requireSuccess(t) - // Swap records don't persist the swap version, so use the legacy swap - // instruction, whose metadata the server can reproduce stablecoinReq := f.env.stablecoinSwapRequest(t, f.owner, common.ToCoreMintQuarks(10)) - stablecoinReq.stablecoin.SwapVersion = 0 stablecoinResult := f.env.statefulSwap(t, stablecoinReq) stablecoinResult.requireSuccess(t) @@ -3811,18 +3830,6 @@ func TestGetSwap(t *testing.T) { requireProtoSwap(t, stablecoinReq, stablecoinResult, resp.Swap, transactionpb.SwapMetadata_CREATED) }) - t.Run("stablecoin with a swap version", func(t *testing.T) { - t.Skip("known bug: swap records don't persist swap_version, so toProtoSwap omits it and the proof signature doesn't verify against the returned metadata") - - req := f.env.stablecoinSwapRequest(t, f.owner, common.ToCoreMintQuarks(10)) - result := f.env.statefulSwap(t, req) - result.requireSuccess(t) - - resp, err := f.env.getSwap(t, f.owner, req.swapId(), f.owner) - require.NoError(t, err) - requireProtoSwap(t, req, result, resp.Swap, transactionpb.SwapMetadata_CREATED) - }) - t.Run("treasury funded new currency", func(t *testing.T) { t.Skip("known bug: swap records don't persist full_amount_exchange_data, so toProtoSwap omits it and the proof signature doesn't verify against the returned metadata") @@ -3896,11 +3903,9 @@ func TestGetPendingSwaps(t *testing.T) { pendingResults[req.swapId()] = result } - // A stablecoin swap is pending too. Its swap version isn't returned, so - // leave it unset to get metadata the proof signature verifies against. + // A stablecoin swap is pending too f.env.setupCoinbasePool(t, common.ToCoreMintQuarks(1_000_000)) stablecoinReq := f.env.stablecoinSwapRequest(t, f.owner, common.ToCoreMintQuarks(10)) - stablecoinReq.stablecoin.SwapVersion = 0 stablecoinResult := f.env.statefulSwap(t, stablecoinReq) stablecoinResult.requireSuccess(t) pending[stablecoinReq.swapId()] = stablecoinReq @@ -3990,7 +3995,6 @@ func TestMakeStatelessSwapTransaction(t *testing.T) { OutVault: testutil.NewRandomAccount(t).PublicKey().ToBytes(), InVaultTokenAccount: testutil.NewRandomAccount(t).PublicKey().ToBytes(), OutVaultTokenAccount: testutil.NewRandomAccount(t).PublicKey().ToBytes(), - Whitelist: testutil.NewRandomAccount(t).PublicKey().ToBytes(), FeeRecipient: poolFeeRecipient.PublicKey().ToBytes(), FeeRecipientTokenAccount: testutil.NewRandomAccount(t).PublicKey().ToBytes(), } @@ -3998,66 +4002,62 @@ func TestMakeStatelessSwapTransaction(t *testing.T) { var blockhash solana.Blockhash copy(blockhash[:], testutil.NewRandomAccount(t).PublicKey().ToBytes()) - for _, swapVersion := range []transaction_util.CoinbaseSwapVersion{transaction_util.CoinbaseSwapV1, transaction_util.CoinbaseSwapV2} { - coinbaseSwapIxn, err := transaction_util.MakeCoinbaseSwapInstruction( - swapVersion, - coinbaseAccounts, - owner.PublicKey().ToBytes(), - fromMint.PublicKey().ToBytes(), - common.CoreMintAccount.PublicKey().ToBytes(), - testutil.NewRandomAccount(t).PublicKey().ToBytes(), - depositAta, - 1_000_000, - 1_000_000, - ) - require.NoError(t, err) + coinbaseSwapIxn := transaction_util.MakeCoinbaseSwapInstruction( + coinbaseAccounts, + owner.PublicKey().ToBytes(), + fromMint.PublicKey().ToBytes(), + common.CoreMintAccount.PublicKey().ToBytes(), + testutil.NewRandomAccount(t).PublicKey().ToBytes(), + depositAta, + 1_000_000, + 1_000_000, + ) - t.Run("txn v0 swap "+swapVersion.String(), func(t *testing.T) { - txn, serverParameters, err := makeStatelessSwapTransaction(solana.MessageVersion0, blockhash, poolFeeRecipient, createDepositAtaIxn, coinbaseSwapIxn) - require.NoError(t, err) + t.Run("txn v0", func(t *testing.T) { + txn, serverParameters, err := makeStatelessSwapTransaction(solana.MessageVersion0, blockhash, poolFeeRecipient, createDepositAtaIxn, coinbaseSwapIxn) + require.NoError(t, err) - assert.Equal(t, solana.MessageVersion0, txn.Message.Version) - assertCommonStatelessSwapServerParameters(t, serverParameters, blockhash, poolFeeRecipient) - assert.Equal(t, "coinbase_stable_swapper_v0", serverParameters.MemoValue) - assert.Equal(t, transaction_util.ToProtoAlts([]solana.AddressLookupTable{transaction_util.GetAltForCoreMint()}), serverParameters.Alts) - assert.EqualValues(t, statelessSwapComputeUnitLimit, serverParameters.ComputeUnitLimit) - assert.EqualValues(t, statelessSwapComputeUnitPrice, serverParameters.ComputeUnitPrice) - assert.Nil(t, serverParameters.TransactionConfig) + assert.Equal(t, solana.MessageVersion0, txn.Message.Version) + assertCommonStatelessSwapServerParameters(t, serverParameters, blockhash, poolFeeRecipient) + assert.Equal(t, "coinbase_stable_swapper_v0", serverParameters.MemoValue) + assert.Equal(t, transaction_util.ToProtoAlts([]solana.AddressLookupTable{transaction_util.GetAltForCoreMint()}), serverParameters.Alts) + assert.EqualValues(t, statelessSwapComputeUnitLimit, serverParameters.ComputeUnitLimit) + assert.EqualValues(t, statelessSwapComputeUnitPrice, serverParameters.ComputeUnitPrice) + assert.Nil(t, serverParameters.TransactionConfig) - requireClientRebuildMatches(t, txn, serverParameters, createDepositAtaIxn, coinbaseSwapIxn) - }) + requireClientRebuildMatches(t, txn, serverParameters, createDepositAtaIxn, coinbaseSwapIxn) + }) - t.Run("txn v1 swap "+swapVersion.String(), func(t *testing.T) { - txn, serverParameters, err := makeStatelessSwapTransaction(solana.MessageVersion1, blockhash, poolFeeRecipient, createDepositAtaIxn, coinbaseSwapIxn) - require.NoError(t, err) + t.Run("txn v1", func(t *testing.T) { + txn, serverParameters, err := makeStatelessSwapTransaction(solana.MessageVersion1, blockhash, poolFeeRecipient, createDepositAtaIxn, coinbaseSwapIxn) + require.NoError(t, err) - assert.Equal(t, solana.MessageVersion1, txn.Message.Version) - assert.Empty(t, txn.Message.AddressTableLookups) - assertCommonStatelessSwapServerParameters(t, serverParameters, blockhash, poolFeeRecipient) - assert.Equal(t, "coinbase_stable_swapper_v1", serverParameters.MemoValue) - assert.Empty(t, serverParameters.Alts) - assert.Zero(t, serverParameters.ComputeUnitLimit) - assert.Zero(t, serverParameters.ComputeUnitPrice) - - require.NotNil(t, serverParameters.TransactionConfig) - assert.EqualValues(t, statelessSwapComputeUnitLimit, serverParameters.TransactionConfig.ComputeUnitLimit) - assert.EqualValues(t, transaction_util.CoinbaseSwapLoadedAccountsDataSizeLimit, serverParameters.TransactionConfig.LoadedAccountsDataSizeLimit) - assert.EqualValues(t, 1_000, serverParameters.TransactionConfig.PriorityFeeLamports) - assert.Zero(t, serverParameters.TransactionConfig.HeapSize) - - // ComputeBudget instructions are omitted in v1 - for _, account := range txn.Message.Accounts { - assert.NotEqual(t, compute_budget.ProgramKey, account) - } - assert.Len(t, txn.Message.Instructions, 3) + assert.Equal(t, solana.MessageVersion1, txn.Message.Version) + assert.Empty(t, txn.Message.AddressTableLookups) + assertCommonStatelessSwapServerParameters(t, serverParameters, blockhash, poolFeeRecipient) + assert.Equal(t, "coinbase_stable_swapper_v1", serverParameters.MemoValue) + assert.Empty(t, serverParameters.Alts) + assert.Zero(t, serverParameters.ComputeUnitLimit) + assert.Zero(t, serverParameters.ComputeUnitPrice) + + require.NotNil(t, serverParameters.TransactionConfig) + assert.EqualValues(t, statelessSwapComputeUnitLimit, serverParameters.TransactionConfig.ComputeUnitLimit) + assert.EqualValues(t, transaction_util.CoinbaseSwapLoadedAccountsDataSizeLimit, serverParameters.TransactionConfig.LoadedAccountsDataSizeLimit) + assert.EqualValues(t, 1_000, serverParameters.TransactionConfig.PriorityFeeLamports) + assert.Zero(t, serverParameters.TransactionConfig.HeapSize) + + // ComputeBudget instructions are omitted in v1 + for _, account := range txn.Message.Accounts { + assert.NotEqual(t, compute_budget.ProgramKey, account) + } + assert.Len(t, txn.Message.Instructions, 3) - marshalled, err := txn.Marshal() - require.NoError(t, err) - assert.LessOrEqual(t, len(marshalled), solana.MaxV1TransactionSize) + marshalled, err := txn.Marshal() + require.NoError(t, err) + assert.LessOrEqual(t, len(marshalled), solana.MaxV1TransactionSize) - requireClientRebuildMatches(t, txn, serverParameters, createDepositAtaIxn, coinbaseSwapIxn) - }) - } + requireClientRebuildMatches(t, txn, serverParameters, createDepositAtaIxn, coinbaseSwapIxn) + }) t.Run("unsupported version", func(t *testing.T) { _, _, err := makeStatelessSwapTransaction(solana.MessageVersionLegacy, blockhash, poolFeeRecipient, createDepositAtaIxn, createDepositAtaIxn) @@ -4286,27 +4286,24 @@ func TestStatelessSwap_ClientReceiveTimeout(t *testing.T) { func TestStatelessSwap_HappyPath(t *testing.T) { for _, transactionVersion := range []uint32{0, 1} { - for _, swapVersion := range []transaction_util.CoinbaseSwapVersion{transaction_util.CoinbaseSwapV1, transaction_util.CoinbaseSwapV2} { - t.Run(fmt.Sprintf("txn v%d swap %s", transactionVersion, swapVersion), func(t *testing.T) { - env, owner := newStatelessSwapFixture(t, withAntispamChecks()) - - req := env.statelessSwapRequest(t, owner, 25*1_000_000) - req.transactionVersion = transactionVersion - req.params.SwapVersion = uint32(swapVersion) + t.Run(fmt.Sprintf("txn v%d", transactionVersion), func(t *testing.T) { + env, owner := newStatelessSwapFixture(t, withAntispamChecks()) - before := env.swapSnapshot(t, []*common.Account{owner}) - result := env.statelessSwap(t, req) - require.NoError(t, result.err) - require.NotNil(t, result.resp.GetSuccess(), "expected success, got %v", result.resp) - assert.Equal(t, transactionpb.StatelessSwapResponse_Success_SUBMITTED, result.resp.GetSuccess().Code) - env.requireSubmitted(t, before, req, result) + req := env.statelessSwapRequest(t, owner, 25*1_000_000) + req.transactionVersion = transactionVersion - assert.Equal(t, selectSwapTransactionVersion(transactionVersion), result.expectedTxn.Message.Version) - assert.Equal(t, []string{ - expectedAntispamSwapCall(swap.KindStablecoin, transactionpb.FundingSource_FUNDING_SOURCE_UNKNOWN, req.params.FromMint, req.params.ToMint, req.params.SwapAmount, 0, false), - }, env.antispamIntegration.getCalls()) - }) - } + before := env.swapSnapshot(t, []*common.Account{owner}) + result := env.statelessSwap(t, req) + require.NoError(t, result.err) + require.NotNil(t, result.resp.GetSuccess(), "expected success, got %v", result.resp) + assert.Equal(t, transactionpb.StatelessSwapResponse_Success_SUBMITTED, result.resp.GetSuccess().Code) + env.requireSubmitted(t, before, req, result) + + assert.Equal(t, selectSwapTransactionVersion(transactionVersion), result.expectedTxn.Message.Version) + assert.Equal(t, []string{ + expectedAntispamSwapCall(swap.KindStablecoin, transactionpb.FundingSource_FUNDING_SOURCE_UNKNOWN, req.params.FromMint, req.params.ToMint, req.params.SwapAmount, 0, false), + }, env.antispamIntegration.getCalls()) + }) } } @@ -4417,6 +4414,24 @@ func TestStatelessSwap_Validation(t *testing.T) { setup func(t *testing.T, env *testEnv, req *statelessSwapRequest) verify func(t *testing.T, result *statelessSwapResult) }{ + { + name: "swap version unset", + setup: func(t *testing.T, env *testEnv, req *statelessSwapRequest) { + req.params.SwapVersion = 0 + }, + verify: func(t *testing.T, result *statelessSwapResult) { + result.requireInvalidSwap(t, "swap version must be 2") + }, + }, + { + name: "swap version 1", + setup: func(t *testing.T, env *testEnv, req *statelessSwapRequest) { + req.params.SwapVersion = 1 + }, + verify: func(t *testing.T, result *statelessSwapResult) { + result.requireInvalidSwap(t, "swap version must be 2") + }, + }, { name: "source isn't usdc", setup: func(t *testing.T, env *testEnv, req *statelessSwapRequest) { @@ -4614,6 +4629,7 @@ func TestStatefulSwap_Coinbase_TransactionVersionV1(t *testing.T) { FundingSource: transactionpb.FundingSource_FUNDING_SOURCE_SUBMIT_INTENT, FundingId: testutil.NewRandomAccount(t).PublicKey().ToBase58(), DestinationOwner: testutil.NewRandomAccount(t).ToProto(), + SwapVersion: requiredCoinbaseSwapVersion, }, }, }, @@ -4663,9 +4679,10 @@ func TestStatelessSwap_TransactionVersionV1Accepted(t *testing.T) { initiate := &transactionpb.StatelessSwapRequest_Initiate{ Kind: &transactionpb.StatelessSwapRequest_Initiate_Stablecoin{ Stablecoin: &transactionpb.StatelessSwapRequest_Initiate_CoinbaseStableSwapperClientParameters{ - FromMint: common.CoreMintAccount.ToProto(), - ToMint: common.CoreMintAccount.ToProto(), - SwapAmount: common.CoreMintQuarksPerUnit, + FromMint: common.CoreMintAccount.ToProto(), + ToMint: common.CoreMintAccount.ToProto(), + SwapAmount: common.CoreMintQuarksPerUnit, + SwapVersion: requiredCoinbaseSwapVersion, }, }, Owner: owner.ToProto(), @@ -4722,79 +4739,76 @@ func TestCoinbaseStableSwapperSwapHandler_TransactionVersions(t *testing.T) { const swapAmount, feeAmount = 5_000_000, 500_000 for _, transactionVersion := range []solana.MessageVersion{solana.MessageVersion0, solana.MessageVersion1} { - for _, coinbaseSwapVersion := range []transaction_util.CoinbaseSwapVersion{transaction_util.CoinbaseSwapV1, transaction_util.CoinbaseSwapV2} { - t.Run("txn "+transactionVersion.String()+" swap "+coinbaseSwapVersion.String(), func(t *testing.T) { - h := NewCoinbaseStableSwapperSwapHandler( - env.data, - owner, - swapAuthority, - destinationOwner, - fromMint, - toMint, - swapAmount, - feeAmount, - selectedNonce, - transactionVersion, - coinbaseSwapVersion, - ) - - txn, err := makeStatefulSwapTransaction(env.ctx, h) - require.NoError(t, err) - txn.SetBlockhash(selectedNonce.Blockhash) - - serverParameters := h.GetServerParameters().GetStablecoin() - require.NotNil(t, serverParameters) - - assert.Equal(t, transactionVersion, txn.Message.Version) - assert.Equal(t, common.GetSubsidizer().PublicKey().ToBytes(), serverParameters.Payer.Value) - assert.Equal(t, selectedNonce.Account.PublicKey().ToBytes(), serverParameters.Nonce.Value) - assert.Equal(t, blockhash[:], serverParameters.Blockhash.Value) - assert.Equal(t, common.CoreMintFeesAccount.PublicKey().ToBytes(), serverParameters.FeeDestination.Value) - - switch transactionVersion { - case solana.MessageVersion0: - assert.Equal(t, "coinbase_stable_swapper_v0", serverParameters.MemoValue) - assert.Equal(t, transaction_util.ToProtoAlts([]solana.AddressLookupTable{transaction_util.GetAltForCoreMint()}), serverParameters.Alts) - assert.EqualValues(t, 125_000, serverParameters.ComputeUnitLimit) - assert.EqualValues(t, 10_000, serverParameters.ComputeUnitPrice) - assert.Nil(t, serverParameters.TransactionConfig) - assert.Nil(t, h.GetTransactionConfig()) - case solana.MessageVersion1: - assert.Equal(t, "coinbase_stable_swapper_v1", serverParameters.MemoValue) - assert.Empty(t, serverParameters.Alts) - assert.Zero(t, serverParameters.ComputeUnitLimit) - assert.Zero(t, serverParameters.ComputeUnitPrice) - - require.NotNil(t, serverParameters.TransactionConfig) - assert.EqualValues(t, 125_000, serverParameters.TransactionConfig.ComputeUnitLimit) - assert.EqualValues(t, transaction_util.CoinbaseSwapLoadedAccountsDataSizeLimit, serverParameters.TransactionConfig.LoadedAccountsDataSizeLimit) - assert.EqualValues(t, 1_250, serverParameters.TransactionConfig.PriorityFeeLamports) - assert.Zero(t, serverParameters.TransactionConfig.HeapSize) - - assert.Empty(t, txn.Message.AddressTableLookups) - for _, account := range txn.Message.Accounts { - assert.NotEqual(t, compute_budget.ProgramKey, account) - } - assert.Len(t, txn.Message.Instructions, 7) + t.Run("txn "+transactionVersion.String(), func(t *testing.T) { + h := NewCoinbaseStableSwapperSwapHandler( + env.data, + owner, + swapAuthority, + destinationOwner, + fromMint, + toMint, + swapAmount, + feeAmount, + selectedNonce, + transactionVersion, + ) - marshalled, err := txn.Marshal() - require.NoError(t, err) - assert.LessOrEqual(t, len(marshalled), solana.MaxV1TransactionSize) + txn, err := makeStatefulSwapTransaction(env.ctx, h) + require.NoError(t, err) + txn.SetBlockhash(selectedNonce.Blockhash) + + serverParameters := h.GetServerParameters().GetStablecoin() + require.NotNil(t, serverParameters) + + assert.Equal(t, transactionVersion, txn.Message.Version) + assert.Equal(t, common.GetSubsidizer().PublicKey().ToBytes(), serverParameters.Payer.Value) + assert.Equal(t, selectedNonce.Account.PublicKey().ToBytes(), serverParameters.Nonce.Value) + assert.Equal(t, blockhash[:], serverParameters.Blockhash.Value) + assert.Equal(t, common.CoreMintFeesAccount.PublicKey().ToBytes(), serverParameters.FeeDestination.Value) + + switch transactionVersion { + case solana.MessageVersion0: + assert.Equal(t, "coinbase_stable_swapper_v0", serverParameters.MemoValue) + assert.Equal(t, transaction_util.ToProtoAlts([]solana.AddressLookupTable{transaction_util.GetAltForCoreMint()}), serverParameters.Alts) + assert.EqualValues(t, 125_000, serverParameters.ComputeUnitLimit) + assert.EqualValues(t, 10_000, serverParameters.ComputeUnitPrice) + assert.Nil(t, serverParameters.TransactionConfig) + assert.Nil(t, h.GetTransactionConfig()) + case solana.MessageVersion1: + assert.Equal(t, "coinbase_stable_swapper_v1", serverParameters.MemoValue) + assert.Empty(t, serverParameters.Alts) + assert.Zero(t, serverParameters.ComputeUnitLimit) + assert.Zero(t, serverParameters.ComputeUnitPrice) + + require.NotNil(t, serverParameters.TransactionConfig) + assert.EqualValues(t, 125_000, serverParameters.TransactionConfig.ComputeUnitLimit) + assert.EqualValues(t, transaction_util.CoinbaseSwapLoadedAccountsDataSizeLimit, serverParameters.TransactionConfig.LoadedAccountsDataSizeLimit) + assert.EqualValues(t, 1_250, serverParameters.TransactionConfig.PriorityFeeLamports) + assert.Zero(t, serverParameters.TransactionConfig.HeapSize) + + assert.Empty(t, txn.Message.AddressTableLookups) + for _, account := range txn.Message.Accounts { + assert.NotEqual(t, compute_budget.ProgramKey, account) } + assert.Len(t, txn.Message.Instructions, 7) - // The owner and swap authority are the client signers - var clientSigners int - for i := range int(txn.Message.Header.NumSignatures) { - account := txn.Message.Accounts[i] - if bytes.Equal(account, owner.PublicKey().ToBytes()) || bytes.Equal(account, swapAuthority.PublicKey().ToBytes()) { - clientSigners++ - } + marshalled, err := txn.Marshal() + require.NoError(t, err) + assert.LessOrEqual(t, len(marshalled), solana.MaxV1TransactionSize) + } + + // The owner and swap authority are the client signers + var clientSigners int + for i := range int(txn.Message.Header.NumSignatures) { + account := txn.Message.Accounts[i] + if bytes.Equal(account, owner.PublicKey().ToBytes()) || bytes.Equal(account, swapAuthority.PublicKey().ToBytes()) { + clientSigners++ } - assert.Equal(t, 2, clientSigners) + } + assert.Equal(t, 2, clientSigners) - requireCoinbaseStatefulClientRebuildMatches(t, env, txn, serverParameters, owner, swapAuthority, destinationOwner, fromMint, toMint, swapAmount, feeAmount, coinbaseSwapVersion) - }) - } + requireCoinbaseStatefulClientRebuildMatches(t, env, txn, serverParameters, owner, swapAuthority, destinationOwner, fromMint, toMint, swapAmount, feeAmount) + }) } } @@ -4809,7 +4823,6 @@ func requireCoinbaseStatefulClientRebuildMatches( params *transactionpb.StatefulSwapResponse_ServerParameters_CoinbaseStableSwapperServerParameter, owner, swapAuthority, destinationOwner, fromMint, toMint *common.Account, swapAmount, feeAmount uint64, - coinbaseSwapVersion transaction_util.CoinbaseSwapVersion, ) { payer := params.Payer.Value @@ -4827,8 +4840,7 @@ func requireCoinbaseStatefulClientRebuildMatches( require.NoError(t, err) require.Equal(t, []byte(coinbaseAccounts.FeeRecipient), params.PoolFeeRecipient.Value) - coinbaseSwapIxn, err := transaction_util.MakeCoinbaseSwapInstruction( - coinbaseSwapVersion, + coinbaseSwapIxn := transaction_util.MakeCoinbaseSwapInstruction( coinbaseAccounts, swapAuthority.PublicKey().ToBytes(), fromMint.PublicKey().ToBytes(), @@ -4838,7 +4850,6 @@ func requireCoinbaseStatefulClientRebuildMatches( swapAmount, swapAmount, ) - require.NoError(t, err) ixns := []solana.Instruction{system.AdvanceNonce(params.Nonce.Value, payer)} if params.TransactionConfig == nil { @@ -5159,14 +5170,6 @@ func TestReserveSwapHandlers_TransactionVersions(t *testing.T) { } } -func TestSelectCoinbaseSwapVersion(t *testing.T) { - // Unset (older clients) and 1 both use the legacy swap instruction - assert.Equal(t, transaction_util.CoinbaseSwapV1, selectCoinbaseSwapVersion(0)) - assert.Equal(t, transaction_util.CoinbaseSwapV1, selectCoinbaseSwapVersion(1)) - - assert.Equal(t, transaction_util.CoinbaseSwapV2, selectCoinbaseSwapVersion(2)) -} - func TestSelectSwapTransactionVersion(t *testing.T) { assert.Equal(t, solana.MessageVersion0, selectSwapTransactionVersion(0)) assert.Equal(t, solana.MessageVersion1, selectSwapTransactionVersion(1)) diff --git a/ocp/transaction/coinbase_swap.go b/ocp/transaction/coinbase_swap.go index c1d15f6..aad7036 100644 --- a/ocp/transaction/coinbase_swap.go +++ b/ocp/transaction/coinbase_swap.go @@ -13,38 +13,15 @@ import ( "github.com/code-payments/ocp-server/solana/token" ) -// CoinbaseSwapVersion selects the CoinbaseStableSwapper swap instruction. -// Clients build and sign swap transactions locally, so the server must build -// the same version as the client. -type CoinbaseSwapVersion uint8 - -const ( - CoinbaseSwapV1 CoinbaseSwapVersion = iota + 1 // swap, with the deprecated whitelist account - CoinbaseSwapV2 // swap_v2 -) - -func (v CoinbaseSwapVersion) String() string { - switch v { - case CoinbaseSwapV1: - return "v1" - case CoinbaseSwapV2: - return "v2" - default: - return "unknown" - } -} - // CoinbaseSwapAccounts captures all derived PDAs and on-chain values needed // to build a CoinbaseStableSwapper swap instruction for a (fromMint, toMint) // pair. FeeRecipient is sourced from the on-chain LiquidityPool account. -// Whitelist is only used by CoinbaseSwapV1. type CoinbaseSwapAccounts struct { Pool ed25519.PublicKey InVault ed25519.PublicKey OutVault ed25519.PublicKey InVaultTokenAccount ed25519.PublicKey OutVaultTokenAccount ed25519.PublicKey - Whitelist ed25519.PublicKey FeeRecipient ed25519.PublicKey FeeRecipientTokenAccount ed25519.PublicKey } @@ -87,11 +64,6 @@ func GetCoinbaseSwapAccounts(ctx context.Context, data ocp_data.Provider, fromMi return nil, errors.Wrap(err, "error getting out vault token account address") } - whitelist, _, err := coinbase_stable_swapper.GetWhitelistAddress() - if err != nil { - return nil, errors.Wrap(err, "error getting whitelist address") - } - poolAccountInfo, _, err := data.GetBlockchainAccountInfo(ctx, base58.Encode(pool)) if err != nil { return nil, errors.Wrap(err, "error getting coinbase liquidity pool account info") @@ -113,7 +85,6 @@ func GetCoinbaseSwapAccounts(ctx context.Context, data ocp_data.Provider, fromMi OutVault: outVault, InVaultTokenAccount: inVaultTokenAccount, OutVaultTokenAccount: outVaultTokenAccount, - Whitelist: whitelist, FeeRecipient: poolAccount.FeeRecipient, FeeRecipientTokenAccount: feeRecipientTokenAccount, }, nil @@ -155,61 +126,33 @@ func GetCoinbaseSwapDestinationLiquidity(ctx context.Context, data ocp_data.Prov return info.Amount, nil } -// MakeCoinbaseSwapInstruction builds a CoinbaseStableSwapper swap instruction -// for the provided version. +// MakeCoinbaseSwapInstruction builds a CoinbaseStableSwapper swap_v2 +// instruction. func MakeCoinbaseSwapInstruction( - version CoinbaseSwapVersion, accounts *CoinbaseSwapAccounts, user ed25519.PublicKey, fromMint, toMint ed25519.PublicKey, userFromTokenAccount, userToTokenAccount ed25519.PublicKey, amountIn, minAmountOut uint64, -) (solana.Instruction, error) { - switch version { - case CoinbaseSwapV1: - return coinbase_stable_swapper.NewSwapInstruction( - &coinbase_stable_swapper.SwapInstructionAccounts{ - Pool: accounts.Pool, - InVault: accounts.InVault, - OutVault: accounts.OutVault, - InVaultTokenAccount: accounts.InVaultTokenAccount, - OutVaultTokenAccount: accounts.OutVaultTokenAccount, - UserFromTokenAccount: userFromTokenAccount, - ToTokenAccount: userToTokenAccount, - FeeRecipientTokenAccount: accounts.FeeRecipientTokenAccount, - FeeRecipient: accounts.FeeRecipient, - FromMint: fromMint, - ToMint: toMint, - User: user, - Whitelist: accounts.Whitelist, - }, - &coinbase_stable_swapper.SwapInstructionArgs{ - AmountIn: amountIn, - MinAmountOut: minAmountOut, - }, - ), nil - case CoinbaseSwapV2: - return coinbase_stable_swapper.NewSwapV2Instruction( - &coinbase_stable_swapper.SwapV2InstructionAccounts{ - Pool: accounts.Pool, - InVault: accounts.InVault, - OutVault: accounts.OutVault, - InVaultTokenAccount: accounts.InVaultTokenAccount, - OutVaultTokenAccount: accounts.OutVaultTokenAccount, - UserFromTokenAccount: userFromTokenAccount, - ToTokenAccount: userToTokenAccount, - FeeRecipientTokenAccount: accounts.FeeRecipientTokenAccount, - FeeRecipient: accounts.FeeRecipient, - FromMint: fromMint, - ToMint: toMint, - User: user, - }, - &coinbase_stable_swapper.SwapV2InstructionArgs{ - AmountIn: amountIn, - MinAmountOut: minAmountOut, - }, - ), nil - default: - return solana.Instruction{}, errors.Errorf("unsupported coinbase swap version: %d", version) - } +) solana.Instruction { + return coinbase_stable_swapper.NewSwapV2Instruction( + &coinbase_stable_swapper.SwapV2InstructionAccounts{ + Pool: accounts.Pool, + InVault: accounts.InVault, + OutVault: accounts.OutVault, + InVaultTokenAccount: accounts.InVaultTokenAccount, + OutVaultTokenAccount: accounts.OutVaultTokenAccount, + UserFromTokenAccount: userFromTokenAccount, + ToTokenAccount: userToTokenAccount, + FeeRecipientTokenAccount: accounts.FeeRecipientTokenAccount, + FeeRecipient: accounts.FeeRecipient, + FromMint: fromMint, + ToMint: toMint, + User: user, + }, + &coinbase_stable_swapper.SwapV2InstructionArgs{ + AmountIn: amountIn, + MinAmountOut: minAmountOut, + }, + ) } diff --git a/ocp/transaction/coinbase_swap_test.go b/ocp/transaction/coinbase_swap_test.go index 9053094..ce42f06 100644 --- a/ocp/transaction/coinbase_swap_test.go +++ b/ocp/transaction/coinbase_swap_test.go @@ -5,13 +5,12 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" coinbase_stable_swapper "github.com/code-payments/ocp-server/solana/coinbasestableswapper" ) func TestMakeCoinbaseSwapInstruction(t *testing.T) { - keys := make([]ed25519.PublicKey, 14) + keys := make([]ed25519.PublicKey, 12) for i := range keys { keys[i] = make([]byte, ed25519.PublicKeySize) keys[i][0] = byte(i + 1) @@ -23,43 +22,33 @@ func TestMakeCoinbaseSwapInstruction(t *testing.T) { OutVault: keys[2], InVaultTokenAccount: keys[3], OutVaultTokenAccount: keys[4], - Whitelist: keys[5], - FeeRecipient: keys[6], - FeeRecipientTokenAccount: keys[7], - } - user, fromMint, toMint, userFrom, userTo := keys[8], keys[9], keys[10], keys[11], keys[12] - - build := func(version CoinbaseSwapVersion) ([]ed25519.PublicKey, []byte, error) { - ixn, err := MakeCoinbaseSwapInstruction(version, accounts, user, fromMint, toMint, userFrom, userTo, 1_000_000, 990_000) - if err != nil { - return nil, nil, err - } - assert.EqualValues(t, coinbase_stable_swapper.PROGRAM_ADDRESS, ixn.Program) - var ixnKeys []ed25519.PublicKey - for _, meta := range ixn.Accounts { - ixnKeys = append(ixnKeys, meta.PublicKey) - } - return ixnKeys, ixn.Data, nil - } - - v1Keys, v1Data, err := build(CoinbaseSwapV1) - require.NoError(t, err) - assert.Equal(t, coinbase_stable_swapper.SwapInstructionDiscriminator, v1Data[:8]) - assert.Len(t, v1Keys, 16) - assert.Contains(t, v1Keys, accounts.Whitelist) - - v2Keys, v2Data, err := build(CoinbaseSwapV2) - require.NoError(t, err) - assert.Equal(t, coinbase_stable_swapper.SwapV2InstructionDiscriminator, v2Data[:8]) - assert.Len(t, v2Keys, 15) - assert.NotContains(t, v2Keys, accounts.Whitelist) - - // Same args and same accounts, other than the whitelist - assert.Equal(t, v1Data[8:], v2Data[8:]) - assert.Equal(t, append(append([]ed25519.PublicKey{}, v1Keys[:12]...), v1Keys[13:]...), v2Keys) - - for _, version := range []CoinbaseSwapVersion{0, CoinbaseSwapV2 + 1} { - _, _, err = build(version) - assert.Error(t, err) + FeeRecipient: keys[5], + FeeRecipientTokenAccount: keys[6], } + user, fromMint, toMint, userFrom, userTo := keys[7], keys[8], keys[9], keys[10], keys[11] + + ixn := MakeCoinbaseSwapInstruction(accounts, user, fromMint, toMint, userFrom, userTo, 1_000_000, 990_000) + + expected := coinbase_stable_swapper.NewSwapV2Instruction( + &coinbase_stable_swapper.SwapV2InstructionAccounts{ + Pool: accounts.Pool, + InVault: accounts.InVault, + OutVault: accounts.OutVault, + InVaultTokenAccount: accounts.InVaultTokenAccount, + OutVaultTokenAccount: accounts.OutVaultTokenAccount, + UserFromTokenAccount: userFrom, + ToTokenAccount: userTo, + FeeRecipientTokenAccount: accounts.FeeRecipientTokenAccount, + FeeRecipient: accounts.FeeRecipient, + FromMint: fromMint, + ToMint: toMint, + User: user, + }, + &coinbase_stable_swapper.SwapV2InstructionArgs{ + AmountIn: 1_000_000, + MinAmountOut: 990_000, + }, + ) + assert.Equal(t, expected, ixn) + assert.Equal(t, coinbase_stable_swapper.SwapV2InstructionDiscriminator, ixn.Data[:8]) } diff --git a/solana/coinbasestableswapper/address.go b/solana/coinbasestableswapper/address.go index 360afb9..40eed4e 100644 --- a/solana/coinbasestableswapper/address.go +++ b/solana/coinbasestableswapper/address.go @@ -10,7 +10,6 @@ var ( LiquidityPoolPrefix = []byte("liquidity_pool") TokenVaultPrefix = []byte("token_vault") VaultTokenAccountPrefix = []byte("vault_token_account") - AddressWhitelistPrefix = []byte("address_whitelist") ) // GetPoolAddress returns the PDA for the liquidity pool @@ -48,11 +47,3 @@ func GetVaultTokenAccountAddress(args *GetVaultTokenAccountAddressArgs) (ed25519 args.Vault, ) } - -// GetWhitelistAddress returns the PDA for the address whitelist -func GetWhitelistAddress() (ed25519.PublicKey, uint8, error) { - return solana.FindProgramAddressAndBump( - PROGRAM_ID, - AddressWhitelistPrefix, - ) -} diff --git a/solana/coinbasestableswapper/instructions_swap.go b/solana/coinbasestableswapper/instructions_swap.go deleted file mode 100644 index f0cc5ce..0000000 --- a/solana/coinbasestableswapper/instructions_swap.go +++ /dev/null @@ -1,139 +0,0 @@ -package coinbase_stable_swapper - -import ( - "crypto/ed25519" - - "github.com/code-payments/ocp-server/solana" -) - -const ( - SwapInstructionArgsSize = (8 + // discriminator - 8 + // amount_in - 8) // min_amount_out -) - -type SwapInstructionArgs struct { - AmountIn uint64 - MinAmountOut uint64 -} - -type SwapInstructionAccounts struct { - Pool ed25519.PublicKey - InVault ed25519.PublicKey - OutVault ed25519.PublicKey - InVaultTokenAccount ed25519.PublicKey - OutVaultTokenAccount ed25519.PublicKey - UserFromTokenAccount ed25519.PublicKey - ToTokenAccount ed25519.PublicKey - FeeRecipientTokenAccount ed25519.PublicKey - FeeRecipient ed25519.PublicKey - FromMint ed25519.PublicKey - ToMint ed25519.PublicKey - User ed25519.PublicKey - Whitelist ed25519.PublicKey -} - -func NewSwapInstruction( - accounts *SwapInstructionAccounts, - args *SwapInstructionArgs, -) solana.Instruction { - var offset int - - // Serialize instruction arguments - data := make([]byte, SwapInstructionArgsSize) - - putDiscriminator(data, SwapInstructionDiscriminator, &offset) - putUint64(data, args.AmountIn, &offset) - putUint64(data, args.MinAmountOut, &offset) - - return solana.Instruction{ - Program: PROGRAM_ADDRESS, - - // Instruction args - Data: data, - - // Instruction accounts - Accounts: []solana.AccountMeta{ - { - PublicKey: accounts.Pool, - IsWritable: false, - IsSigner: false, - }, - { - PublicKey: accounts.InVault, - IsWritable: false, - IsSigner: false, - }, - { - PublicKey: accounts.OutVault, - IsWritable: false, - IsSigner: false, - }, - { - PublicKey: accounts.InVaultTokenAccount, - IsWritable: true, - IsSigner: false, - }, - { - PublicKey: accounts.OutVaultTokenAccount, - IsWritable: true, - IsSigner: false, - }, - { - PublicKey: accounts.UserFromTokenAccount, - IsWritable: true, - IsSigner: false, - }, - { - PublicKey: accounts.ToTokenAccount, - IsWritable: true, - IsSigner: false, - }, - { - PublicKey: accounts.FeeRecipientTokenAccount, - IsWritable: true, - IsSigner: false, - }, - { - PublicKey: accounts.FeeRecipient, - IsWritable: false, - IsSigner: false, - }, - { - PublicKey: accounts.FromMint, - IsWritable: false, - IsSigner: false, - }, - { - PublicKey: accounts.ToMint, - IsWritable: false, - IsSigner: false, - }, - { - PublicKey: accounts.User, - IsWritable: true, - IsSigner: true, - }, - { - PublicKey: accounts.Whitelist, - IsWritable: false, - IsSigner: false, - }, - { - PublicKey: SPL_TOKEN_PROGRAM_ID, - IsWritable: false, - IsSigner: false, - }, - { - PublicKey: ASSOCIATED_TOKEN_PROGRAM_ID, - IsWritable: false, - IsSigner: false, - }, - { - PublicKey: SYSTEM_PROGRAM_ID, - IsWritable: false, - IsSigner: false, - }, - }, - } -} diff --git a/solana/coinbasestableswapper/instructions_swap_v2.go b/solana/coinbasestableswapper/instructions_swap_v2.go index d6ef012..460a452 100644 --- a/solana/coinbasestableswapper/instructions_swap_v2.go +++ b/solana/coinbasestableswapper/instructions_swap_v2.go @@ -32,8 +32,9 @@ type SwapV2InstructionAccounts struct { User ed25519.PublicKey } -// NewSwapV2Instruction builds a swap_v2 instruction, which is swap without the -// deprecated whitelist account. Args, logic, and effects are unchanged. +// NewSwapV2Instruction builds a swap_v2 instruction. The original swap +// instruction, which required an address whitelist account, is deprecated and +// unsupported. func NewSwapV2Instruction( accounts *SwapV2InstructionAccounts, args *SwapV2InstructionArgs, diff --git a/solana/coinbasestableswapper/instructions_swap_v2_test.go b/solana/coinbasestableswapper/instructions_swap_v2_test.go index a9b9c22..819a8ef 100644 --- a/solana/coinbasestableswapper/instructions_swap_v2_test.go +++ b/solana/coinbasestableswapper/instructions_swap_v2_test.go @@ -9,36 +9,14 @@ import ( "github.com/code-payments/ocp-server/solana" ) -func TestSwapV2Instruction_MatchesSwapWithoutWhitelist(t *testing.T) { - keys := make([]ed25519.PublicKey, 13) +func TestSwapV2Instruction(t *testing.T) { + keys := make([]ed25519.PublicKey, 12) for i := range keys { keys[i] = make([]byte, ed25519.PublicKeySize) keys[i][0] = byte(i + 1) } - v1 := NewSwapInstruction( - &SwapInstructionAccounts{ - Pool: keys[0], - InVault: keys[1], - OutVault: keys[2], - InVaultTokenAccount: keys[3], - OutVaultTokenAccount: keys[4], - UserFromTokenAccount: keys[5], - ToTokenAccount: keys[6], - FeeRecipientTokenAccount: keys[7], - FeeRecipient: keys[8], - FromMint: keys[9], - ToMint: keys[10], - User: keys[11], - Whitelist: keys[12], - }, - &SwapInstructionArgs{ - AmountIn: 1_500_000, - MinAmountOut: 1_490_000, - }, - ) - - v2 := NewSwapV2Instruction( + ixn := NewSwapV2Instruction( &SwapV2InstructionAccounts{ Pool: keys[0], InVault: keys[1], @@ -59,20 +37,29 @@ func TestSwapV2Instruction_MatchesSwapWithoutWhitelist(t *testing.T) { }, ) - require.EqualValues(t, PROGRAM_ADDRESS, v2.Program) + require.EqualValues(t, PROGRAM_ADDRESS, ixn.Program) require.Equal(t, []byte{ 43, 4, 237, 11, 26, 201, 30, 98, // discriminator 0x60, 0xe3, 0x16, 0, 0, 0, 0, 0, // amount_in = 1_500_000 0x50, 0xbc, 0x16, 0, 0, 0, 0, 0, // min_amount_out = 1_490_000 - }, v2.Data) - require.Equal(t, v1.Data[8:], v2.Data[8:]) + }, ixn.Data) - // The whitelist is the 13th account in swap; swap_v2 drops it and keeps - // everything else in order. - require.Len(t, v1.Accounts, 16) - require.Len(t, v2.Accounts, 15) - require.EqualValues(t, keys[12], v1.Accounts[12].PublicKey) - expected := append(append([]solana.AccountMeta{}, v1.Accounts[:12]...), v1.Accounts[13:]...) - require.Equal(t, expected, v2.Accounts) + require.Equal(t, []solana.AccountMeta{ + {PublicKey: keys[0]}, + {PublicKey: keys[1]}, + {PublicKey: keys[2]}, + {PublicKey: keys[3], IsWritable: true}, + {PublicKey: keys[4], IsWritable: true}, + {PublicKey: keys[5], IsWritable: true}, + {PublicKey: keys[6], IsWritable: true}, + {PublicKey: keys[7], IsWritable: true}, + {PublicKey: keys[8]}, + {PublicKey: keys[9]}, + {PublicKey: keys[10]}, + {PublicKey: keys[11], IsWritable: true, IsSigner: true}, + {PublicKey: SPL_TOKEN_PROGRAM_ID}, + {PublicKey: ASSOCIATED_TOKEN_PROGRAM_ID}, + {PublicKey: SYSTEM_PROGRAM_ID}, + }, ixn.Accounts) } diff --git a/solana/coinbasestableswapper/types_account_type.go b/solana/coinbasestableswapper/types_account_type.go index 15d0ab4..06741fe 100644 --- a/solana/coinbasestableswapper/types_account_type.go +++ b/solana/coinbasestableswapper/types_account_type.go @@ -5,9 +5,6 @@ var ( // LiquidityPool discriminator: [66, 38, 17, 64, 188, 80, 68, 129] LiquidityPoolAccountDiscriminator = []byte{66, 38, 17, 64, 188, 80, 68, 129} - // AddressWhitelist discriminator: [10, 102, 46, 176, 154, 249, 160, 48] - AddressWhitelistAccountDiscriminator = []byte{10, 102, 46, 176, 154, 249, 160, 48} - // TokenVault discriminator: [121, 7, 84, 254, 151, 228, 43, 144] TokenVaultAccountDiscriminator = []byte{121, 7, 84, 254, 151, 228, 43, 144} ) diff --git a/solana/coinbasestableswapper/types_instruction_type.go b/solana/coinbasestableswapper/types_instruction_type.go index 1dda9b9..f4b7d63 100644 --- a/solana/coinbasestableswapper/types_instruction_type.go +++ b/solana/coinbasestableswapper/types_instruction_type.go @@ -2,9 +2,6 @@ package coinbase_stable_swapper // Instruction discriminators from the on-chain IDL var ( - // swap discriminator: [248, 198, 158, 145, 225, 117, 135, 200] - SwapInstructionDiscriminator = []byte{248, 198, 158, 145, 225, 117, 135, 200} - // swap_v2 discriminator: [43, 4, 237, 11, 26, 201, 30, 98] SwapV2InstructionDiscriminator = []byte{43, 4, 237, 11, 26, 201, 30, 98} )