Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: sdk extension for people to swap #213

Open
wants to merge 32 commits into
base: main
Choose a base branch
from
Open

Conversation

shoom3301
Copy link
Contributor

@shoom3301 shoom3301 commented Jun 26, 2024

See https://github.com/cowprotocol/cow-sdk/blob/56985986c7bf3585eed85d5b71e221f69ed763a2/src/trading/README.md

The shortest way to post an order

import { SupportedChainId, OrderKind, TradeParameters, TradingSdk } from '@cowprotocol/sdk'

const sdk = new TradingSdk({
  chainId: SupportedChainId.SEPOLIA,
  signer: '<privateKeyOrEthersSigner>',
  appCode: '<YOUR_APP_CODE>',
})

const parameters: TradeParameters = {
  kind: OrderKind.BUY,
  sellToken: '0xfff9976782d46cc05630d1f6ebab18b2324d6b14',
  sellTokenDecimals: 18,
  buyToken: '0x0625afb445c3b6b7b929342a04a22599fd5dbb59',
  buyTokenDecimals: 18,
  amount: '120000000000000000'
}

const orderId = await sdk.postSwapOrder(parameters)

console.log('Order created, id: ', orderId)

Get quote -> confirm -> post order

import { SupportedChainId, OrderKind, TradeParameters, TradingSdk } from '@cowprotocol/sdk'

const sdk = new TradingSdk({
  chainId: SupportedChainId.SEPOLIA,
  signer: '<privateKeyOrEthersSigner>',
  appCode: '<YOUR_APP_CODE>',
})

const parameters: TradeParameters = {
  kind: OrderKind.BUY,
  sellToken: '0xfff9976782d46cc05630d1f6ebab18b2324d6b14',
  sellTokenDecimals: 18,
  buyToken: '0x0625afb445c3b6b7b929342a04a22599fd5dbb59',
  buyTokenDecimals: 18,
  amount: '120000000000000000'
}

const { quoteResults, postSwapOrderFromQuote } = await sdk.getQuote(parameters)

const buyAmount = quoteResults.amountsAndCosts.afterSlippage.buyAmount

if (confirm(`You will get at least: ${buyAmount}, ok?`)) {
  const orderId = await postSwapOrderFromQuote()

  console.log('Order created, id: ', orderId)
}

Copy link
Contributor

@anxolin anxolin left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like where this is going.

However, I imagined this differently.

Here you make a call to postSwapOrder once with the equivalent to what you input in the widget form, and it will post the order.

I think is great, but if someone needs to build a UI will need the quote information.

The problem I think is interesting to improve is, its freaking hard to come up with the parameters of the order as we send them to be signed.

This is why this should be broken in 2 steps:

    1. Get order params
    1. Post order

In (1) we will:

  • Make a quote
  • Take slippage into account
  • prepare the app data
  • handle eth flow
  • return
    • order params, AS WE SHOULD SIGN THEM in the wallet
    • convenient info to show to the user
      • Mimum received
      • USD amounts
      • fee estimation
      • fee estimations in USD
      • slippage calculations
      • warnings of all sort! (let people to have good protection without effort)
      • etc

In essence, for me the great contribution is implementing this (1). Maybe this is herlpul:

For (2), we just need to pass the order params from (1) and pass them along the signer

Just some final 💡 I'd like to add. This logic will be made into a library, which we can reuse anywhere. I'd like to use it in BFF and implement a simple endpoint, so it allows non JS projects to easily get the trading parameters. This way, we make integrations dead simple

Here are some related notes on some similar idea:

https://www.notion.so/cownation/2023-10-Swap-as-Limit-orders-fee-0-5a00548015a14c9f939b934cb5e33309?pvs=4#2b4061efcce740bdb6c743ad269c5214

@anxolin
Copy link
Contributor

anxolin commented Jun 26, 2024

I just want to add a plausible roadmap of this:

v1: Library
v2: Endpoint
v3: Using the same abstractions we can make the Swap Kit: https://www.notion.so/cownation/CoW-Swap-Kit-lib-623d1bbb4db2400b8db1d7ad44106c4d?pvs=4

This way we can provide "progressive integrations"
Widget --> Swap Kit --> Library / Endpoint --> You own thing (uses only blockchain)

Form left to right, you get more and more control. This way, we provide an easy way to start, and then ways to gain control

Copy link

socket-security bot commented Jun 27, 2024

👍 Dependency issues cleared. Learn more about Socket for GitHub ↗︎

This PR previously contained dependency changes with security issues that have been resolved, removed, or ignored.

View full report↗︎

@cowprotocol cowprotocol deleted a comment from socket-security bot Jun 28, 2024
@shoom3301 shoom3301 requested a review from a team July 5, 2024 14:53
@shoom3301 shoom3301 marked this pull request as ready for review July 5, 2024 14:53
@coveralls
Copy link
Collaborator

Coverage Status

coverage: 72.791% (-6.8%) from 79.583%
when pulling 5639517 on feat/swap-for-people
into 97d0315 on main.

@coveralls
Copy link
Collaborator

Coverage Status

coverage: 72.791% (-6.8%) from 79.583%
when pulling 5639517 on feat/swap-for-people
into 97d0315 on main.

@coveralls
Copy link
Collaborator

coveralls commented Sep 2, 2024

Coverage Status

coverage: 78.814% (+0.6%) from 78.23%
when pulling 953f848 on feat/swap-for-people
into 5ad85a1 on main.

@cowprotocol cowprotocol deleted a comment from socket-security bot Sep 5, 2024
src/common/consts.ts Outdated Show resolved Hide resolved
@shoom3301 shoom3301 requested a review from a team November 8, 2024 12:30
@shoom3301 shoom3301 self-assigned this Nov 8, 2024
@shoom3301
Copy link
Contributor Author

@anxolin thanks for the feedback!

This is why this should be broken in 2 steps:

Make a quote

Take slippage into account

prepare the app data

handle eth flow

return order params, AS WE SHOULD SIGN THEM in the wallet

Mimum received

USD amounts

fee estimation

fee estimations in USD

slippage calculations

warnings of all sort! (let people to have good protection without effort)

Points that are not done (❌) - we discussed them and decided to not implement them right now.

@shoom3301 shoom3301 changed the title feat: SDK extension for people to swap feat: sdk extension for people to swap Nov 8, 2024
Copy link
Contributor

@anxolin anxolin left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll continue reviewing in another moment cause I need to leave, so far looks great and easy to use.

}

export const getFormState = (): FormState => {
return Object.fromEntries(new FormData(document.getElementById('form') as HTMLFormElement)) as unknown as FormState
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good old vanilla :)

const buyToken = TOKENS[chainId].find((t) => t.address === _buyToken)
const decimals = isSell ? sellToken.decimals : buyToken.decimals
const multiplicator = decimals > 3 ? 3 : 0
const amount = BigInt(+_amount * 10 ** multiplicator) * BigInt(10 ** (decimals - multiplicator))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't get what you want to do here

@@ -27,10 +27,11 @@
"prepare": "npm run build",
"prepublishOnly": "npm test && npm run lint",
"graphql:codegen": "graphql-codegen --config graphql-codegen.yml",
"swagger:codegen": " openapi --input https://raw.githubusercontent.com/cowprotocol/services/v2.281.0/crates/orderbook/openapi.yml --output src/order-book/generated --exportServices false --exportCore false",
"swagger:codegen": " openapi --input https://raw.githubusercontent.com/cowprotocol/services/main/crates/orderbook/openapi.yml --output src/order-book/generated --exportServices false --exportCore false",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure @alfetopito will like this

@@ -95,7 +96,7 @@ export abstract class ConditionalOrder<D, S> {
assertIsValid(): void {
const isValidResult = this.isValid()
if (!isValidResult.isValid) {
throw new Error(`Invalid order: ${isValidResult.reason}`)
throw new Error(`Invalid order: ${(isValidResult as IsNotValid).reason}`)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably this cast has to be done cause we didn't use type assertions. Not from this PR though

* @param {Order} order order to sign
* @param {Pick<OrderUidParams, 'owner'>} params order unique identifier parameters.
*/
export async function generateOrderId(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would swear we had already one piece of code doing this. I remember in the watch-tower and SDK deriving the orderId form the order data

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is what I meant:

const orderUid = await computeOrderUid(chainId, owner, fromStructToOrder(order))

Copy link

Report too large to display inline

View full report↗︎

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants