• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Mintbase / mintbase-js / 8189415147

07 Mar 2024 02:05PM CUT coverage: 76.955%. First build
8189415147

Pull #480

github

tifrel
Remove duplicate import
Pull Request #480: Enable arweave uploads from NodeJS

860 of 1307 branches covered (65.8%)

Branch coverage included in aggregate %.

1 of 1 new or added line in 1 file covered. (100.0%)

1177 of 1340 relevant lines covered (87.84%)

13.24 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

47.46
/packages/sdk/src/execute/execute.utils.ts
1
import type { Wallet, FinalExecutionOutcome } from '@near-wallet-selector/core';
2
import type { providers, Account } from 'near-api-js';
3
import type {
4
  CallBackArgs,
5
  ContractCall,
6
  TxnOptionalSignerId,
7
  NearExecuteOptions,
8
  ExecuteArgsResponse,
9
  ComposableCall,
10
} from '../types';
11
import BN from 'bn.js';
3✔
12
import { NoSigningMethodPassedError } from '../errors';
3✔
13

14
/**
15
 * checkCallbackUrl()
16
 * method to check if its a regular browser wallet or a InjectedWallet, and make them have the same behavior (redirect) to the desired url.
17
 * @param callbackUrl url that should redirect after transaction
18
 * @param callbackArgs metadata that should be passed via url to the success page
19
 * @returns an outcome object or an array of outcome objects if batching calls {@link FinalExecutionOutcome[]} | {@link FinalExecutionOutcome}, or a redirect to selected callbackUrl
20
 */
21
export const checkCallbackUrl = (
3✔
22
  callbackUrl: string,
23
  callbackArgs: CallBackArgs,
24
  wallet: Wallet,
25
  outcomes: void | FinalExecutionOutcome[],
26
): void | FinalExecutionOutcome[] | FinalExecutionOutcome => {
27
  const isNotBrowserWallet = wallet?.type !== 'browser';
18✔
28
  const hasCallbackUrl = Boolean(
18✔
29
    typeof window !== 'undefined' && callbackUrl?.length > 0,
12!
30
  );
31

32
  if (hasCallbackUrl && isNotBrowserWallet) {
18!
33
    const { transactionHash } = checkTransactionHash(outcomes);
×
34

35
    let finalUrl = `${callbackUrl}?transactionHashes=${transactionHash}`;
×
36

37
    if (callbackArgs) {
×
38
      const args = JSON.stringify({
×
39
        type: callbackArgs?.type ?? '',
×
40
        args: callbackArgs?.args ?? '',
×
41
      });
42

43
      const signMeta = encodeURIComponent(args);
×
44

45
      finalUrl = `${callbackUrl}?transactionHashes=${transactionHash}&signMeta=${signMeta}`;
×
46
    }
47
    return window.location.assign(finalUrl);
×
48
  }
49

50
  return outcomes && outcomes.length == 1 ? outcomes[0] : outcomes;
18✔
51
};
52

53
/**
54
 * checkTransactionHash()
55
 * check what transaction receipt to return to the user.
56
 * @param receipt near transaction Receipt object
57
 * @returns transactionHash object
58
 */
59
const checkTransactionHash = (receipt): { transactionHash: string } => {
3✔
60
  let transactionHash = receipt?.transaction_outcome?.id;
×
61

62
  if (receipt?.length == 1) {
×
63
    transactionHash = receipt[0]?.transaction_outcome?.id;
×
64
  }
65

66
  if (receipt?.length > 1) {
×
67
    transactionHash = receipt[1]?.transaction_outcome?.id;
×
68
  }
69

70
  return { transactionHash };
×
71
};
72

73
export const callbackUrlFormatter = (
3✔
74
  callbackUrl: string,
75
  callbackArgs: CallBackArgs,
76
): string => {
77
  let url =
78
    callbackUrl && typeof callbackUrl !== 'undefined' ? callbackUrl : null;
18✔
79

80
  if (callbackArgs?.type && callbackUrl) {
18!
81
    const args = JSON.stringify({
×
82
      type: callbackArgs?.type,
×
83
      args: callbackArgs?.args,
×
84
    });
85

86
    const signMeta = encodeURIComponent(args);
×
87
    url = `${callbackUrl}?signMeta=${signMeta}`;
×
88
  }
89

90
  return url;
18✔
91
};
92

93
export const genericBatchExecute = async (
3✔
94
  call: ContractCall<ExecuteArgsResponse>[],
95
  wallet: Wallet,
96
  account: Account,
97
  callbackUrl: string,
98
  callbackArgs: CallBackArgs,
99
): Promise<void | providers.FinalExecutionOutcome[]> => {
18✔
100
  const url = callbackUrlFormatter(callbackUrl, callbackArgs);
18✔
101
  if (wallet) {
18✔
102
    return url
9✔
103
      ? batchExecuteWithBrowserWallet(call, wallet, url, callbackArgs)
104
      : batchExecuteWithBrowserWallet(call, wallet);
105
  }
106
  return batchExecuteWithNearAccount(call, account, url);
9✔
107
};
108

109
// account call translation wrappers https://docs.near.org/tools/near-api-js/faq#how-to-send-batch-transactions
110
// TODO: share batch signature with wallet selector sendAndSignTransaction when method becomes public
111
const batchExecuteWithNearAccount = async (
3✔
112
  calls: ContractCall<ExecuteArgsResponse>[],
113
  account: Account,
114
  callbackUrl?: string,
115
): Promise<FinalExecutionOutcome[]> => {
9✔
116
  const outcomes: FinalExecutionOutcome[] = [];
9✔
117
  for (const call of calls) {
9✔
118
    try {
27✔
119
      outcomes.push(
27✔
120
        await account.functionCall({
121
          contractId: call.contractAddress,
122
          methodName: call.methodName,
123
          args: call.args,
124
          gas: new BN(call.gas),
125
          attachedDeposit: new BN(call.deposit),
126
          ...(callbackUrl && { walletCallbackUrl: callbackUrl }),
18!
127
        }),
128
      );
129
    } catch (err: unknown) {
130
      console.error(
9✔
131
        `${call.contractAddress}:${call.methodName} in batch failed: ${err}`,
132
      );
133
    }
134
  }
135

136
  return outcomes;
9✔
137
};
138

139
const batchExecuteWithBrowserWallet = async (
3✔
140
  calls: ContractCall<ExecuteArgsResponse>[],
141
  wallet: Wallet,
142
  callback?: string,
143
  callbackArgs?: CallBackArgs,
144
): Promise<void | FinalExecutionOutcome[]> => {
9✔
145
  const res = await wallet.signAndSendTransactions({
9✔
146
    transactions: calls.map(
147
      convertGenericCallToWalletCall,
148
    ) as TxnOptionalSignerId[],
149
    ...(callback && { callbackUrl: callback }),
8✔
150
    ...(callbackArgs && { callbackArgs: callbackArgs }),
6!
151
  });
152

153
  return res;
9✔
154
};
155

156
export const convertGenericCallToWalletCall = (
3✔
157
  call: ContractCall<ExecuteArgsResponse>,
158
): TxnOptionalSignerId => {
159
  return {
15✔
160
    signerId: call.signerId,
161
    receiverId: call.contractAddress,
162
    actions: [
163
      {
164
        type: 'FunctionCall',
165
        params: {
166
          methodName: call.methodName,
167
          args: call.args,
168
          gas: call.gas as string,
169
          deposit: call.deposit as string,
170
        },
171
      },
172
    ],
173
  };
174
};
175

176
export function flattenArgs(
3✔
177
  calls: ComposableCall[],
178
): ContractCall<ExecuteArgsResponse>[] {
179
  const contractCalls: ContractCall<ExecuteArgsResponse>[] = [];
18✔
180
  for (const call of calls) {
18✔
181
    if (
33✔
182
      call instanceof Array &&
38✔
183
      call.length > 0 &&
184
      (call as ContractCall<ExecuteArgsResponse>[])
185
    ) {
186
      call.map((item: ComposableCall) =>
12✔
187
        contractCalls.push(item as ContractCall<ExecuteArgsResponse>),
21✔
188
      );
189
    } else {
190
      contractCalls.push(call as ContractCall<ExecuteArgsResponse>);
21✔
191
    }
192
  }
193
  return contractCalls;
18✔
194
}
195

196
export const validateSigningOptions = ({
3✔
197
  wallet,
198
  account,
199
}: NearExecuteOptions): void => {
200
  if (!wallet && !account) {
21✔
201
    throw NoSigningMethodPassedError;
3✔
202
  }
203
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc