@paradex/sdk 0.10.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,103 @@
1
+ import { defaultApiUrl, fetchTransport, SessionApiError, } from './session-transport.js';
2
+ import { builderAddress, } from './session-typed-data.js';
3
+ /**
4
+ * Builder Codes reads: an owner's builder approvals (list and revoke) and
5
+ * the public builder stats and leaderboard.
6
+ *
7
+ * @experimental The request and response shapes may change.
8
+ */
9
+ export const BUILDER_APPROVALS_LIST_PATH = '/v2/builders/approvals';
10
+ /**
11
+ * Reads Builder Codes approvals and stats.
12
+ *
13
+ * Listing and revoking approvals needs the account owner's main-key JWT,
14
+ * passed as `token`; a session or subkey token is refused with 403, and
15
+ * listing is also refused for an account Paradex has not enabled sessions
16
+ * for. The stats and leaderboard are public. `fetchStats` answers 404 for a
17
+ * builder with no recorded stats, and both answer 404 while the server has
18
+ * no stats to serve at all.
19
+ *
20
+ * @experimental
21
+ */
22
+ export class BuilderCodesClient {
23
+ constructor(params) {
24
+ this.apiUrl = (params.apiUrl ?? defaultApiUrl(params.environment)).replace(/\/+$/, '');
25
+ this.transport = params.transport ?? fetchTransport;
26
+ }
27
+ /**
28
+ * `GET /v2/builders/approvals`: the account's live approvals, newest first;
29
+ * with `includeInactive` also its revoked and expired ones.
30
+ */
31
+ async listApprovals(token, options = {}) {
32
+ const query = options.includeInactive === true ? '?include_inactive=true' : '';
33
+ return await this.results({
34
+ method: 'GET',
35
+ url: `${this.apiUrl}${BUILDER_APPROVALS_LIST_PATH}${query}`,
36
+ headers: bearer(token),
37
+ });
38
+ }
39
+ /**
40
+ * `DELETE /v2/builders/approvals/{builder_account}`: new orders naming the
41
+ * builder are refused at once, on the account and its sub-accounts, and
42
+ * the resting orders naming it there are cancelled. Every session of the
43
+ * account that names the builder is revoked too, on every device. A
44
+ * builder with no live approval is a 404 `SessionApiError`.
45
+ */
46
+ async revokeApproval(token, builderAccount) {
47
+ await this.send({
48
+ method: 'DELETE',
49
+ url: `${this.apiUrl}${BUILDER_APPROVALS_LIST_PATH}/${builderAddress(builderAccount, 'builderAccount')}`,
50
+ headers: bearer(token),
51
+ });
52
+ }
53
+ /**
54
+ * `GET /v1/builders/{builder_account}/stats`: one row per window. A window
55
+ * with no paid fill, or with too few paying users, is zeros. Stats lag the
56
+ * fills they count.
57
+ */
58
+ async fetchStats(builderAccount) {
59
+ return await this.results({
60
+ method: 'GET',
61
+ url: `${this.apiUrl}/v1/builders/${builderAddress(builderAccount, 'builderAccount')}/stats`,
62
+ headers: {},
63
+ });
64
+ }
65
+ /**
66
+ * `GET /v1/builders/leaderboard`: builders ranked by `fees_paid` over one
67
+ * window, then by volume. The server's default window is `7d`, and it
68
+ * answers 400 for a window it does not serve.
69
+ */
70
+ async fetchLeaderboard(window) {
71
+ const query = window != null ? `?window=${encodeURIComponent(window)}` : '';
72
+ return await this.results({
73
+ method: 'GET',
74
+ url: `${this.apiUrl}/v1/builders/leaderboard${query}`,
75
+ headers: {},
76
+ });
77
+ }
78
+ async send(request) {
79
+ const response = await this.transport(request);
80
+ if (response.status < 200 || response.status >= 300) {
81
+ throw new SessionApiError(response.status, response.body);
82
+ }
83
+ return response.body;
84
+ }
85
+ async results(request) {
86
+ const body = await this.send(request);
87
+ const results = body?.results;
88
+ if (!Array.isArray(results)) {
89
+ throw new SessionApiError(200, {
90
+ error: 'INVALID_RESPONSE',
91
+ message: `${request.method} ${new URL(request.url).pathname} returned no results`,
92
+ });
93
+ }
94
+ return results;
95
+ }
96
+ }
97
+ /** The `Authorization` header for an account owner's JWT. */
98
+ export function bearer(token) {
99
+ if (typeof token !== 'string' || token === '') {
100
+ throw new Error("token must be the account owner's JWT");
101
+ }
102
+ return { Authorization: `Bearer ${token}` };
103
+ }
@@ -0,0 +1,101 @@
1
+ import * as Starknet from 'starknet';
2
+ import type { ReceivableAmount, SocializedLossFactor, WithdrawResult } from './client.js';
3
+ import type { ParadexConfig } from './config.js';
4
+ import { type EvmOwnerSigner } from './evm-owner-signer.js';
5
+ import { DefaultProvider } from './paraclear-provider.js';
6
+ /**
7
+ * L2 gas reserved for `__validate__` on an EIP-191 account. Validation runs
8
+ * keccak256 and a secp256k1 ecrecover in Cairo, a fixed cost of about 17.3M
9
+ * L2 gas whatever the call does; this leaves headroom over it.
10
+ */
11
+ export declare const EVM_VALIDATE_L2_GAS = 25000000n;
12
+ /**
13
+ * The fee is estimated with `SKIP_VALIDATE`, so the wallet is asked to sign
14
+ * once, not twice. The estimate then leaves out `__validate__`, whose cost
15
+ * is fixed, so it is added rather than scaled: a multiplier on a cheap
16
+ * call's estimate falls short of it and the transaction runs out of gas.
17
+ * Execution gets 50% headroom because the estimate runs at `pre_confirmed`
18
+ * and execution at inclusion can cost more.
19
+ */
20
+ export declare function withEvmValidationGas(bounds: Starknet.ResourceBoundsBN): Starknet.ResourceBoundsBN;
21
+ export interface CreateClientFromEvmOwnerParams {
22
+ readonly config: ParadexConfig;
23
+ /** The EVM wallet that owns the account. See `EvmOwnerSigner`. */
24
+ readonly signer: EvmOwnerSigner;
25
+ /**
26
+ * The EVM-owned account to act on. Defaults to the wallet's main account,
27
+ * looked up with `GET /onboarding?eth_address=…&account_signer_type=eip191`.
28
+ * Pass it for an EVM sub-account the same wallet owns.
29
+ */
30
+ readonly accountAddress?: string;
31
+ /**
32
+ * Paradex REST API base URL for the account lookup.
33
+ * Defaults to `config.paradexApiUrl`.
34
+ */
35
+ readonly apiUrl?: string;
36
+ }
37
+ /**
38
+ * Client for an EVM-owned (EIP-191) Paradex account, whose on-chain owner is
39
+ * an EVM wallet rather than a Stark key. Every transaction is signed by the
40
+ * owner wallet with `personal_sign` over the Starknet transaction hash.
41
+ *
42
+ * No Stark key is derived: `Client.fromEthSigner` derives a key for a
43
+ * different (Stark-owned) account and must not be used for these accounts.
44
+ *
45
+ * Balance reads (`getTokenBalance`, `getMaxWithdraw`) are not offered: the
46
+ * Paradex full node returns account data only to authenticated callers. Use
47
+ * the REST API (`GET /v1/balance`) with the account's JWT instead.
48
+ */
49
+ export declare class EvmOwnerClient {
50
+ private readonly config;
51
+ private readonly provider;
52
+ private readonly account;
53
+ private readonly ownerAddress;
54
+ private constructor();
55
+ static create({ config, signer, accountAddress, apiUrl, }: CreateClientFromEvmOwnerParams): Promise<EvmOwnerClient>;
56
+ /** The Paradex (Starknet) account address. */
57
+ getAddress(): string;
58
+ /** The EVM wallet that owns the account and signs its transactions. */
59
+ getOwnerAddress(): string;
60
+ getSocializedLossFactor(): Promise<SocializedLossFactor>;
61
+ /** The amount a withdrawal of `amount` delivers after socialized loss. */
62
+ getReceivableAmount(token: string, amount: string): Promise<ReceivableAmount>;
63
+ /**
64
+ * Withdraws `amount` of `token` from Paraclear and runs `bridgeCall` in the
65
+ * same atomic transaction, signed by the owner wallet (one signature
66
+ * prompt).
67
+ *
68
+ * `paraclear.withdraw` moves the funds to the account contract's own
69
+ * Starknet token balance; the bridge call must then move them out (for
70
+ * example `starkgateWithdrawCall`). Build it for the receivable amount
71
+ * from `getReceivableAmount`. Do not use `paraclear.transfer` as a bridge
72
+ * call: it credits another Paradex account's Paraclear balance, not the
73
+ * bridge.
74
+ */
75
+ withdraw(token: string, amount: string, bridgeCall: Starknet.Call | readonly Starknet.Call[]): Promise<WithdrawResult>;
76
+ /**
77
+ * Signs and sends any invoke from the account with the owner wallet.
78
+ * @advanced Prefer `withdraw`.
79
+ */
80
+ execute(calls: Starknet.Call | readonly Starknet.Call[]): Promise<WithdrawResult>;
81
+ waitForTransaction(txHash: string, options?: Starknet.waitForTransactionOptions): Promise<Starknet.GetTransactionReceiptResponse>;
82
+ /** The underlying provider (unauthenticated full-node RPC). */
83
+ getProvider(): DefaultProvider;
84
+ }
85
+ export interface StarkgateWithdrawCallParams {
86
+ readonly config: ParadexConfig;
87
+ /** Token symbol, e.g. `'USDC'`. */
88
+ readonly token: string;
89
+ /** Ethereum (L1) address that receives the funds. */
90
+ readonly l1Recipient: string;
91
+ /**
92
+ * Amount in the token's own decimals, normally `receivableAmountChain`
93
+ * from `getReceivableAmount`.
94
+ */
95
+ readonly amountChain: string;
96
+ }
97
+ /**
98
+ * The StarkGate bridge call that sends a withdrawn amount to Ethereum: the
99
+ * funds are claimable on L1 once the Starknet block is proven there.
100
+ */
101
+ export declare function starkgateWithdrawCall({ config, token, l1Recipient, amountChain, }: StarkgateWithdrawCallParams): Starknet.Call;
@@ -0,0 +1,191 @@
1
+ import { BigNumber } from 'bignumber.js';
2
+ import * as Starknet from 'starknet';
3
+ import { fetchOnboarding } from './account.js';
4
+ import { createEip191StarknetSigner, } from './evm-owner-signer.js';
5
+ import { DefaultProvider } from './paraclear-provider.js';
6
+ import * as Paraclear from './paraclear.js';
7
+ /**
8
+ * L2 gas reserved for `__validate__` on an EIP-191 account. Validation runs
9
+ * keccak256 and a secp256k1 ecrecover in Cairo, a fixed cost of about 17.3M
10
+ * L2 gas whatever the call does; this leaves headroom over it.
11
+ */
12
+ export const EVM_VALIDATE_L2_GAS = 25000000n;
13
+ /**
14
+ * The fee is estimated with `SKIP_VALIDATE`, so the wallet is asked to sign
15
+ * once, not twice. The estimate then leaves out `__validate__`, whose cost
16
+ * is fixed, so it is added rather than scaled: a multiplier on a cheap
17
+ * call's estimate falls short of it and the transaction runs out of gas.
18
+ * Execution gets 50% headroom because the estimate runs at `pre_confirmed`
19
+ * and execution at inclusion can cost more.
20
+ */
21
+ export function withEvmValidationGas(bounds) {
22
+ const estimated = BigInt(bounds.l2_gas.max_amount);
23
+ return {
24
+ ...bounds,
25
+ l2_gas: {
26
+ ...bounds.l2_gas,
27
+ max_amount: (estimated * 3n) / 2n + EVM_VALIDATE_L2_GAS,
28
+ },
29
+ };
30
+ }
31
+ /**
32
+ * Client for an EVM-owned (EIP-191) Paradex account, whose on-chain owner is
33
+ * an EVM wallet rather than a Stark key. Every transaction is signed by the
34
+ * owner wallet with `personal_sign` over the Starknet transaction hash.
35
+ *
36
+ * No Stark key is derived: `Client.fromEthSigner` derives a key for a
37
+ * different (Stark-owned) account and must not be used for these accounts.
38
+ *
39
+ * Balance reads (`getTokenBalance`, `getMaxWithdraw`) are not offered: the
40
+ * Paradex full node returns account data only to authenticated callers. Use
41
+ * the REST API (`GET /v1/balance`) with the account's JWT instead.
42
+ */
43
+ export class EvmOwnerClient {
44
+ constructor(config, provider, account, ownerAddress) {
45
+ this.config = config;
46
+ this.provider = provider;
47
+ this.account = account;
48
+ this.ownerAddress = ownerAddress;
49
+ }
50
+ static async create({ config, signer, accountAddress, apiUrl, }) {
51
+ const ownerAddress = await signer.getAddress();
52
+ if (!/^0x[0-9a-fA-F]{40}$/.test(ownerAddress)) {
53
+ throw new Error('EVM owner signer returned an invalid address; expected a 0x-prefixed 20-byte address');
54
+ }
55
+ const address = accountAddress ?? (await lookupAccount());
56
+ if (!/^0x[0-9a-fA-F]{1,64}$/.test(address)) {
57
+ throw new Error('accountAddress must be a 0x-prefixed Starknet address');
58
+ }
59
+ // No credentials: the provider never signs full-node auth headers, which
60
+ // need a Stark key this account does not have.
61
+ const provider = new DefaultProvider(config);
62
+ const account = new Starknet.Account({
63
+ provider,
64
+ address,
65
+ signer: createEip191StarknetSigner(signer, ownerAddress),
66
+ });
67
+ return new EvmOwnerClient(config, provider, account, ownerAddress);
68
+ async function lookupAccount() {
69
+ const resolvedApiUrl = apiUrl ?? config.paradexApiUrl;
70
+ if (resolvedApiUrl == null || resolvedApiUrl === '') {
71
+ throw new Error('Looking up the account needs an API URL: pass apiUrl or accountAddress, or use a config from Config.fetch()');
72
+ }
73
+ const info = await fetchOnboarding({
74
+ apiUrl: resolvedApiUrl,
75
+ ethAddress: ownerAddress,
76
+ });
77
+ if (info.accountSignerType !== 'eip191') {
78
+ throw new Error(`The wallet's Paradex account is not EVM-owned (signer type ${info.accountSignerType}); use Client.fromEthSigner`);
79
+ }
80
+ if (!info.exists) {
81
+ throw new Error('This wallet has no EVM-owned Paradex account yet; onboard it in the Paradex app first');
82
+ }
83
+ return info.address;
84
+ }
85
+ }
86
+ /** The Paradex (Starknet) account address. */
87
+ getAddress() {
88
+ return this.account.address;
89
+ }
90
+ /** The EVM wallet that owns the account and signs its transactions. */
91
+ getOwnerAddress() {
92
+ return this.ownerAddress;
93
+ }
94
+ async getSocializedLossFactor() {
95
+ return await Paraclear.getSocializedLossFactor({
96
+ provider: this.provider,
97
+ config: this.config,
98
+ });
99
+ }
100
+ /** The amount a withdrawal of `amount` delivers after socialized loss. */
101
+ async getReceivableAmount(token, amount) {
102
+ return await Paraclear.getReceivableAmount({
103
+ provider: this.provider,
104
+ config: this.config,
105
+ token,
106
+ amount,
107
+ });
108
+ }
109
+ /**
110
+ * Withdraws `amount` of `token` from Paraclear and runs `bridgeCall` in the
111
+ * same atomic transaction, signed by the owner wallet (one signature
112
+ * prompt).
113
+ *
114
+ * `paraclear.withdraw` moves the funds to the account contract's own
115
+ * Starknet token balance; the bridge call must then move them out (for
116
+ * example `starkgateWithdrawCall`). Build it for the receivable amount
117
+ * from `getReceivableAmount`. Do not use `paraclear.transfer` as a bridge
118
+ * call: it credits another Paradex account's Paraclear balance, not the
119
+ * bridge.
120
+ */
121
+ async withdraw(token, amount, bridgeCall) {
122
+ const amountBn = new BigNumber(amount);
123
+ if (amountBn.isNaN() || !amountBn.isGreaterThan(0)) {
124
+ throw new Error('Invalid amount');
125
+ }
126
+ const calls = Paraclear.buildWithdrawCalls({
127
+ config: this.config,
128
+ token,
129
+ amount,
130
+ bridgeCall,
131
+ });
132
+ return await this.execute(calls);
133
+ }
134
+ /**
135
+ * Signs and sends any invoke from the account with the owner wallet.
136
+ * @advanced Prefer `withdraw`.
137
+ */
138
+ async execute(calls) {
139
+ const batch = Array.isArray(calls)
140
+ ? [...calls]
141
+ : [calls];
142
+ const blockIdentifier = Starknet.BlockTag.PRE_CONFIRMED;
143
+ const nonce = await this.account.getNonce(blockIdentifier);
144
+ const fees = await this.account.estimateInvokeFee(batch, {
145
+ blockIdentifier,
146
+ nonce,
147
+ tip: 0n,
148
+ skipValidate: true,
149
+ });
150
+ const result = await this.account.execute(batch, {
151
+ nonce,
152
+ tip: 0n,
153
+ resourceBounds: withEvmValidationGas(fees.resourceBounds),
154
+ });
155
+ return { hash: result.transaction_hash };
156
+ }
157
+ async waitForTransaction(txHash, options) {
158
+ return await this.provider.waitForTransaction(txHash, options);
159
+ }
160
+ /** The underlying provider (unauthenticated full-node RPC). */
161
+ getProvider() {
162
+ return this.provider;
163
+ }
164
+ }
165
+ /**
166
+ * The StarkGate bridge call that sends a withdrawn amount to Ethereum: the
167
+ * funds are claimable on L1 once the Starknet block is proven there.
168
+ */
169
+ export function starkgateWithdrawCall({ config, token, l1Recipient, amountChain, }) {
170
+ const tokenConfig = config.bridgedTokens[token];
171
+ if (tokenConfig == null) {
172
+ throw new Error(`Token ${token} is not supported`);
173
+ }
174
+ if (!/^0x[0-9a-fA-F]{40}$/.test(l1Recipient)) {
175
+ throw new Error('l1Recipient must be a 0x-prefixed 20-byte address');
176
+ }
177
+ if (!/^[0-9]+$/.test(amountChain) || BigInt(amountChain) === 0n) {
178
+ throw new Error('amountChain must be a positive integer string');
179
+ }
180
+ const amount = Starknet.uint256.bnToUint256(amountChain);
181
+ return {
182
+ contractAddress: tokenConfig.l2BridgeAddress,
183
+ entrypoint: 'initiate_token_withdraw',
184
+ calldata: [
185
+ tokenConfig.l1TokenAddress,
186
+ l1Recipient,
187
+ Starknet.num.toHex(amount.low),
188
+ Starknet.num.toHex(amount.high),
189
+ ],
190
+ };
191
+ }
@@ -0,0 +1,81 @@
1
+ import type { ethers } from 'ethers';
2
+ import * as Starknet from 'starknet';
3
+ import type { Eip1193Provider } from './session-owner-signer.js';
4
+ import type { Hex } from './types.js';
5
+ /**
6
+ * The EVM wallet that owns an EVM-owned (EIP-191) Paradex account.
7
+ *
8
+ * The account contract (Argent v0.5, `Eip191` owner) accepts a transaction
9
+ * when the owner wallet `personal_sign`s its 32-byte Starknet transaction
10
+ * hash, so this is all the SDK needs from the wallet. No Stark key is
11
+ * derived or used.
12
+ *
13
+ * Adapters: {@link evmOwnerSignerFromEthers}, {@link evmOwnerSignerFromViem},
14
+ * {@link evmOwnerSignerFromEip1193}. A custom signer (an MPC or embedded
15
+ * wallet API) must sign the 32 bytes as bytes, not their hex spelling as
16
+ * text.
17
+ */
18
+ export interface EvmOwnerSigner {
19
+ /** The owner wallet's address. */
20
+ readonly getAddress: () => Promise<string>;
21
+ /**
22
+ * EIP-191 `personal_sign` over `message`, the 32 raw bytes of the
23
+ * transaction hash: the wallet signs
24
+ * `keccak256("\x19Ethereum Signed Message:\n32" ‖ message)`.
25
+ * Must return a 65-byte `r‖s‖v` hex signature.
26
+ */
27
+ readonly signMessage: (message: Uint8Array) => Promise<string>;
28
+ }
29
+ /** Uses an ethers v6 `Signer` (e.g. `Wallet`, `BrowserProvider.getSigner()`). */
30
+ export declare function evmOwnerSignerFromEthers(signer: ethers.Signer): EvmOwnerSigner;
31
+ /** The subset of a viem `WalletClient` (or `LocalAccount`) used here. */
32
+ export interface ViemMessageSigner {
33
+ readonly signMessage: (args: {
34
+ readonly account?: any;
35
+ readonly message: {
36
+ readonly raw: Hex;
37
+ };
38
+ }) => Promise<string>;
39
+ }
40
+ export interface EvmOwnerSignerFromViemParams {
41
+ /** A viem `WalletClient`, or a `LocalAccount` such as `privateKeyToAccount`. */
42
+ readonly client: ViemMessageSigner;
43
+ /** The owner wallet address, or the viem `Account` to sign with. */
44
+ readonly account: string | {
45
+ readonly address: string;
46
+ };
47
+ }
48
+ /** Uses a viem `WalletClient` or `LocalAccount`. */
49
+ export declare function evmOwnerSignerFromViem({ client, account, }: EvmOwnerSignerFromViemParams): EvmOwnerSigner;
50
+ export interface EvmOwnerSignerFromEip1193Params {
51
+ readonly provider: Eip1193Provider;
52
+ /** The owner wallet address. Defaults to the wallet's first account. */
53
+ readonly address?: string;
54
+ }
55
+ /**
56
+ * Uses an injected wallet (`window.ethereum`), a Privy embedded wallet's
57
+ * EIP-1193 provider, or any other EIP-1193 provider, via `personal_sign`.
58
+ */
59
+ export declare function evmOwnerSignerFromEip1193({ provider, address, }: EvmOwnerSignerFromEip1193Params): EvmOwnerSigner;
60
+ /**
61
+ * A Starknet `SignerInterface` for an Argent v0.5 account whose owner is an
62
+ * `Eip191` signer. Signs invoke transactions only.
63
+ *
64
+ * Each signature is checked to recover to `ownerAddress` before it is
65
+ * returned, so a wallet that signs the wrong bytes fails here with a clear
66
+ * error instead of as an on-chain validation failure.
67
+ *
68
+ * @internal Use `Client.fromEvmOwner()`.
69
+ */
70
+ export declare function createEip191StarknetSigner(owner: EvmOwnerSigner, ownerAddress: string): Starknet.SignerInterface;
71
+ /** The transaction hash as 32 big-endian bytes, the message the contract checks. */
72
+ export declare function txHashBytes(txHash: Starknet.BigNumberish): Uint8Array;
73
+ /**
74
+ * Encodes a 65-byte EVM signature as the Argent v0.5 account signature:
75
+ * `[1, Eip191 = 3, eth_address, r.low, r.high, s.low, s.high, y_parity]`
76
+ * (one owner signature, no guardian).
77
+ *
78
+ * A high-s signature is converted to its low-s form. Throws unless the
79
+ * signature recovers to `ownerAddress` over the EIP-191 hash of `txHash`.
80
+ */
81
+ export declare function formatEip191Signature(ownerAddress: string, txHash: Starknet.BigNumberish, signatureHex: string): string[];
@@ -0,0 +1,165 @@
1
+ import { secp256k1 } from '@noble/curves/secp256k1';
2
+ import { keccak_256 } from '@noble/hashes/sha3';
3
+ import * as Starknet from 'starknet';
4
+ /** Uses an ethers v6 `Signer` (e.g. `Wallet`, `BrowserProvider.getSigner()`). */
5
+ export function evmOwnerSignerFromEthers(signer) {
6
+ return {
7
+ getAddress: async () => await signer.getAddress(),
8
+ // A Uint8Array is signed as bytes; a string would be signed as UTF-8.
9
+ signMessage: async (message) => await signer.signMessage(message),
10
+ };
11
+ }
12
+ /** Uses a viem `WalletClient` or `LocalAccount`. */
13
+ export function evmOwnerSignerFromViem({ client, account, }) {
14
+ const address = typeof account === 'string' ? account : account.address;
15
+ return {
16
+ getAddress: async () => address,
17
+ signMessage: async (message) => await client.signMessage({
18
+ account,
19
+ message: { raw: bytesToHex(message) },
20
+ }),
21
+ };
22
+ }
23
+ /**
24
+ * Uses an injected wallet (`window.ethereum`), a Privy embedded wallet's
25
+ * EIP-1193 provider, or any other EIP-1193 provider, via `personal_sign`.
26
+ */
27
+ export function evmOwnerSignerFromEip1193({ provider, address, }) {
28
+ const getAddress = async () => {
29
+ if (address != null)
30
+ return address;
31
+ const accounts = await provider.request({ method: 'eth_requestAccounts' });
32
+ const first = Array.isArray(accounts) ? accounts[0] : undefined;
33
+ if (typeof first !== 'string') {
34
+ throw new Error('Wallet returned no accounts');
35
+ }
36
+ return first;
37
+ };
38
+ return {
39
+ getAddress,
40
+ signMessage: async (message) => {
41
+ const signature = await provider.request({
42
+ method: 'personal_sign',
43
+ params: [bytesToHex(message), await getAddress()],
44
+ });
45
+ if (typeof signature !== 'string') {
46
+ throw new Error('Wallet returned a non-string signature');
47
+ }
48
+ return signature;
49
+ },
50
+ };
51
+ }
52
+ /**
53
+ * A Starknet `SignerInterface` for an Argent v0.5 account whose owner is an
54
+ * `Eip191` signer. Signs invoke transactions only.
55
+ *
56
+ * Each signature is checked to recover to `ownerAddress` before it is
57
+ * returned, so a wallet that signs the wrong bytes fails here with a clear
58
+ * error instead of as an on-chain validation failure.
59
+ *
60
+ * @internal Use `Client.fromEvmOwner()`.
61
+ */
62
+ export function createEip191StarknetSigner(owner, ownerAddress) {
63
+ const unsupported = (what) => async () => {
64
+ throw new Error(`EVM owner signer cannot sign ${what}`);
65
+ };
66
+ return {
67
+ getPubKey: async () => '0x0',
68
+ signMessage: unsupported('Starknet typed data'),
69
+ signDeployAccountTransaction: unsupported('deploy account transactions'),
70
+ signDeclareTransaction: unsupported('declare transactions'),
71
+ async signTransaction(transactions, details) {
72
+ if (!('resourceBounds' in details)) {
73
+ throw new Error('EVM owner signer signs V3 transactions only');
74
+ }
75
+ const compiledCalldata = Starknet.transaction.getExecuteCalldata(transactions, details.cairoVersion);
76
+ const txHash = Starknet.hash.calculateInvokeTransactionHash({
77
+ senderAddress: details.walletAddress,
78
+ version: details.version,
79
+ compiledCalldata,
80
+ chainId: details.chainId,
81
+ nonce: details.nonce,
82
+ accountDeploymentData: details.accountDeploymentData,
83
+ nonceDataAvailabilityMode: Starknet.stark.intDAM(details.nonceDataAvailabilityMode),
84
+ feeDataAvailabilityMode: Starknet.stark.intDAM(details.feeDataAvailabilityMode),
85
+ resourceBounds: details.resourceBounds,
86
+ tip: details.tip,
87
+ paymasterData: details.paymasterData,
88
+ });
89
+ const signature = await owner.signMessage(txHashBytes(txHash));
90
+ return formatEip191Signature(ownerAddress, txHash, signature);
91
+ },
92
+ };
93
+ }
94
+ /** The transaction hash as 32 big-endian bytes, the message the contract checks. */
95
+ export function txHashBytes(txHash) {
96
+ const hex = BigInt(txHash).toString(16).padStart(64, '0');
97
+ if (hex.length !== 64)
98
+ throw new Error('Transaction hash exceeds 32 bytes');
99
+ return hexToBytes(hex);
100
+ }
101
+ /**
102
+ * Encodes a 65-byte EVM signature as the Argent v0.5 account signature:
103
+ * `[1, Eip191 = 3, eth_address, r.low, r.high, s.low, s.high, y_parity]`
104
+ * (one owner signature, no guardian).
105
+ *
106
+ * A high-s signature is converted to its low-s form. Throws unless the
107
+ * signature recovers to `ownerAddress` over the EIP-191 hash of `txHash`.
108
+ */
109
+ export function formatEip191Signature(ownerAddress, txHash, signatureHex) {
110
+ const sig = signatureHex.replace(/^0x/, '');
111
+ if (!/^[0-9a-fA-F]{130}$/.test(sig)) {
112
+ throw new Error('Owner signature must be a 65-byte EOA signature; contract wallets are not supported');
113
+ }
114
+ const r = BigInt(`0x${sig.slice(0, 64)}`);
115
+ let s = BigInt(`0x${sig.slice(64, 128)}`);
116
+ const v = parseInt(sig.slice(128, 130), 16);
117
+ let yParity = v >= 27 ? v - 27 : v;
118
+ if (yParity !== 0 && yParity !== 1) {
119
+ throw new Error(`Owner signature has an invalid v: ${v}`);
120
+ }
121
+ // The account accepts only low-s. A high-s signature is the same signature
122
+ // as (n - s) with the other parity, so convert it rather than fail on chain.
123
+ const n = secp256k1.CURVE.n;
124
+ if (s > n / 2n) {
125
+ s = n - s;
126
+ yParity ^= 1;
127
+ }
128
+ const recovered = recoverEip191Address(txHashBytes(txHash), r, s, yParity);
129
+ if (recovered.toLowerCase() !== ownerAddress.toLowerCase()) {
130
+ throw new Error(`Owner signature recovers to ${recovered}, not the account owner ${ownerAddress}. ` +
131
+ 'The wallet must personal_sign the 32 hash bytes, not their hex text.');
132
+ }
133
+ const rU = Starknet.uint256.bnToUint256(r);
134
+ const sU = Starknet.uint256.bnToUint256(s);
135
+ return [
136
+ '0x1',
137
+ '0x3',
138
+ Starknet.num.toHex(ownerAddress),
139
+ Starknet.num.toHex(rU.low),
140
+ Starknet.num.toHex(rU.high),
141
+ Starknet.num.toHex(sU.low),
142
+ Starknet.num.toHex(sU.high),
143
+ Starknet.num.toHex(yParity),
144
+ ];
145
+ }
146
+ function recoverEip191Address(message, r, s, recovery) {
147
+ const prefix = new TextEncoder().encode(`\x19Ethereum Signed Message:\n${message.length}`);
148
+ const digest = keccak_256(new Uint8Array([...prefix, ...message]));
149
+ const publicKey = new secp256k1.Signature(r, s)
150
+ .addRecoveryBit(recovery)
151
+ .recoverPublicKey(digest)
152
+ .toRawBytes(false);
153
+ const address = keccak_256(publicKey.slice(1)).slice(-20);
154
+ return bytesToHex(address);
155
+ }
156
+ function bytesToHex(bytes) {
157
+ return `0x${Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')}`;
158
+ }
159
+ function hexToBytes(hex) {
160
+ const out = new Uint8Array(hex.length / 2);
161
+ for (let i = 0; i < out.length; i++) {
162
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
163
+ }
164
+ return out;
165
+ }