near-safe 0.4.2 → 0.5.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.
@@ -3,7 +3,7 @@ import { FinalExecutionOutcome } from "near-api-js/lib/providers";
3
3
  import { NearEthAdapter, SignRequestData } from "near-ca";
4
4
  import { Address, Hash, Hex } from "viem";
5
5
  import { SafeContractSuite } from "./lib/safe";
6
- import { EncodedTxData, EvmTransactionData, MetaTransaction, UserOperation, UserOperationReceipt } from "./types";
6
+ import { DecodedMultisend, EncodedTxData, EvmTransactionData, MetaTransaction, UserOperation, UserOperationReceipt } from "./types";
7
7
  export interface NearSafeConfig {
8
8
  accountId: string;
9
9
  mpcContractId: string;
@@ -19,33 +19,150 @@ export declare class NearSafe {
19
19
  private setup;
20
20
  private pimlicoKey;
21
21
  private safeSaltNonce;
22
+ /**
23
+ * Creates a new instance of the `NearSafe` class using the provided configuration.
24
+ *
25
+ * @param {NearSafeConfig} config - The configuration object required to initialize the `NearSafe` instance, including the Pimlico key and safe salt nonce.
26
+ * @returns {Promise<NearSafe>} - A promise that resolves to a new `NearSafe` instance.
27
+ */
22
28
  static create(config: NearSafeConfig): Promise<NearSafe>;
29
+ /**
30
+ * Constructs a new `NearSafe` object with the provided parameters.
31
+ *
32
+ * @param {NearEthAdapter} nearAdapter - The NEAR adapter used for interacting with the NEAR blockchain.
33
+ * @param {SafeContractSuite} safePack - A suite of contracts and utilities for managing the Safe contract.
34
+ * @param {string} pimlicoKey - A key required for authenticating with the Pimlico service.
35
+ * @param {string} setup - The setup string generated for the Safe contract.
36
+ * @param {Address} safeAddress - The address of the deployed Safe contract.
37
+ * @param {string} safeSaltNonce - A unique nonce used to differentiate the Safe setup.
38
+ */
23
39
  constructor(nearAdapter: NearEthAdapter, safePack: SafeContractSuite, pimlicoKey: string, setup: string, safeAddress: Address, safeSaltNonce: string);
40
+ /**
41
+ * Retrieves the MPC (Multi-Party Computation) address associated with the NEAR adapter.
42
+ *
43
+ * @returns {Address} - The MPC address of the NEAR adapter.
44
+ */
24
45
  get mpcAddress(): Address;
46
+ /**
47
+ * Retrieves the contract ID of the MPC contract associated with the NEAR adapter.
48
+ *
49
+ * @returns {string} - The contract ID of the MPC contract.
50
+ */
25
51
  get mpcContractId(): string;
52
+ /**
53
+ * Retrieves the balance of the Safe account on the specified EVM chain.
54
+ *
55
+ * @param {number} chainId - The ID of the blockchain network where the Safe account is located.
56
+ * @returns {Promise<bigint>} - A promise that resolves to the balance of the Safe account in wei.
57
+ */
26
58
  getBalance(chainId: number): Promise<bigint>;
59
+ /**
60
+ * Constructs a user operation for the specified chain, including necessary gas fees, nonce, and paymaster data.
61
+ * Warning: Uses a private ethRPC with sensitive Pimlico API key (should be run server side).
62
+ *
63
+ * @param {Object} args - The arguments for building the transaction.
64
+ * @param {number} args.chainId - The ID of the blockchain network where the transaction will be executed.
65
+ * @param {MetaTransaction[]} args.transactions - A list of meta-transactions to be included in the user operation.
66
+ * @param {boolean} args.usePaymaster - Flag indicating whether to use a paymaster for gas fees. If true, the transaction will be sponsored by the paymaster.
67
+ * @returns {Promise<UserOperation>} - A promise that resolves to a complete `UserOperation` object, including gas fees, nonce, and paymaster data.
68
+ * @throws {Error} - Throws an error if the transaction set is empty or if any operation fails during the building process.
69
+ */
27
70
  buildTransaction(args: {
28
71
  chainId: number;
29
72
  transactions: MetaTransaction[];
30
73
  usePaymaster: boolean;
31
74
  }): Promise<UserOperation>;
75
+ /**
76
+ * Signs a transaction with the NEAR adapter using the provided operation hash.
77
+ *
78
+ * @param {Hex} safeOpHash - The hash of the user operation that needs to be signed.
79
+ * @returns {Promise<Hex>} - A promise that resolves to the packed signature in hexadecimal format.
80
+ */
32
81
  signTransaction(safeOpHash: Hex): Promise<Hex>;
82
+ /**
83
+ * Computes the operation hash for a given user operation.
84
+ *
85
+ * @param {UserOperation} userOp - The user operation for which the hash needs to be computed.
86
+ * @returns {Promise<Hash>} - A promise that resolves to the hash of the provided user operation.
87
+ */
33
88
  opHash(userOp: UserOperation): Promise<Hash>;
89
+ /**
90
+ * Encodes a request to sign a transaction using either a paymaster or the user's own funds.
91
+ *
92
+ * @param {SignRequestData} signRequest - The data required to create the signature request. This includes information such as the chain ID and other necessary fields for the transaction.
93
+ * @param {boolean} usePaymaster - Flag indicating whether to use a paymaster for gas fees. If true, the transaction will be sponsored by the paymaster.
94
+ * @returns {Promise<EncodedTxData>} - A promise that resolves to the encoded transaction data for the NEAR and EVM networks.
95
+ */
34
96
  encodeSignRequest(signRequest: SignRequestData, usePaymaster: boolean): Promise<EncodedTxData>;
97
+ /**
98
+ * Broadcasts a user operation to the EVM network with a provided signature.
99
+ * Warning: Uses a private ethRPC with sensitive Pimlico API key (should be run server side).
100
+ *
101
+ * @param {number} chainId - The ID of the EVM network to which the transaction should be broadcasted.
102
+ * @param {FinalExecutionOutcome} outcome - The result of the NEAR transaction execution, which contains the necessary data to construct an EVM signature.
103
+ * @param {UserOperation} unsignedUserOp - The unsigned user operation to be broadcasted. This includes transaction data such as the destination address and data payload.
104
+ * @returns {Promise<{ signature: Hex; opHash: Hash }>} - A promise that resolves to an object containing the signature used and the hash of the executed user operation.
105
+ * @throws {Error} - Throws an error if the EVM broadcast fails, including the error message for debugging.
106
+ */
35
107
  broadcastEvm(chainId: number, outcome: FinalExecutionOutcome, unsignedUserOp: UserOperation): Promise<{
36
108
  signature: Hex;
37
- receipt: UserOperationReceipt;
109
+ opHash: Hash;
38
110
  }>;
39
- executeTransaction(chainId: number, userOp: UserOperation): Promise<UserOperationReceipt>;
111
+ /**
112
+ * Executes a user operation on the specified blockchain network.
113
+ * Warning: Uses a private ethRPC with sensitive Pimlico API key (should be run server side).
114
+ *
115
+ * @param {number} chainId - The ID of the blockchain network on which to execute the transaction.
116
+ * @param {UserOperation} userOp - The user operation to be executed, typically includes the data and signatures necessary for the transaction.
117
+ * @returns {Promise<Hash>} - A promise that resolves to the hash of the executed transaction.
118
+ */
119
+ executeTransaction(chainId: number, userOp: UserOperation): Promise<Hash>;
120
+ /**
121
+ * Retrieves the receipt of a previously executed user operation.
122
+ * Warning: Uses a private ethRPC with sensitive Pimlico API key (should be run server side).
123
+ *
124
+ * @param {number} chainId - The ID of the blockchain network where the operation was executed.
125
+ * @param {Hash} userOpHash - The hash of the user operation for which to retrieve the receipt.
126
+ * @returns {Promise<UserOperationReceipt>} - A promise that resolves to the receipt of the user operation, which includes status and logs.
127
+ */
128
+ getOpReceipt(chainId: number, userOpHash: Hash): Promise<UserOperationReceipt>;
129
+ /**
130
+ * Checks if the Safe contract is deployed on the specified chain.
131
+ *
132
+ * @param {number} chainId - The ID of the blockchain network where the Safe contract should be checked.
133
+ * @returns {Promise<boolean>} - A promise that resolves to `true` if the Safe contract is deployed, otherwise `false`.
134
+ */
40
135
  safeDeployed(chainId: number): Promise<boolean>;
136
+ /**
137
+ * Determines if the Safe account has sufficient funds to cover the transaction costs.
138
+ *
139
+ * @param {number} chainId - The ID of the blockchain network where the Safe account is located.
140
+ * @param {MetaTransaction[]} transactions - A list of meta-transactions to be evaluated for funding.
141
+ * @param {bigint} gasCost - The estimated gas cost of executing the transactions.
142
+ * @returns {Promise<boolean>} - A promise that resolves to `true` if the Safe account has sufficient funds, otherwise `false`.
143
+ */
41
144
  sufficientlyFunded(chainId: number, transactions: MetaTransaction[], gasCost: bigint): Promise<boolean>;
145
+ /**
146
+ * Creates a meta-transaction for adding a new owner to the Safe contract.
147
+ *
148
+ * @param {Address} address - The address of the new owner to be added.
149
+ * @returns {MetaTransaction} - A meta-transaction object for adding the new owner.
150
+ */
42
151
  addOwnerTx(address: Address): MetaTransaction;
152
+ /**
153
+ * Creates and returns a new `Erc4337Bundler` instance for the specified chain.
154
+ *
155
+ * @param {number} chainId - The ID of the blockchain network for which the bundler is to be created.
156
+ * @returns {Erc4337Bundler} - A new instance of the `Erc4337Bundler` class configured for the specified chain.
157
+ */
43
158
  private bundlerForChainId;
44
- decodeTxData(data: EvmTransactionData): {
45
- chainId: number;
46
- costEstimate: string;
47
- transactions: MetaTransaction[];
48
- };
159
+ /**
160
+ * Decodes transaction data for a given EVM transaction and extracts relevant details.
161
+ *
162
+ * @param {EvmTransactionData} data - The raw transaction data to be decoded.
163
+ * @returns {{ chainId: number; costEstimate: string; transactions: MetaTransaction[] }} - An object containing the chain ID, estimated cost, and a list of decoded meta-transactions.
164
+ */
165
+ decodeTxData(data: EvmTransactionData): DecodedMultisend;
49
166
  /**
50
167
  * Handles routing of signature requests based on the provided method, chain ID, and parameters.
51
168
  *
@@ -10,6 +10,12 @@ const safe_1 = require("./lib/safe");
10
10
  const safe_message_1 = require("./lib/safe-message");
11
11
  const util_1 = require("./util");
12
12
  class NearSafe {
13
+ /**
14
+ * Creates a new instance of the `NearSafe` class using the provided configuration.
15
+ *
16
+ * @param {NearSafeConfig} config - The configuration object required to initialize the `NearSafe` instance, including the Pimlico key and safe salt nonce.
17
+ * @returns {Promise<NearSafe>} - A promise that resolves to a new `NearSafe` instance.
18
+ */
13
19
  static async create(config) {
14
20
  const { pimlicoKey, safeSaltNonce } = config;
15
21
  const nearAdapter = await (0, near_ca_1.setupAdapter)({ ...config });
@@ -24,6 +30,16 @@ class NearSafe {
24
30
  `);
25
31
  return new NearSafe(nearAdapter, safePack, pimlicoKey, setup, safeAddress, safeSaltNonce || "0");
26
32
  }
33
+ /**
34
+ * Constructs a new `NearSafe` object with the provided parameters.
35
+ *
36
+ * @param {NearEthAdapter} nearAdapter - The NEAR adapter used for interacting with the NEAR blockchain.
37
+ * @param {SafeContractSuite} safePack - A suite of contracts and utilities for managing the Safe contract.
38
+ * @param {string} pimlicoKey - A key required for authenticating with the Pimlico service.
39
+ * @param {string} setup - The setup string generated for the Safe contract.
40
+ * @param {Address} safeAddress - The address of the deployed Safe contract.
41
+ * @param {string} safeSaltNonce - A unique nonce used to differentiate the Safe setup.
42
+ */
27
43
  constructor(nearAdapter, safePack, pimlicoKey, setup, safeAddress, safeSaltNonce) {
28
44
  this.nearAdapter = nearAdapter;
29
45
  this.address = safeAddress;
@@ -32,15 +48,42 @@ class NearSafe {
32
48
  this.pimlicoKey = pimlicoKey;
33
49
  this.safeSaltNonce = safeSaltNonce;
34
50
  }
51
+ /**
52
+ * Retrieves the MPC (Multi-Party Computation) address associated with the NEAR adapter.
53
+ *
54
+ * @returns {Address} - The MPC address of the NEAR adapter.
55
+ */
35
56
  get mpcAddress() {
36
57
  return this.nearAdapter.address;
37
58
  }
59
+ /**
60
+ * Retrieves the contract ID of the MPC contract associated with the NEAR adapter.
61
+ *
62
+ * @returns {string} - The contract ID of the MPC contract.
63
+ */
38
64
  get mpcContractId() {
39
65
  return this.nearAdapter.mpcContract.contract.contractId;
40
66
  }
67
+ /**
68
+ * Retrieves the balance of the Safe account on the specified EVM chain.
69
+ *
70
+ * @param {number} chainId - The ID of the blockchain network where the Safe account is located.
71
+ * @returns {Promise<bigint>} - A promise that resolves to the balance of the Safe account in wei.
72
+ */
41
73
  async getBalance(chainId) {
42
74
  return await (0, util_1.getClient)(chainId).getBalance({ address: this.address });
43
75
  }
76
+ /**
77
+ * Constructs a user operation for the specified chain, including necessary gas fees, nonce, and paymaster data.
78
+ * Warning: Uses a private ethRPC with sensitive Pimlico API key (should be run server side).
79
+ *
80
+ * @param {Object} args - The arguments for building the transaction.
81
+ * @param {number} args.chainId - The ID of the blockchain network where the transaction will be executed.
82
+ * @param {MetaTransaction[]} args.transactions - A list of meta-transactions to be included in the user operation.
83
+ * @param {boolean} args.usePaymaster - Flag indicating whether to use a paymaster for gas fees. If true, the transaction will be sponsored by the paymaster.
84
+ * @returns {Promise<UserOperation>} - A promise that resolves to a complete `UserOperation` object, including gas fees, nonce, and paymaster data.
85
+ * @throws {Error} - Throws an error if the transaction set is empty or if any operation fails during the building process.
86
+ */
44
87
  async buildTransaction(args) {
45
88
  const { transactions, usePaymaster, chainId } = args;
46
89
  if (transactions.length === 0) {
@@ -59,13 +102,32 @@ class NearSafe {
59
102
  const unsignedUserOp = { ...rawUserOp, ...paymasterData };
60
103
  return unsignedUserOp;
61
104
  }
105
+ /**
106
+ * Signs a transaction with the NEAR adapter using the provided operation hash.
107
+ *
108
+ * @param {Hex} safeOpHash - The hash of the user operation that needs to be signed.
109
+ * @returns {Promise<Hex>} - A promise that resolves to the packed signature in hexadecimal format.
110
+ */
62
111
  async signTransaction(safeOpHash) {
63
112
  const signature = await this.nearAdapter.sign(safeOpHash);
64
113
  return (0, util_1.packSignature)(signature);
65
114
  }
115
+ /**
116
+ * Computes the operation hash for a given user operation.
117
+ *
118
+ * @param {UserOperation} userOp - The user operation for which the hash needs to be computed.
119
+ * @returns {Promise<Hash>} - A promise that resolves to the hash of the provided user operation.
120
+ */
66
121
  async opHash(userOp) {
67
122
  return this.safePack.getOpHash(userOp);
68
123
  }
124
+ /**
125
+ * Encodes a request to sign a transaction using either a paymaster or the user's own funds.
126
+ *
127
+ * @param {SignRequestData} signRequest - The data required to create the signature request. This includes information such as the chain ID and other necessary fields for the transaction.
128
+ * @param {boolean} usePaymaster - Flag indicating whether to use a paymaster for gas fees. If true, the transaction will be sponsored by the paymaster.
129
+ * @returns {Promise<EncodedTxData>} - A promise that resolves to the encoded transaction data for the NEAR and EVM networks.
130
+ */
69
131
  async encodeSignRequest(signRequest, usePaymaster) {
70
132
  const { payload, evmMessage, hash } = await this.requestRouter(signRequest, usePaymaster);
71
133
  return {
@@ -81,12 +143,22 @@ class NearSafe {
81
143
  },
82
144
  };
83
145
  }
146
+ /**
147
+ * Broadcasts a user operation to the EVM network with a provided signature.
148
+ * Warning: Uses a private ethRPC with sensitive Pimlico API key (should be run server side).
149
+ *
150
+ * @param {number} chainId - The ID of the EVM network to which the transaction should be broadcasted.
151
+ * @param {FinalExecutionOutcome} outcome - The result of the NEAR transaction execution, which contains the necessary data to construct an EVM signature.
152
+ * @param {UserOperation} unsignedUserOp - The unsigned user operation to be broadcasted. This includes transaction data such as the destination address and data payload.
153
+ * @returns {Promise<{ signature: Hex; opHash: Hash }>} - A promise that resolves to an object containing the signature used and the hash of the executed user operation.
154
+ * @throws {Error} - Throws an error if the EVM broadcast fails, including the error message for debugging.
155
+ */
84
156
  async broadcastEvm(chainId, outcome, unsignedUserOp) {
85
157
  const signature = (0, util_1.packSignature)((0, viem_1.serializeSignature)((0, near_ca_1.signatureFromOutcome)(outcome)));
86
158
  try {
87
159
  return {
88
160
  signature,
89
- receipt: await this.executeTransaction(chainId, {
161
+ opHash: await this.executeTransaction(chainId, {
90
162
  ...unsignedUserOp,
91
163
  signature,
92
164
  }),
@@ -96,19 +168,45 @@ class NearSafe {
96
168
  throw new Error(`Failed EVM broadcast: ${error instanceof Error ? error.message : String(error)}`);
97
169
  }
98
170
  }
171
+ /**
172
+ * Executes a user operation on the specified blockchain network.
173
+ * Warning: Uses a private ethRPC with sensitive Pimlico API key (should be run server side).
174
+ *
175
+ * @param {number} chainId - The ID of the blockchain network on which to execute the transaction.
176
+ * @param {UserOperation} userOp - The user operation to be executed, typically includes the data and signatures necessary for the transaction.
177
+ * @returns {Promise<Hash>} - A promise that resolves to the hash of the executed transaction.
178
+ */
99
179
  async executeTransaction(chainId, userOp) {
100
- const bundler = this.bundlerForChainId(chainId);
101
- const userOpHash = await bundler.sendUserOperation(userOp);
102
- console.log("UserOp Hash", userOpHash);
103
- const userOpReceipt = await bundler.getUserOpReceipt(userOpHash);
104
- console.log("userOp Receipt", userOpReceipt);
105
- // Update safeNotDeployed after the first transaction
106
- this.safeDeployed(chainId);
107
- return userOpReceipt;
180
+ return this.bundlerForChainId(chainId).sendUserOperation(userOp);
108
181
  }
182
+ /**
183
+ * Retrieves the receipt of a previously executed user operation.
184
+ * Warning: Uses a private ethRPC with sensitive Pimlico API key (should be run server side).
185
+ *
186
+ * @param {number} chainId - The ID of the blockchain network where the operation was executed.
187
+ * @param {Hash} userOpHash - The hash of the user operation for which to retrieve the receipt.
188
+ * @returns {Promise<UserOperationReceipt>} - A promise that resolves to the receipt of the user operation, which includes status and logs.
189
+ */
190
+ async getOpReceipt(chainId, userOpHash) {
191
+ return this.bundlerForChainId(chainId).getUserOpReceipt(userOpHash);
192
+ }
193
+ /**
194
+ * Checks if the Safe contract is deployed on the specified chain.
195
+ *
196
+ * @param {number} chainId - The ID of the blockchain network where the Safe contract should be checked.
197
+ * @returns {Promise<boolean>} - A promise that resolves to `true` if the Safe contract is deployed, otherwise `false`.
198
+ */
109
199
  async safeDeployed(chainId) {
110
200
  return (0, util_1.isContract)(this.address, chainId);
111
201
  }
202
+ /**
203
+ * Determines if the Safe account has sufficient funds to cover the transaction costs.
204
+ *
205
+ * @param {number} chainId - The ID of the blockchain network where the Safe account is located.
206
+ * @param {MetaTransaction[]} transactions - A list of meta-transactions to be evaluated for funding.
207
+ * @param {bigint} gasCost - The estimated gas cost of executing the transactions.
208
+ * @returns {Promise<boolean>} - A promise that resolves to `true` if the Safe account has sufficient funds, otherwise `false`.
209
+ */
112
210
  async sufficientlyFunded(chainId, transactions, gasCost) {
113
211
  const txValue = transactions.reduce((acc, tx) => acc + BigInt(tx.value), 0n);
114
212
  if (txValue + gasCost === 0n) {
@@ -117,6 +215,12 @@ class NearSafe {
117
215
  const safeBalance = await this.getBalance(chainId);
118
216
  return txValue + gasCost < safeBalance;
119
217
  }
218
+ /**
219
+ * Creates a meta-transaction for adding a new owner to the Safe contract.
220
+ *
221
+ * @param {Address} address - The address of the new owner to be added.
222
+ * @returns {MetaTransaction} - A meta-transaction object for adding the new owner.
223
+ */
120
224
  addOwnerTx(address) {
121
225
  return {
122
226
  to: this.address,
@@ -124,9 +228,21 @@ class NearSafe {
124
228
  data: this.safePack.addOwnerData(address),
125
229
  };
126
230
  }
231
+ /**
232
+ * Creates and returns a new `Erc4337Bundler` instance for the specified chain.
233
+ *
234
+ * @param {number} chainId - The ID of the blockchain network for which the bundler is to be created.
235
+ * @returns {Erc4337Bundler} - A new instance of the `Erc4337Bundler` class configured for the specified chain.
236
+ */
127
237
  bundlerForChainId(chainId) {
128
238
  return new bundler_1.Erc4337Bundler(this.safePack.entryPoint.address, this.pimlicoKey, chainId);
129
239
  }
240
+ /**
241
+ * Decodes transaction data for a given EVM transaction and extracts relevant details.
242
+ *
243
+ * @param {EvmTransactionData} data - The raw transaction data to be decoded.
244
+ * @returns {{ chainId: number; costEstimate: string; transactions: MetaTransaction[] }} - An object containing the chain ID, estimated cost, and a list of decoded meta-transactions.
245
+ */
130
246
  decodeTxData(data) {
131
247
  // TODO: data.data may not always parse to UserOperation. We will have to handle the other cases.
132
248
  const userOp = JSON.parse(data.data);
@@ -136,7 +252,7 @@ class NearSafe {
136
252
  abi: this.safePack.m4337.abi,
137
253
  data: userOp.callData,
138
254
  });
139
- // Determine if sungular or double!
255
+ // Determine if singular or double!
140
256
  const transactions = (0, multisend_1.isMultisendTx)(args)
141
257
  ? (0, ethers_multisend_1.decodeMulti)(args[2])
142
258
  : [
@@ -1,113 +1,247 @@
1
1
  import { FunctionCallTransaction, SignArgs } from "near-ca";
2
2
  import { Address, Hex, ParseAbi } from "viem";
3
+ /**
4
+ * Represents a collection of Safe contract deployments, each with its own address and ABI.
5
+ */
3
6
  export type SafeDeployments = {
7
+ /** Deployment for the singleton contract. */
4
8
  singleton: Deployment;
9
+ /** Deployment for the proxy factory contract. */
5
10
  proxyFactory: Deployment;
11
+ /** Deployment for the module setup contract. */
6
12
  moduleSetup: Deployment;
13
+ /** Deployment for the m4337 module contract. */
7
14
  m4337: Deployment;
15
+ /** Deployment for the entry point contract. */
8
16
  entryPoint: Deployment;
9
17
  };
18
+ /**
19
+ * Represents the details of a deployed contract, including its ABI and address.
20
+ */
10
21
  export interface Deployment {
22
+ /** The ABI of the deployed contract. Can be a raw ABI array or a parsed ABI. */
11
23
  abi: unknown[] | ParseAbi<readonly string[]>;
24
+ /** The address of the deployed contract. */
12
25
  address: Address;
13
26
  }
27
+ /**
28
+ * Represents an unsigned user operation that can be sent to the EntryPoint contract.
29
+ */
14
30
  export interface UnsignedUserOperation {
31
+ /** The sender's address initiating the user operation. */
15
32
  sender: Address;
33
+ /** The unique nonce associated with this user operation. */
16
34
  nonce: string;
35
+ /** The optional factory address to use for creating new contracts. */
17
36
  factory?: Address;
37
+ /** Optional additional data for the factory, typically used for contract initialization. */
18
38
  factoryData?: Hex;
39
+ /** The encoded data for the contract call or transaction execution. */
19
40
  callData: Hex;
41
+ /** Maximum priority fee per gas unit for the transaction. */
20
42
  maxPriorityFeePerGas: Hex;
43
+ /** Maximum fee per gas unit for the transaction. */
21
44
  maxFeePerGas: Hex;
22
45
  }
23
46
  /**
24
- * Supported Representation of UserOperation for EntryPoint v0.7
47
+ * Supported representation of a user operation for EntryPoint version 0.7, including gas limits and signature.
25
48
  */
26
49
  export interface UserOperation extends UnsignedUserOperation {
50
+ /** The gas limit for verification of the operation. */
27
51
  verificationGasLimit: Hex;
52
+ /** The gas limit for the execution of the operation call. */
28
53
  callGasLimit: Hex;
54
+ /** The gas used before verification begins. */
29
55
  preVerificationGas: Hex;
56
+ /** Optional signature for the user operation. */
30
57
  signature?: Hex;
31
58
  }
59
+ /**
60
+ * Represents additional paymaster-related data for a user operation.
61
+ */
32
62
  export interface PaymasterData {
63
+ /** Optional paymaster address responsible for covering gas costs. */
33
64
  paymaster?: Address;
65
+ /** Optional additional data required by the paymaster. */
34
66
  paymasterData?: Hex;
67
+ /** The gas limit for paymaster verification. */
35
68
  paymasterVerificationGasLimit?: Hex;
69
+ /** The gas limit for paymaster post-operation execution. */
36
70
  paymasterPostOpGasLimit?: Hex;
71
+ /** The gas limit for operation verification. */
37
72
  verificationGasLimit: Hex;
73
+ /** The gas limit for the operation call execution. */
38
74
  callGasLimit: Hex;
75
+ /** The gas used before verification begins. */
39
76
  preVerificationGas: Hex;
40
77
  }
78
+ /**
79
+ * User configuration options for transaction building and user operation execution.
80
+ */
41
81
  export interface UserOptions {
82
+ /** Whether to use a paymaster for gas fee coverage. */
42
83
  usePaymaster: boolean;
84
+ /** The unique nonce used to differentiate multiple Safe setups. */
43
85
  safeSaltNonce: string;
86
+ /** The NEAR contract ID for the MPC contract. */
44
87
  mpcContractId: string;
88
+ /** Optional recovery address in case of key compromise or other emergency situations. */
45
89
  recoveryAddress?: string;
46
90
  }
91
+ /**
92
+ * Represents the possible transaction statuses.
93
+ */
47
94
  export type TxStatus = "success" | "reverted";
95
+ /**
96
+ * Represents a log entry in a transaction receipt.
97
+ */
48
98
  interface Log {
99
+ /** The index of the log in the transaction. */
49
100
  logIndex: string;
101
+ /** The index of the transaction within the block. */
50
102
  transactionIndex: string;
103
+ /** The hash of the transaction containing the log. */
51
104
  transactionHash: string;
105
+ /** The hash of the block containing the transaction. */
52
106
  blockHash: string;
107
+ /** The number of the block containing the transaction. */
53
108
  blockNumber: string;
109
+ /** The address that generated the log. */
54
110
  address: string;
111
+ /** The raw data of the log. */
55
112
  data: string;
113
+ /** The topics associated with the log event. */
56
114
  topics: string[];
57
115
  }
116
+ /**
117
+ * Represents a transaction receipt returned by the blockchain.
118
+ */
58
119
  interface Receipt {
120
+ /** The hash of the transaction. */
59
121
  transactionHash: Hex;
122
+ /** The index of the transaction within the block. */
60
123
  transactionIndex: bigint;
124
+ /** The hash of the block containing the transaction. */
61
125
  blockHash: Hex;
126
+ /** The number of the block containing the transaction. */
62
127
  blockNumber: bigint;
128
+ /** The address from which the transaction originated. */
63
129
  from: Address;
130
+ /** Optional address to which the transaction was sent (if applicable). */
64
131
  to?: Address;
132
+ /** The cumulative gas used in the block up to this transaction. */
65
133
  cumulativeGasUsed: bigint;
134
+ /** The status of the transaction (success or reverted). */
66
135
  status: TxStatus;
136
+ /** The total gas used by this transaction. */
67
137
  gasUsed: bigint;
138
+ /** Optional address of a newly deployed contract (if applicable). */
68
139
  contractAddress?: Address;
140
+ /** The logs bloom filter for the transaction. */
69
141
  logsBloom: Hex;
142
+ /** The effective gas price used in the transaction. */
70
143
  effectiveGasPrice: bigint;
71
144
  }
145
+ /**
146
+ * Represents the receipt of a user operation including its details, logs, and result.
147
+ */
72
148
  export type UserOperationReceipt = {
149
+ /** The hash of the user operation. */
73
150
  userOpHash: Hex;
151
+ /** The address of the entry point contract handling the user operation. */
74
152
  entryPoint: Address;
153
+ /** The sender's address initiating the user operation. */
75
154
  sender: Address;
155
+ /** The nonce of the user operation. */
76
156
  nonce: bigint;
157
+ /** Optional paymaster address responsible for covering gas costs. */
77
158
  paymaster?: Address;
159
+ /** The actual gas used by the operation. */
78
160
  actualGasUsed: bigint;
161
+ /** The actual gas cost of the operation. */
79
162
  actualGasCost: bigint;
163
+ /** Whether the user operation succeeded or failed. */
80
164
  success: boolean;
165
+ /** Optional reason for failure if the operation was unsuccessful. */
81
166
  reason?: string;
167
+ /** The transaction receipt associated with the user operation. */
82
168
  receipt: Receipt;
169
+ /** The list of logs generated by the user operation. */
83
170
  logs: Log[];
84
171
  };
172
+ /**
173
+ * Represents the different gas prices for transaction execution based on priority levels.
174
+ */
85
175
  export interface GasPrices {
176
+ /** Gas price for slower transactions. */
86
177
  slow: GasPrice;
178
+ /** Gas price for standard transactions. */
87
179
  standard: GasPrice;
180
+ /** Gas price for fast transactions. */
88
181
  fast: GasPrice;
89
182
  }
183
+ /**
184
+ * Represents a specific gas price configuration for transaction execution.
185
+ */
90
186
  export interface GasPrice {
187
+ /** Maximum fee per gas unit for the transaction. */
91
188
  maxFeePerGas: Hex;
189
+ /** Maximum priority fee per gas unit for the transaction. */
92
190
  maxPriorityFeePerGas: Hex;
93
191
  }
192
+ /**
193
+ * Enum representing the type of operation in a meta-transaction.
194
+ */
94
195
  export declare enum OperationType {
196
+ /** Standard call operation (0). */
95
197
  Call = 0,
198
+ /** Delegate call operation (1). */
96
199
  DelegateCall = 1
97
200
  }
201
+ /**
202
+ * Represents a meta-transaction, which includes the destination address, value, data, and type of operation.
203
+ */
98
204
  export interface MetaTransaction {
205
+ /** The destination address for the meta-transaction. */
99
206
  readonly to: string;
207
+ /** The value to be sent with the transaction (as a string to handle large numbers). */
100
208
  readonly value: string;
209
+ /** The encoded data for the contract call or function execution. */
101
210
  readonly data: string;
211
+ /** Optional type of operation (call or delegate call). */
102
212
  readonly operation?: OperationType;
103
213
  }
214
+ /**
215
+ * Represents raw transaction data for an EVM transaction.
216
+ */
104
217
  export interface EvmTransactionData {
218
+ /** The chain ID of the network where the transaction is being executed. */
105
219
  chainId: number;
220
+ /** The raw data of the transaction. */
106
221
  data: string;
222
+ /** The hash of the transaction. */
107
223
  hash: string;
108
224
  }
225
+ /**
226
+ * Represents the decoded details of a multisend transaction.
227
+ */
228
+ export interface DecodedMultisend {
229
+ /** The chain ID of the network where the multisend transaction is being executed. */
230
+ chainId: number;
231
+ /** The estimated cost of the multisend transaction in Ether.
232
+ * This is an upper bound on the transaction fee (could wind up lower).
233
+ */
234
+ costEstimate: string;
235
+ /** The list of meta-transactions included in the multisend. */
236
+ transactions: MetaTransaction[];
237
+ }
238
+ /**
239
+ * Represents encoded transaction data for both NEAR and EVM networks.
240
+ */
109
241
  export interface EncodedTxData {
242
+ /** The encoded transaction data for the EVM network. */
110
243
  evmData: EvmTransactionData;
244
+ /** The encoded payload for a NEAR function call, including the signing arguments. */
111
245
  nearPayload: FunctionCallTransaction<{
112
246
  request: SignArgs;
113
247
  }>;
package/dist/cjs/types.js CHANGED
@@ -1,8 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.OperationType = void 0;
4
+ /**
5
+ * Enum representing the type of operation in a meta-transaction.
6
+ */
4
7
  var OperationType;
5
8
  (function (OperationType) {
9
+ /** Standard call operation (0). */
6
10
  OperationType[OperationType["Call"] = 0] = "Call";
11
+ /** Delegate call operation (1). */
7
12
  OperationType[OperationType["DelegateCall"] = 1] = "DelegateCall";
8
13
  })(OperationType || (exports.OperationType = OperationType = {}));
@@ -3,7 +3,7 @@ import { FinalExecutionOutcome } from "near-api-js/lib/providers";
3
3
  import { NearEthAdapter, SignRequestData } from "near-ca";
4
4
  import { Address, Hash, Hex } from "viem";
5
5
  import { SafeContractSuite } from "./lib/safe";
6
- import { EncodedTxData, EvmTransactionData, MetaTransaction, UserOperation, UserOperationReceipt } from "./types";
6
+ import { DecodedMultisend, EncodedTxData, EvmTransactionData, MetaTransaction, UserOperation, UserOperationReceipt } from "./types";
7
7
  export interface NearSafeConfig {
8
8
  accountId: string;
9
9
  mpcContractId: string;
@@ -19,33 +19,150 @@ export declare class NearSafe {
19
19
  private setup;
20
20
  private pimlicoKey;
21
21
  private safeSaltNonce;
22
+ /**
23
+ * Creates a new instance of the `NearSafe` class using the provided configuration.
24
+ *
25
+ * @param {NearSafeConfig} config - The configuration object required to initialize the `NearSafe` instance, including the Pimlico key and safe salt nonce.
26
+ * @returns {Promise<NearSafe>} - A promise that resolves to a new `NearSafe` instance.
27
+ */
22
28
  static create(config: NearSafeConfig): Promise<NearSafe>;
29
+ /**
30
+ * Constructs a new `NearSafe` object with the provided parameters.
31
+ *
32
+ * @param {NearEthAdapter} nearAdapter - The NEAR adapter used for interacting with the NEAR blockchain.
33
+ * @param {SafeContractSuite} safePack - A suite of contracts and utilities for managing the Safe contract.
34
+ * @param {string} pimlicoKey - A key required for authenticating with the Pimlico service.
35
+ * @param {string} setup - The setup string generated for the Safe contract.
36
+ * @param {Address} safeAddress - The address of the deployed Safe contract.
37
+ * @param {string} safeSaltNonce - A unique nonce used to differentiate the Safe setup.
38
+ */
23
39
  constructor(nearAdapter: NearEthAdapter, safePack: SafeContractSuite, pimlicoKey: string, setup: string, safeAddress: Address, safeSaltNonce: string);
40
+ /**
41
+ * Retrieves the MPC (Multi-Party Computation) address associated with the NEAR adapter.
42
+ *
43
+ * @returns {Address} - The MPC address of the NEAR adapter.
44
+ */
24
45
  get mpcAddress(): Address;
46
+ /**
47
+ * Retrieves the contract ID of the MPC contract associated with the NEAR adapter.
48
+ *
49
+ * @returns {string} - The contract ID of the MPC contract.
50
+ */
25
51
  get mpcContractId(): string;
52
+ /**
53
+ * Retrieves the balance of the Safe account on the specified EVM chain.
54
+ *
55
+ * @param {number} chainId - The ID of the blockchain network where the Safe account is located.
56
+ * @returns {Promise<bigint>} - A promise that resolves to the balance of the Safe account in wei.
57
+ */
26
58
  getBalance(chainId: number): Promise<bigint>;
59
+ /**
60
+ * Constructs a user operation for the specified chain, including necessary gas fees, nonce, and paymaster data.
61
+ * Warning: Uses a private ethRPC with sensitive Pimlico API key (should be run server side).
62
+ *
63
+ * @param {Object} args - The arguments for building the transaction.
64
+ * @param {number} args.chainId - The ID of the blockchain network where the transaction will be executed.
65
+ * @param {MetaTransaction[]} args.transactions - A list of meta-transactions to be included in the user operation.
66
+ * @param {boolean} args.usePaymaster - Flag indicating whether to use a paymaster for gas fees. If true, the transaction will be sponsored by the paymaster.
67
+ * @returns {Promise<UserOperation>} - A promise that resolves to a complete `UserOperation` object, including gas fees, nonce, and paymaster data.
68
+ * @throws {Error} - Throws an error if the transaction set is empty or if any operation fails during the building process.
69
+ */
27
70
  buildTransaction(args: {
28
71
  chainId: number;
29
72
  transactions: MetaTransaction[];
30
73
  usePaymaster: boolean;
31
74
  }): Promise<UserOperation>;
75
+ /**
76
+ * Signs a transaction with the NEAR adapter using the provided operation hash.
77
+ *
78
+ * @param {Hex} safeOpHash - The hash of the user operation that needs to be signed.
79
+ * @returns {Promise<Hex>} - A promise that resolves to the packed signature in hexadecimal format.
80
+ */
32
81
  signTransaction(safeOpHash: Hex): Promise<Hex>;
82
+ /**
83
+ * Computes the operation hash for a given user operation.
84
+ *
85
+ * @param {UserOperation} userOp - The user operation for which the hash needs to be computed.
86
+ * @returns {Promise<Hash>} - A promise that resolves to the hash of the provided user operation.
87
+ */
33
88
  opHash(userOp: UserOperation): Promise<Hash>;
89
+ /**
90
+ * Encodes a request to sign a transaction using either a paymaster or the user's own funds.
91
+ *
92
+ * @param {SignRequestData} signRequest - The data required to create the signature request. This includes information such as the chain ID and other necessary fields for the transaction.
93
+ * @param {boolean} usePaymaster - Flag indicating whether to use a paymaster for gas fees. If true, the transaction will be sponsored by the paymaster.
94
+ * @returns {Promise<EncodedTxData>} - A promise that resolves to the encoded transaction data for the NEAR and EVM networks.
95
+ */
34
96
  encodeSignRequest(signRequest: SignRequestData, usePaymaster: boolean): Promise<EncodedTxData>;
97
+ /**
98
+ * Broadcasts a user operation to the EVM network with a provided signature.
99
+ * Warning: Uses a private ethRPC with sensitive Pimlico API key (should be run server side).
100
+ *
101
+ * @param {number} chainId - The ID of the EVM network to which the transaction should be broadcasted.
102
+ * @param {FinalExecutionOutcome} outcome - The result of the NEAR transaction execution, which contains the necessary data to construct an EVM signature.
103
+ * @param {UserOperation} unsignedUserOp - The unsigned user operation to be broadcasted. This includes transaction data such as the destination address and data payload.
104
+ * @returns {Promise<{ signature: Hex; opHash: Hash }>} - A promise that resolves to an object containing the signature used and the hash of the executed user operation.
105
+ * @throws {Error} - Throws an error if the EVM broadcast fails, including the error message for debugging.
106
+ */
35
107
  broadcastEvm(chainId: number, outcome: FinalExecutionOutcome, unsignedUserOp: UserOperation): Promise<{
36
108
  signature: Hex;
37
- receipt: UserOperationReceipt;
109
+ opHash: Hash;
38
110
  }>;
39
- executeTransaction(chainId: number, userOp: UserOperation): Promise<UserOperationReceipt>;
111
+ /**
112
+ * Executes a user operation on the specified blockchain network.
113
+ * Warning: Uses a private ethRPC with sensitive Pimlico API key (should be run server side).
114
+ *
115
+ * @param {number} chainId - The ID of the blockchain network on which to execute the transaction.
116
+ * @param {UserOperation} userOp - The user operation to be executed, typically includes the data and signatures necessary for the transaction.
117
+ * @returns {Promise<Hash>} - A promise that resolves to the hash of the executed transaction.
118
+ */
119
+ executeTransaction(chainId: number, userOp: UserOperation): Promise<Hash>;
120
+ /**
121
+ * Retrieves the receipt of a previously executed user operation.
122
+ * Warning: Uses a private ethRPC with sensitive Pimlico API key (should be run server side).
123
+ *
124
+ * @param {number} chainId - The ID of the blockchain network where the operation was executed.
125
+ * @param {Hash} userOpHash - The hash of the user operation for which to retrieve the receipt.
126
+ * @returns {Promise<UserOperationReceipt>} - A promise that resolves to the receipt of the user operation, which includes status and logs.
127
+ */
128
+ getOpReceipt(chainId: number, userOpHash: Hash): Promise<UserOperationReceipt>;
129
+ /**
130
+ * Checks if the Safe contract is deployed on the specified chain.
131
+ *
132
+ * @param {number} chainId - The ID of the blockchain network where the Safe contract should be checked.
133
+ * @returns {Promise<boolean>} - A promise that resolves to `true` if the Safe contract is deployed, otherwise `false`.
134
+ */
40
135
  safeDeployed(chainId: number): Promise<boolean>;
136
+ /**
137
+ * Determines if the Safe account has sufficient funds to cover the transaction costs.
138
+ *
139
+ * @param {number} chainId - The ID of the blockchain network where the Safe account is located.
140
+ * @param {MetaTransaction[]} transactions - A list of meta-transactions to be evaluated for funding.
141
+ * @param {bigint} gasCost - The estimated gas cost of executing the transactions.
142
+ * @returns {Promise<boolean>} - A promise that resolves to `true` if the Safe account has sufficient funds, otherwise `false`.
143
+ */
41
144
  sufficientlyFunded(chainId: number, transactions: MetaTransaction[], gasCost: bigint): Promise<boolean>;
145
+ /**
146
+ * Creates a meta-transaction for adding a new owner to the Safe contract.
147
+ *
148
+ * @param {Address} address - The address of the new owner to be added.
149
+ * @returns {MetaTransaction} - A meta-transaction object for adding the new owner.
150
+ */
42
151
  addOwnerTx(address: Address): MetaTransaction;
152
+ /**
153
+ * Creates and returns a new `Erc4337Bundler` instance for the specified chain.
154
+ *
155
+ * @param {number} chainId - The ID of the blockchain network for which the bundler is to be created.
156
+ * @returns {Erc4337Bundler} - A new instance of the `Erc4337Bundler` class configured for the specified chain.
157
+ */
43
158
  private bundlerForChainId;
44
- decodeTxData(data: EvmTransactionData): {
45
- chainId: number;
46
- costEstimate: string;
47
- transactions: MetaTransaction[];
48
- };
159
+ /**
160
+ * Decodes transaction data for a given EVM transaction and extracts relevant details.
161
+ *
162
+ * @param {EvmTransactionData} data - The raw transaction data to be decoded.
163
+ * @returns {{ chainId: number; costEstimate: string; transactions: MetaTransaction[] }} - An object containing the chain ID, estimated cost, and a list of decoded meta-transactions.
164
+ */
165
+ decodeTxData(data: EvmTransactionData): DecodedMultisend;
49
166
  /**
50
167
  * Handles routing of signature requests based on the provided method, chain ID, and parameters.
51
168
  *
@@ -13,6 +13,12 @@ export class NearSafe {
13
13
  setup;
14
14
  pimlicoKey;
15
15
  safeSaltNonce;
16
+ /**
17
+ * Creates a new instance of the `NearSafe` class using the provided configuration.
18
+ *
19
+ * @param {NearSafeConfig} config - The configuration object required to initialize the `NearSafe` instance, including the Pimlico key and safe salt nonce.
20
+ * @returns {Promise<NearSafe>} - A promise that resolves to a new `NearSafe` instance.
21
+ */
16
22
  static async create(config) {
17
23
  const { pimlicoKey, safeSaltNonce } = config;
18
24
  const nearAdapter = await setupAdapter({ ...config });
@@ -27,6 +33,16 @@ export class NearSafe {
27
33
  `);
28
34
  return new NearSafe(nearAdapter, safePack, pimlicoKey, setup, safeAddress, safeSaltNonce || "0");
29
35
  }
36
+ /**
37
+ * Constructs a new `NearSafe` object with the provided parameters.
38
+ *
39
+ * @param {NearEthAdapter} nearAdapter - The NEAR adapter used for interacting with the NEAR blockchain.
40
+ * @param {SafeContractSuite} safePack - A suite of contracts and utilities for managing the Safe contract.
41
+ * @param {string} pimlicoKey - A key required for authenticating with the Pimlico service.
42
+ * @param {string} setup - The setup string generated for the Safe contract.
43
+ * @param {Address} safeAddress - The address of the deployed Safe contract.
44
+ * @param {string} safeSaltNonce - A unique nonce used to differentiate the Safe setup.
45
+ */
30
46
  constructor(nearAdapter, safePack, pimlicoKey, setup, safeAddress, safeSaltNonce) {
31
47
  this.nearAdapter = nearAdapter;
32
48
  this.address = safeAddress;
@@ -35,15 +51,42 @@ export class NearSafe {
35
51
  this.pimlicoKey = pimlicoKey;
36
52
  this.safeSaltNonce = safeSaltNonce;
37
53
  }
54
+ /**
55
+ * Retrieves the MPC (Multi-Party Computation) address associated with the NEAR adapter.
56
+ *
57
+ * @returns {Address} - The MPC address of the NEAR adapter.
58
+ */
38
59
  get mpcAddress() {
39
60
  return this.nearAdapter.address;
40
61
  }
62
+ /**
63
+ * Retrieves the contract ID of the MPC contract associated with the NEAR adapter.
64
+ *
65
+ * @returns {string} - The contract ID of the MPC contract.
66
+ */
41
67
  get mpcContractId() {
42
68
  return this.nearAdapter.mpcContract.contract.contractId;
43
69
  }
70
+ /**
71
+ * Retrieves the balance of the Safe account on the specified EVM chain.
72
+ *
73
+ * @param {number} chainId - The ID of the blockchain network where the Safe account is located.
74
+ * @returns {Promise<bigint>} - A promise that resolves to the balance of the Safe account in wei.
75
+ */
44
76
  async getBalance(chainId) {
45
77
  return await getClient(chainId).getBalance({ address: this.address });
46
78
  }
79
+ /**
80
+ * Constructs a user operation for the specified chain, including necessary gas fees, nonce, and paymaster data.
81
+ * Warning: Uses a private ethRPC with sensitive Pimlico API key (should be run server side).
82
+ *
83
+ * @param {Object} args - The arguments for building the transaction.
84
+ * @param {number} args.chainId - The ID of the blockchain network where the transaction will be executed.
85
+ * @param {MetaTransaction[]} args.transactions - A list of meta-transactions to be included in the user operation.
86
+ * @param {boolean} args.usePaymaster - Flag indicating whether to use a paymaster for gas fees. If true, the transaction will be sponsored by the paymaster.
87
+ * @returns {Promise<UserOperation>} - A promise that resolves to a complete `UserOperation` object, including gas fees, nonce, and paymaster data.
88
+ * @throws {Error} - Throws an error if the transaction set is empty or if any operation fails during the building process.
89
+ */
47
90
  async buildTransaction(args) {
48
91
  const { transactions, usePaymaster, chainId } = args;
49
92
  if (transactions.length === 0) {
@@ -62,13 +105,32 @@ export class NearSafe {
62
105
  const unsignedUserOp = { ...rawUserOp, ...paymasterData };
63
106
  return unsignedUserOp;
64
107
  }
108
+ /**
109
+ * Signs a transaction with the NEAR adapter using the provided operation hash.
110
+ *
111
+ * @param {Hex} safeOpHash - The hash of the user operation that needs to be signed.
112
+ * @returns {Promise<Hex>} - A promise that resolves to the packed signature in hexadecimal format.
113
+ */
65
114
  async signTransaction(safeOpHash) {
66
115
  const signature = await this.nearAdapter.sign(safeOpHash);
67
116
  return packSignature(signature);
68
117
  }
118
+ /**
119
+ * Computes the operation hash for a given user operation.
120
+ *
121
+ * @param {UserOperation} userOp - The user operation for which the hash needs to be computed.
122
+ * @returns {Promise<Hash>} - A promise that resolves to the hash of the provided user operation.
123
+ */
69
124
  async opHash(userOp) {
70
125
  return this.safePack.getOpHash(userOp);
71
126
  }
127
+ /**
128
+ * Encodes a request to sign a transaction using either a paymaster or the user's own funds.
129
+ *
130
+ * @param {SignRequestData} signRequest - The data required to create the signature request. This includes information such as the chain ID and other necessary fields for the transaction.
131
+ * @param {boolean} usePaymaster - Flag indicating whether to use a paymaster for gas fees. If true, the transaction will be sponsored by the paymaster.
132
+ * @returns {Promise<EncodedTxData>} - A promise that resolves to the encoded transaction data for the NEAR and EVM networks.
133
+ */
72
134
  async encodeSignRequest(signRequest, usePaymaster) {
73
135
  const { payload, evmMessage, hash } = await this.requestRouter(signRequest, usePaymaster);
74
136
  return {
@@ -84,12 +146,22 @@ export class NearSafe {
84
146
  },
85
147
  };
86
148
  }
149
+ /**
150
+ * Broadcasts a user operation to the EVM network with a provided signature.
151
+ * Warning: Uses a private ethRPC with sensitive Pimlico API key (should be run server side).
152
+ *
153
+ * @param {number} chainId - The ID of the EVM network to which the transaction should be broadcasted.
154
+ * @param {FinalExecutionOutcome} outcome - The result of the NEAR transaction execution, which contains the necessary data to construct an EVM signature.
155
+ * @param {UserOperation} unsignedUserOp - The unsigned user operation to be broadcasted. This includes transaction data such as the destination address and data payload.
156
+ * @returns {Promise<{ signature: Hex; opHash: Hash }>} - A promise that resolves to an object containing the signature used and the hash of the executed user operation.
157
+ * @throws {Error} - Throws an error if the EVM broadcast fails, including the error message for debugging.
158
+ */
87
159
  async broadcastEvm(chainId, outcome, unsignedUserOp) {
88
160
  const signature = packSignature(serializeSignature(signatureFromOutcome(outcome)));
89
161
  try {
90
162
  return {
91
163
  signature,
92
- receipt: await this.executeTransaction(chainId, {
164
+ opHash: await this.executeTransaction(chainId, {
93
165
  ...unsignedUserOp,
94
166
  signature,
95
167
  }),
@@ -99,19 +171,45 @@ export class NearSafe {
99
171
  throw new Error(`Failed EVM broadcast: ${error instanceof Error ? error.message : String(error)}`);
100
172
  }
101
173
  }
174
+ /**
175
+ * Executes a user operation on the specified blockchain network.
176
+ * Warning: Uses a private ethRPC with sensitive Pimlico API key (should be run server side).
177
+ *
178
+ * @param {number} chainId - The ID of the blockchain network on which to execute the transaction.
179
+ * @param {UserOperation} userOp - The user operation to be executed, typically includes the data and signatures necessary for the transaction.
180
+ * @returns {Promise<Hash>} - A promise that resolves to the hash of the executed transaction.
181
+ */
102
182
  async executeTransaction(chainId, userOp) {
103
- const bundler = this.bundlerForChainId(chainId);
104
- const userOpHash = await bundler.sendUserOperation(userOp);
105
- console.log("UserOp Hash", userOpHash);
106
- const userOpReceipt = await bundler.getUserOpReceipt(userOpHash);
107
- console.log("userOp Receipt", userOpReceipt);
108
- // Update safeNotDeployed after the first transaction
109
- this.safeDeployed(chainId);
110
- return userOpReceipt;
183
+ return this.bundlerForChainId(chainId).sendUserOperation(userOp);
111
184
  }
185
+ /**
186
+ * Retrieves the receipt of a previously executed user operation.
187
+ * Warning: Uses a private ethRPC with sensitive Pimlico API key (should be run server side).
188
+ *
189
+ * @param {number} chainId - The ID of the blockchain network where the operation was executed.
190
+ * @param {Hash} userOpHash - The hash of the user operation for which to retrieve the receipt.
191
+ * @returns {Promise<UserOperationReceipt>} - A promise that resolves to the receipt of the user operation, which includes status and logs.
192
+ */
193
+ async getOpReceipt(chainId, userOpHash) {
194
+ return this.bundlerForChainId(chainId).getUserOpReceipt(userOpHash);
195
+ }
196
+ /**
197
+ * Checks if the Safe contract is deployed on the specified chain.
198
+ *
199
+ * @param {number} chainId - The ID of the blockchain network where the Safe contract should be checked.
200
+ * @returns {Promise<boolean>} - A promise that resolves to `true` if the Safe contract is deployed, otherwise `false`.
201
+ */
112
202
  async safeDeployed(chainId) {
113
203
  return isContract(this.address, chainId);
114
204
  }
205
+ /**
206
+ * Determines if the Safe account has sufficient funds to cover the transaction costs.
207
+ *
208
+ * @param {number} chainId - The ID of the blockchain network where the Safe account is located.
209
+ * @param {MetaTransaction[]} transactions - A list of meta-transactions to be evaluated for funding.
210
+ * @param {bigint} gasCost - The estimated gas cost of executing the transactions.
211
+ * @returns {Promise<boolean>} - A promise that resolves to `true` if the Safe account has sufficient funds, otherwise `false`.
212
+ */
115
213
  async sufficientlyFunded(chainId, transactions, gasCost) {
116
214
  const txValue = transactions.reduce((acc, tx) => acc + BigInt(tx.value), 0n);
117
215
  if (txValue + gasCost === 0n) {
@@ -120,6 +218,12 @@ export class NearSafe {
120
218
  const safeBalance = await this.getBalance(chainId);
121
219
  return txValue + gasCost < safeBalance;
122
220
  }
221
+ /**
222
+ * Creates a meta-transaction for adding a new owner to the Safe contract.
223
+ *
224
+ * @param {Address} address - The address of the new owner to be added.
225
+ * @returns {MetaTransaction} - A meta-transaction object for adding the new owner.
226
+ */
123
227
  addOwnerTx(address) {
124
228
  return {
125
229
  to: this.address,
@@ -127,9 +231,21 @@ export class NearSafe {
127
231
  data: this.safePack.addOwnerData(address),
128
232
  };
129
233
  }
234
+ /**
235
+ * Creates and returns a new `Erc4337Bundler` instance for the specified chain.
236
+ *
237
+ * @param {number} chainId - The ID of the blockchain network for which the bundler is to be created.
238
+ * @returns {Erc4337Bundler} - A new instance of the `Erc4337Bundler` class configured for the specified chain.
239
+ */
130
240
  bundlerForChainId(chainId) {
131
241
  return new Erc4337Bundler(this.safePack.entryPoint.address, this.pimlicoKey, chainId);
132
242
  }
243
+ /**
244
+ * Decodes transaction data for a given EVM transaction and extracts relevant details.
245
+ *
246
+ * @param {EvmTransactionData} data - The raw transaction data to be decoded.
247
+ * @returns {{ chainId: number; costEstimate: string; transactions: MetaTransaction[] }} - An object containing the chain ID, estimated cost, and a list of decoded meta-transactions.
248
+ */
133
249
  decodeTxData(data) {
134
250
  // TODO: data.data may not always parse to UserOperation. We will have to handle the other cases.
135
251
  const userOp = JSON.parse(data.data);
@@ -139,7 +255,7 @@ export class NearSafe {
139
255
  abi: this.safePack.m4337.abi,
140
256
  data: userOp.callData,
141
257
  });
142
- // Determine if sungular or double!
258
+ // Determine if singular or double!
143
259
  const transactions = isMultisendTx(args)
144
260
  ? decodeMulti(args[2])
145
261
  : [
@@ -1,113 +1,247 @@
1
1
  import { FunctionCallTransaction, SignArgs } from "near-ca";
2
2
  import { Address, Hex, ParseAbi } from "viem";
3
+ /**
4
+ * Represents a collection of Safe contract deployments, each with its own address and ABI.
5
+ */
3
6
  export type SafeDeployments = {
7
+ /** Deployment for the singleton contract. */
4
8
  singleton: Deployment;
9
+ /** Deployment for the proxy factory contract. */
5
10
  proxyFactory: Deployment;
11
+ /** Deployment for the module setup contract. */
6
12
  moduleSetup: Deployment;
13
+ /** Deployment for the m4337 module contract. */
7
14
  m4337: Deployment;
15
+ /** Deployment for the entry point contract. */
8
16
  entryPoint: Deployment;
9
17
  };
18
+ /**
19
+ * Represents the details of a deployed contract, including its ABI and address.
20
+ */
10
21
  export interface Deployment {
22
+ /** The ABI of the deployed contract. Can be a raw ABI array or a parsed ABI. */
11
23
  abi: unknown[] | ParseAbi<readonly string[]>;
24
+ /** The address of the deployed contract. */
12
25
  address: Address;
13
26
  }
27
+ /**
28
+ * Represents an unsigned user operation that can be sent to the EntryPoint contract.
29
+ */
14
30
  export interface UnsignedUserOperation {
31
+ /** The sender's address initiating the user operation. */
15
32
  sender: Address;
33
+ /** The unique nonce associated with this user operation. */
16
34
  nonce: string;
35
+ /** The optional factory address to use for creating new contracts. */
17
36
  factory?: Address;
37
+ /** Optional additional data for the factory, typically used for contract initialization. */
18
38
  factoryData?: Hex;
39
+ /** The encoded data for the contract call or transaction execution. */
19
40
  callData: Hex;
41
+ /** Maximum priority fee per gas unit for the transaction. */
20
42
  maxPriorityFeePerGas: Hex;
43
+ /** Maximum fee per gas unit for the transaction. */
21
44
  maxFeePerGas: Hex;
22
45
  }
23
46
  /**
24
- * Supported Representation of UserOperation for EntryPoint v0.7
47
+ * Supported representation of a user operation for EntryPoint version 0.7, including gas limits and signature.
25
48
  */
26
49
  export interface UserOperation extends UnsignedUserOperation {
50
+ /** The gas limit for verification of the operation. */
27
51
  verificationGasLimit: Hex;
52
+ /** The gas limit for the execution of the operation call. */
28
53
  callGasLimit: Hex;
54
+ /** The gas used before verification begins. */
29
55
  preVerificationGas: Hex;
56
+ /** Optional signature for the user operation. */
30
57
  signature?: Hex;
31
58
  }
59
+ /**
60
+ * Represents additional paymaster-related data for a user operation.
61
+ */
32
62
  export interface PaymasterData {
63
+ /** Optional paymaster address responsible for covering gas costs. */
33
64
  paymaster?: Address;
65
+ /** Optional additional data required by the paymaster. */
34
66
  paymasterData?: Hex;
67
+ /** The gas limit for paymaster verification. */
35
68
  paymasterVerificationGasLimit?: Hex;
69
+ /** The gas limit for paymaster post-operation execution. */
36
70
  paymasterPostOpGasLimit?: Hex;
71
+ /** The gas limit for operation verification. */
37
72
  verificationGasLimit: Hex;
73
+ /** The gas limit for the operation call execution. */
38
74
  callGasLimit: Hex;
75
+ /** The gas used before verification begins. */
39
76
  preVerificationGas: Hex;
40
77
  }
78
+ /**
79
+ * User configuration options for transaction building and user operation execution.
80
+ */
41
81
  export interface UserOptions {
82
+ /** Whether to use a paymaster for gas fee coverage. */
42
83
  usePaymaster: boolean;
84
+ /** The unique nonce used to differentiate multiple Safe setups. */
43
85
  safeSaltNonce: string;
86
+ /** The NEAR contract ID for the MPC contract. */
44
87
  mpcContractId: string;
88
+ /** Optional recovery address in case of key compromise or other emergency situations. */
45
89
  recoveryAddress?: string;
46
90
  }
91
+ /**
92
+ * Represents the possible transaction statuses.
93
+ */
47
94
  export type TxStatus = "success" | "reverted";
95
+ /**
96
+ * Represents a log entry in a transaction receipt.
97
+ */
48
98
  interface Log {
99
+ /** The index of the log in the transaction. */
49
100
  logIndex: string;
101
+ /** The index of the transaction within the block. */
50
102
  transactionIndex: string;
103
+ /** The hash of the transaction containing the log. */
51
104
  transactionHash: string;
105
+ /** The hash of the block containing the transaction. */
52
106
  blockHash: string;
107
+ /** The number of the block containing the transaction. */
53
108
  blockNumber: string;
109
+ /** The address that generated the log. */
54
110
  address: string;
111
+ /** The raw data of the log. */
55
112
  data: string;
113
+ /** The topics associated with the log event. */
56
114
  topics: string[];
57
115
  }
116
+ /**
117
+ * Represents a transaction receipt returned by the blockchain.
118
+ */
58
119
  interface Receipt {
120
+ /** The hash of the transaction. */
59
121
  transactionHash: Hex;
122
+ /** The index of the transaction within the block. */
60
123
  transactionIndex: bigint;
124
+ /** The hash of the block containing the transaction. */
61
125
  blockHash: Hex;
126
+ /** The number of the block containing the transaction. */
62
127
  blockNumber: bigint;
128
+ /** The address from which the transaction originated. */
63
129
  from: Address;
130
+ /** Optional address to which the transaction was sent (if applicable). */
64
131
  to?: Address;
132
+ /** The cumulative gas used in the block up to this transaction. */
65
133
  cumulativeGasUsed: bigint;
134
+ /** The status of the transaction (success or reverted). */
66
135
  status: TxStatus;
136
+ /** The total gas used by this transaction. */
67
137
  gasUsed: bigint;
138
+ /** Optional address of a newly deployed contract (if applicable). */
68
139
  contractAddress?: Address;
140
+ /** The logs bloom filter for the transaction. */
69
141
  logsBloom: Hex;
142
+ /** The effective gas price used in the transaction. */
70
143
  effectiveGasPrice: bigint;
71
144
  }
145
+ /**
146
+ * Represents the receipt of a user operation including its details, logs, and result.
147
+ */
72
148
  export type UserOperationReceipt = {
149
+ /** The hash of the user operation. */
73
150
  userOpHash: Hex;
151
+ /** The address of the entry point contract handling the user operation. */
74
152
  entryPoint: Address;
153
+ /** The sender's address initiating the user operation. */
75
154
  sender: Address;
155
+ /** The nonce of the user operation. */
76
156
  nonce: bigint;
157
+ /** Optional paymaster address responsible for covering gas costs. */
77
158
  paymaster?: Address;
159
+ /** The actual gas used by the operation. */
78
160
  actualGasUsed: bigint;
161
+ /** The actual gas cost of the operation. */
79
162
  actualGasCost: bigint;
163
+ /** Whether the user operation succeeded or failed. */
80
164
  success: boolean;
165
+ /** Optional reason for failure if the operation was unsuccessful. */
81
166
  reason?: string;
167
+ /** The transaction receipt associated with the user operation. */
82
168
  receipt: Receipt;
169
+ /** The list of logs generated by the user operation. */
83
170
  logs: Log[];
84
171
  };
172
+ /**
173
+ * Represents the different gas prices for transaction execution based on priority levels.
174
+ */
85
175
  export interface GasPrices {
176
+ /** Gas price for slower transactions. */
86
177
  slow: GasPrice;
178
+ /** Gas price for standard transactions. */
87
179
  standard: GasPrice;
180
+ /** Gas price for fast transactions. */
88
181
  fast: GasPrice;
89
182
  }
183
+ /**
184
+ * Represents a specific gas price configuration for transaction execution.
185
+ */
90
186
  export interface GasPrice {
187
+ /** Maximum fee per gas unit for the transaction. */
91
188
  maxFeePerGas: Hex;
189
+ /** Maximum priority fee per gas unit for the transaction. */
92
190
  maxPriorityFeePerGas: Hex;
93
191
  }
192
+ /**
193
+ * Enum representing the type of operation in a meta-transaction.
194
+ */
94
195
  export declare enum OperationType {
196
+ /** Standard call operation (0). */
95
197
  Call = 0,
198
+ /** Delegate call operation (1). */
96
199
  DelegateCall = 1
97
200
  }
201
+ /**
202
+ * Represents a meta-transaction, which includes the destination address, value, data, and type of operation.
203
+ */
98
204
  export interface MetaTransaction {
205
+ /** The destination address for the meta-transaction. */
99
206
  readonly to: string;
207
+ /** The value to be sent with the transaction (as a string to handle large numbers). */
100
208
  readonly value: string;
209
+ /** The encoded data for the contract call or function execution. */
101
210
  readonly data: string;
211
+ /** Optional type of operation (call or delegate call). */
102
212
  readonly operation?: OperationType;
103
213
  }
214
+ /**
215
+ * Represents raw transaction data for an EVM transaction.
216
+ */
104
217
  export interface EvmTransactionData {
218
+ /** The chain ID of the network where the transaction is being executed. */
105
219
  chainId: number;
220
+ /** The raw data of the transaction. */
106
221
  data: string;
222
+ /** The hash of the transaction. */
107
223
  hash: string;
108
224
  }
225
+ /**
226
+ * Represents the decoded details of a multisend transaction.
227
+ */
228
+ export interface DecodedMultisend {
229
+ /** The chain ID of the network where the multisend transaction is being executed. */
230
+ chainId: number;
231
+ /** The estimated cost of the multisend transaction in Ether.
232
+ * This is an upper bound on the transaction fee (could wind up lower).
233
+ */
234
+ costEstimate: string;
235
+ /** The list of meta-transactions included in the multisend. */
236
+ transactions: MetaTransaction[];
237
+ }
238
+ /**
239
+ * Represents encoded transaction data for both NEAR and EVM networks.
240
+ */
109
241
  export interface EncodedTxData {
242
+ /** The encoded transaction data for the EVM network. */
110
243
  evmData: EvmTransactionData;
244
+ /** The encoded payload for a NEAR function call, including the signing arguments. */
111
245
  nearPayload: FunctionCallTransaction<{
112
246
  request: SignArgs;
113
247
  }>;
package/dist/esm/types.js CHANGED
@@ -1,5 +1,10 @@
1
+ /**
2
+ * Enum representing the type of operation in a meta-transaction.
3
+ */
1
4
  export var OperationType;
2
5
  (function (OperationType) {
6
+ /** Standard call operation (0). */
3
7
  OperationType[OperationType["Call"] = 0] = "Call";
8
+ /** Delegate call operation (1). */
4
9
  OperationType[OperationType["DelegateCall"] = 1] = "DelegateCall";
5
10
  })(OperationType || (OperationType = {}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "near-safe",
3
- "version": "0.4.2",
3
+ "version": "0.5.1",
4
4
  "license": "MIT",
5
5
  "description": "An SDK for controlling Ethereum Smart Accounts via ERC4337 from a Near Account.",
6
6
  "author": "bh2smith",
@@ -44,7 +44,7 @@
44
44
  "@safe-global/safe-gateway-typescript-sdk": "^3.22.2",
45
45
  "ethers-multisend": "^3.1.0",
46
46
  "near-api-js": "^5.0.0",
47
- "near-ca": "^0.5.6",
47
+ "near-ca": "^0.5.7",
48
48
  "semver": "^7.6.3",
49
49
  "viem": "^2.16.5"
50
50
  },