Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
chore: fix USDC signing for Hypercore transfers
  • Loading branch information
kyleleighton committed Oct 1, 2025
commit a98adc15ea31e1e70db63d4e3e0cf27eef3cdf5e
101 changes: 95 additions & 6 deletions src/routes/mayan/MayanRouteBase.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import type {
ComposableSuiMoveCallsOptions,
Quote as MayanQuote,
PermitDomain,
PermitTypes,
PermitValue,
QuoteOptions,
QuoteParams,
} from '@mayanfinance/swap-sdk';
import {
createSwapFromSolanaInstructions,
createSwapFromSuiMoveCalls,
generateFetchQuoteUrl,
getHyperCoreUSDCDepositPermitParams,
getSwapFromEvmTxPayload,
} from '@mayanfinance/swap-sdk';
import type { SuiClient } from '@mysten/sui/client';
Expand Down Expand Up @@ -62,6 +66,7 @@ import type { EvmChains } from '@wormhole-foundation/sdk-evm';
import {
EvmPlatform,
EvmUnsignedTransaction,
isEvmNativeSigner,
} from '@wormhole-foundation/sdk-evm';
import {
SolanaPlatform,
Expand All @@ -71,6 +76,7 @@ import {
SuiPlatform,
SuiUnsignedTransaction,
} from '@wormhole-foundation/sdk-sui';
import type { JsonRpcProvider } from 'ethers';
import axios from 'axios';
import { createTransactionRequest, getEvmContractAddress } from './evm/utils';
import { getAllTokenIdsForChain } from '../../utils/tokenHelpers';
Expand Down Expand Up @@ -244,6 +250,66 @@ export class MayanRouteBase<N extends Network> extends routes.AutomaticRoute<
return null;
}

private requiresHyperCorePermit(
request: routes.RouteTransferRequest<N>,
quote: Quote,
): boolean {
return (
MayanRouteBase.isHyperCore(request.toChain.chain) &&
quote.details?.hyperCoreParams !== undefined
);
}

private async maybeGetHyperCorePermitSignature(
request: routes.RouteTransferRequest<N>,
signer: Signer<N>,
quote: Quote,
destinationAddress: string,
): Promise<string | undefined> {
if (!this.requiresHyperCorePermit(request, quote)) return undefined;

const quoteDetails = quote.details;

if (!quoteDetails) {
throw new Error('Missing HyperCore quote details required for permit');
}

const arbitrumRpc = (await request.toChain.getRpc()) ?? null;

if (!arbitrumRpc) {
throw new Error('Could not resolve HyperCore RPC connection');
}

let domain: PermitDomain;
let types: typeof PermitTypes;
let value: PermitValue;

try {
({ domain, types, value } = await getHyperCoreUSDCDepositPermitParams(
quoteDetails,
destinationAddress,
arbitrumRpc,
));
} catch (e) {
throw new Error(
`Failed to fetch HyperCore USDC permit params: ${(e as Error).message}`,
);
}

if (typeof (signer as any).signTypedData === 'function') {
return await (signer as any).signTypedData(domain, types, value);
}

if (isEvmNativeSigner(signer)) {
const nativeSigner = signer.unwrap();
return await nativeSigner.signTypedData(domain, types, value);
}

throw new Error(
'Signer must support EIP-712 typed data signing to bridge USDC to HyperCore',
);
}

async validate(
request: routes.RouteTransferRequest<N>,
params: TransferParams,
Expand Down Expand Up @@ -710,8 +776,19 @@ export class MayanRouteBase<N extends Network> extends routes.AutomaticRoute<
const txs: TransactionId[] = [];
const rpc = await request.fromChain.getRpc();
const feeUnits = this.getFeeInBaseUnits(request, quote.params.amount);
const usdcPermitSignature = await this.maybeGetHyperCorePermitSignature(
request,
signer,
quote,
destinationAddress,
);

if (request.fromChain.chain === 'Solana') {
const solanaOptions = {
allowSwapperOffCurve: true,
...(usdcPermitSignature ? { usdcPermitSignature } : {}),
};

const { instructions, signers, lookupTables } =
await (this.isTestnetRequest(request)
? createSwapFromSolanaInstructionsTestnet(
Expand All @@ -720,15 +797,15 @@ export class MayanRouteBase<N extends Network> extends routes.AutomaticRoute<
destinationAddress,
null,
rpc,
{ allowSwapperOffCurve: true },
solanaOptions,
)
: createSwapFromSolanaInstructions(
quote.details!,
originAddress,
destinationAddress,
null,
rpc,
{ allowSwapperOffCurve: true },
solanaOptions,
));

const payerKey = new PublicKey(originAddress);
Expand Down Expand Up @@ -900,26 +977,38 @@ export class MayanRouteBase<N extends Network> extends routes.AutomaticRoute<
}
}

const quoteDetails = quote.details;

if (!quoteDetails) {
throw new Error('Missing Mayan quote details');
}

const mainnetOptions =
usdcPermitSignature !== undefined
? { usdcPermitSignature }
: undefined;

const mayanTxRequest = this.isTestnetRequest(request)
? getSwapFromEvmTxPayloadTestnet(
this.normalizeQuoteForTestnet(quote.details!),
this.normalizeQuoteForTestnet(quoteDetails),
originAddress,
destinationAddress,
null,
originAddress,
Number(nativeChainId!),
undefined,
undefined, // permit?
undefined,
)
: getSwapFromEvmTxPayload(
quote.details!,
quoteDetails,
originAddress,
destinationAddress,
null,
originAddress,
Number(nativeChainId!),
undefined,
undefined, // permit?
undefined,
mainnetOptions,
);

const txReq = createTransactionRequest(
Expand Down
119 changes: 117 additions & 2 deletions src/routes/sdkv2/signer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,23 @@ import type {
RpcConnection,
Platform,
} from '@wormhole-foundation/sdk';
import { chainToPlatform, amount } from '@wormhole-foundation/sdk';
import {
chainToPlatform,
amount,
nativeChainIds,
} from '@wormhole-foundation/sdk';
import { getEvmSigner } from '@wormhole-foundation/sdk-evm';
import { getSolanaSigner } from '@wormhole-foundation/sdk-solana';
import { getSuiSigner } from '@wormhole-foundation/sdk-sui';
import type { TypedDataDomain, TypedDataField } from 'ethers';
import type { EVMWallet } from '@wormhole-labs/wallet-aggregator-evm';
import { NotSupported } from '@wormhole-labs/wallet-aggregator-core';

import { getWormholeContextV2 } from 'config';
import type { TransferWallet } from 'utils/wallet';
import { TransferWallet } from 'utils/wallet';
import type { WormholeConnectWalletProvider } from 'utils/wallet/types';
import { sleep } from 'utils';
import config from 'config';

// Utility class that bridges between legacy Connect signer interface and SDKv2 signer interface
export class SDKv2Signer<N extends Network, C extends Chain>
Expand Down Expand Up @@ -139,6 +148,112 @@ export class SDKv2Signer<N extends Network, C extends Chain>
return txHashes;
}

async signTypedData(
domain: TypedDataDomain,
types: Record<string, TypedDataField[]>,
value: Record<string, unknown>,
): Promise<string> {
const expectedChainIdRaw = domain.chainId;

let expectedChainId: bigint | undefined;
if (expectedChainIdRaw !== undefined && expectedChainIdRaw !== null) {
expectedChainId =
typeof expectedChainIdRaw === 'bigint'
? expectedChainIdRaw
: typeof expectedChainIdRaw === 'string'
? BigInt(expectedChainIdRaw)
: BigInt(expectedChainIdRaw);
}

let targetChain: Chain | undefined;
if (expectedChainId !== undefined) {
const networkChain = nativeChainIds.platformNativeChainIdToNetworkChain(
'Evm',
expectedChainId,
);

if (networkChain) {
const [network, chain] = networkChain;
if (network === config.network) {
targetChain = chain as Chain;
}
}
}

let evmWallet: EVMWallet | undefined;
let walletChain: Chain | undefined;
if (chainToPlatform(this._chain) === 'Evm') {
evmWallet = this._walletProvider.getWallet(
this._chain,
this._walletType,
) as EVMWallet | undefined;
walletChain = this._chain;
}

if (!evmWallet && targetChain) {
walletChain = targetChain;
evmWallet = this._walletProvider.getWallet(
targetChain,
TransferWallet.RECEIVING,
) as EVMWallet | undefined;
}

if (!evmWallet || !walletChain) {
const chainLabel = walletChain ?? targetChain ?? 'the required EVM chain';
throw new Error(
`A connected destination wallet on ${chainLabel} is required to sign the USDC permit`,
);
}

const signer = await evmWallet.getSigner();

if (!signer) {
throw new Error('No signer found for typed data signing');
}

if (expectedChainId !== undefined) {
const signerChainId = (await signer.provider?.getNetwork())?.chainId;

if (signerChainId === undefined) {
throw new Error('Signer has no chainId');
}

if (signerChainId !== expectedChainId) {
try {
await evmWallet.switchChain(Number(expectedChainId));

let signerChainIdAfterSwitch: bigint | undefined = undefined;

for (let i = 0; i < 50; i++) {
signerChainIdAfterSwitch = (await signer.provider?.getNetwork())
?.chainId;

if (signerChainIdAfterSwitch === expectedChainId) {
break;
}

await sleep(100);
}

if (signerChainIdAfterSwitch !== expectedChainId) {
throw new Error(
'Failed to switch signer to the correct EVM chain for typed data signing',
);
}
} catch (e) {
if (e instanceof NotSupported) {
throw new Error(
'Selected EVM wallet does not support switching chains but has the wrong chain selected',
);
}
throw e;
}
}
}

return signer.signTypedData(domain, types, value);
}

chain() {
return this._chainContextV2.chain;
}
Expand Down