Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/strong-books-call.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@reservoir0x/relay-sdk': patch
'@reservoir0x/relay-kit-ui': patch
---

Add hyperliquid usd send functionality
1 change: 1 addition & 0 deletions demo/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ const AppWrapper: FC<AppWrapperProps> = ({ children, dynamicChains }) => {
Chain,
...Chain[]
]

const wagmiConfig = createConfig({
chains: viemChains,
multiInjectedProviderDiscovery: false,
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk/src/utils/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const configureViemChain = (
chain: RelayAPIChain
): RelayChain & Required<Pick<RelayChain, 'viemChain'>> => {
let viemChain: Chain
const overriddenChains = [999]
const overriddenChains = [999, 1337]
const staticChain = overriddenChains.includes(chain.id)
? undefined
: viemChainMap[chain.id]
Expand Down
183 changes: 102 additions & 81 deletions packages/sdk/src/utils/executeSteps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type {
SignatureStepItem
} from '../types/index.js'
import { pollUntilHasData, pollUntilOk } from './pollApi.js'
import { axios } from '../utils/index.js'
import { axios, prepareHyperliquidSignatureStep } from '../utils/index.js'
import type { AxiosRequestConfig } from 'axios'
import { getClient } from '../client.js'
import { LogLevel } from '../utils/logger.js'
Expand All @@ -14,6 +14,7 @@ import {
canBatchTransactions,
prepareBatchTransaction
} from './prepareBatchTransaction.js'
import { sendUsd } from './hyperliquid.js'

export type SetStateData = Pick<
Execute,
Expand Down Expand Up @@ -91,6 +92,20 @@ export async function executeSteps(
}
}

//Check if Hyperliquid and if so, rewrite steps to become a signature step
if (
chainId === 1337 &&
json.steps[0] &&
(json.steps[0].id as any) !== 'sign'
) {
const activeWalletChainId = await wallet?.getChainId()
const signatureStep = prepareHyperliquidSignatureStep(
json.steps,
activeWalletChainId
)
json.steps = [signatureStep]
}

// Update state on first call or recursion
setState({
steps: [...json?.steps],
Expand Down Expand Up @@ -345,6 +360,11 @@ export async function executeSteps(
}
}

//Special Logic for Hyperliquid to send signature
if (chainId === 1337 && signature) {
await sendUsd(client, signature, stepItem)
}

if (postData) {
client.log(['Execute Steps: Posting order'], LogLevel.Verbose)
stepItem.progressState = 'posting'
Expand Down Expand Up @@ -405,86 +425,6 @@ export async function executeSteps(
break
}

// If check, poll check until validated
if (stepItem?.check) {
stepItem.progressState = 'validating'
setState({
steps: [...json.steps],
fees: { ...json?.fees },
breakdown: json?.breakdown,
details: json?.details
})
stepItem.isValidatingSignature = true
setState({
steps: [...json?.steps],
fees: { ...json?.fees },
breakdown: json?.breakdown,
details: json?.details
})

await pollUntilOk(
{
url: `${request.baseURL}${stepItem?.check.endpoint}`,
method: stepItem?.check.method,
headers
},
(res) => {
client.log(
[
`Execute Steps: Polling execute status to check if indexed`,
res
],
LogLevel.Verbose
)

//set status
if (
res?.data?.status === 'success' &&
res?.data?.txHashes
) {
const chainTxHashes: NonNullable<
Execute['steps'][0]['items']
>[0]['txHashes'] = res.data?.txHashes?.map(
(hash: string) => {
return {
txHash: hash,
chainId:
res.data.destinationChainId ?? chain?.id
}
}
)

if (res?.data?.inTxHashes) {
const chainInTxHashes: NonNullable<
Execute['steps'][0]['items']
>[0]['txHashes'] = res.data?.inTxHashes?.map(
(hash: string) => {
return {
txHash: hash,
chainId: chain?.id ?? res.data.originChainId
}
}
)
stepItem.internalTxHashes = chainInTxHashes
}
stepItem.txHashes = chainTxHashes

return true
} else if (res?.data?.status === 'failure') {
throw Error(
res?.data?.details || 'Transaction failed'
)
} else if (res?.data?.status === 'delayed') {
stepItem.progressState = 'validating_delayed'
}
return false
},
maximumAttempts,
0,
pollingInterval
)
}

if (res.status > 299 || res.status < 200) throw res.data

if (res.data.results) {
Expand All @@ -509,6 +449,87 @@ export async function executeSteps(
}
}

// If check, poll check until validated
if (stepItem?.check) {
stepItem.progressState = 'validating'
setState({
steps: [...json.steps],
fees: { ...json?.fees },
breakdown: json?.breakdown,
details: json?.details
})
stepItem.isValidatingSignature = true
setState({
steps: [...json?.steps],
fees: { ...json?.fees },
breakdown: json?.breakdown,
details: json?.details
})

const headers = {
'Content-Type': 'application/json'
}

await pollUntilOk(
{
url: `${request.baseURL}${stepItem?.check.endpoint}`,
method: stepItem?.check.method,
headers
},
(res) => {
client.log(
[
`Execute Steps: Polling execute status to check if indexed`,
res
],
LogLevel.Verbose
)

//set status
if (
res?.data?.status === 'success' &&
res?.data?.txHashes
) {
const chainTxHashes: NonNullable<
Execute['steps'][0]['items']
>[0]['txHashes'] = res.data?.txHashes?.map(
(hash: string) => {
return {
txHash: hash,
chainId: res.data.destinationChainId ?? chain?.id
}
}
)

if (res?.data?.inTxHashes) {
const chainInTxHashes: NonNullable<
Execute['steps'][0]['items']
>[0]['txHashes'] = res.data?.inTxHashes?.map(
(hash: string) => {
return {
txHash: hash,
chainId: chain?.id ?? res.data.originChainId
}
}
)
stepItem.internalTxHashes = chainInTxHashes
}
stepItem.txHashes = chainTxHashes

return true
} else if (res?.data?.status === 'failure') {
throw Error(res?.data?.details || 'Transaction failed')
} else if (res?.data?.status === 'delayed') {
stepItem.progressState = 'validating_delayed'
}
return false
},
maximumAttempts,
0,
pollingInterval
)
}

break
}

Expand Down
109 changes: 109 additions & 0 deletions packages/sdk/src/utils/hyperliquid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { parseSignature } from 'viem'
import type { Execute } from '../types/Execute.js'
import axios from 'axios'
import type { RelayClient } from '../client.js'
import { LogLevel } from './logger.js'

export function prepareHyperliquidSignatureStep(
steps: Execute['steps'],
chainId: number
) {
const items = steps[0]?.items
const amount = items[0]?.data?.action?.parameters?.amount
const destination = items[0]?.data?.action?.parameters?.destination
const signatureStep = {
id: 'sign' as any,
action: 'Confirm transaction in your wallet',
description: `Sign a message to confirm the transaction`,
kind: 'signature' as const,
items: [
{
status: 'incomplete' as 'incomplete' | 'complete',
data: {
sign: {
signatureKind: 'eip712',
domain: {
name: 'HyperliquidSignTransaction',
version: '1',
chainId: chainId,
verifyingContract: '0x0000000000000000000000000000000000000000'
},
types: {
'HyperliquidTransaction:UsdSend': [
{ name: 'hyperliquidChain', type: 'string' },
{ name: 'destination', type: 'string' },
{ name: 'amount', type: 'string' },
{ name: 'time', type: 'uint64' }
],
EIP712Domain: [
{ name: 'name', type: 'string' },
{ name: 'version', type: 'string' },
{ name: 'chainId', type: 'uint256' },
{ name: 'verifyingContract', type: 'address' }
]
},
primaryType: 'HyperliquidTransaction:UsdSend',
value: {
type: 'usdSend',
signatureChainId: `0x${chainId.toString(16)}`,
hyperliquidChain: 'Mainnet',
destination: destination?.toLowerCase(),
amount,
time: new Date().getTime()
}
}
},
check: {
endpoint: `/intents/status?requestId=${steps[0]?.requestId}`,
method: 'GET'
}
}
],
requestId: steps[0]?.requestId,
depositAddress: steps[0]?.depositAddress
}

return signatureStep
}

export async function sendUsd(
client: RelayClient,
signature: string,
stepItem: Execute['steps'][0]['items'][0]
) {
client.log(
['Execute Steps: Sending signature to Hyperliquid', signature],
LogLevel.Verbose
)
const { r, s, v } = parseSignature(signature as `0x${string}`)
const currentTime = stepItem?.data?.sign?.value?.time ?? new Date().getTime()
const res = await axios.post('https://api.hyperliquid.xyz/exchange', {
signature: {
r,
s,
v: Number(v ?? 0n)
},
nonce: currentTime,
action: {
type: stepItem?.data?.sign?.value?.type,
signatureChainId: `0x${stepItem?.data?.sign?.domain?.chainId?.toString(16)}`,
hyperliquidChain: 'Mainnet',
destination: stepItem?.data?.sign?.value?.destination?.toLowerCase(),
amount: stepItem?.data?.sign?.value?.amount,
time: currentTime
}
})
if (
!res ||
!res.data ||
(res && res.status !== 200) ||
res.data.status != 'ok'
) {
throw 'Failed to send signature to HyperLiquid'
}
client.log(
['Execute Steps: Signature sent to Hyperliquid', res.data],
LogLevel.Verbose
)
return res.data
}
1 change: 1 addition & 0 deletions packages/sdk/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ export {
} from './simulateContract.js'
export { safeStructuredClone } from './structuredClone.js'
export { repeatUntilOk } from './repeatUntilOk.js'
export { prepareHyperliquidSignatureStep } from './hyperliquid.js'
10 changes: 7 additions & 3 deletions packages/sdk/src/utils/viemWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,18 @@ export const adaptViemWallet = (wallet: WalletClient): AdaptedWallet => {
})
}
} else if (signData.signatureKind === 'eip712') {
client.log(['Execute Steps: Signing with eip712'], LogLevel.Verbose)
signature = await wallet.signTypedData({
const signatureData = {
account: wallet.account as Account,
domain: signData.domain as any,
types: signData.types as any,
primaryType: signData.primaryType,
message: signData.value
})
}
client.log(
['Execute Steps: Signing with eip712', signatureData],
LogLevel.Verbose
)
signature = await wallet.signTypedData(signatureData)
}
}
return signature
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ const TokenSelector: FC<TokenSelectorProps> = ({
(chain.vmType === 'evm' ||
chain.vmType === 'suivm' ||
chain.vmType === 'tvm' ||
chain.vmType === 'hypevm' ||
chain.id === solana.id ||
chain.id === eclipse.id ||
chain.id === bitcoin.id) &&
Expand Down
Loading