-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy patherc-20-private-payment-hinkal.ts
More file actions
255 lines (228 loc) · 9.41 KB
/
erc-20-private-payment-hinkal.ts
File metadata and controls
255 lines (228 loc) · 9.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import { BigNumber, BigNumberish, Contract, ContractTransaction, providers, Signer } from 'ethers';
import { erc20FeeProxyArtifact } from '@requestnetwork/smart-contracts';
import {
ERC20__factory,
ERC20FeeProxy__factory,
ERC20Proxy__factory,
} from '@requestnetwork/smart-contracts/types';
import { ClientTypes, ExtensionTypes } from '@requestnetwork/types';
import { Erc20PaymentNetwork, getPaymentNetworkExtension } from '@requestnetwork/payment-detection';
import { EvmChains } from '@requestnetwork/currency';
import {
getAmountToPay,
getProvider,
getProxyAddress,
getRequestPaymentValues,
getSigner,
validateErc20FeeProxyRequest,
validateRequest,
} from './utils';
import { IPreparedPrivateTransaction } from './prepared-transaction';
import { getERC20Token, type IHinkal, type RelayerTransaction } from '@hinkal/common';
/**
* This is a globally accessible state variable exported for use in other parts of the application or tests.
*/
export const hinkalStore: Record<string, IHinkal> = {};
/**
* Adds an IHinkal instance to the Hinkal store for a given signer.
*
* This function checks if an IHinkal instance already exists for the provided signer’s address in the `hinkalStore`.
* If it does not exist, it initializes the instance using `prepareEthersHinkal` and stores it. The existing or newly
* created instance is then returned.
*
* @param signer - The signer for which the IHinkal instance should be added or retrieved.
*/
export async function addToHinkalStore(signer: Signer): Promise<IHinkal> {
const address = await signer.getAddress();
if (!hinkalStore[address]) {
const { prepareEthersHinkal } = await import('@hinkal/common/providers/prepareEthersHinkal');
hinkalStore[address] = await prepareEthersHinkal(signer);
}
return hinkalStore[address];
}
/**
* Sends ERC20 tokens into a Hinkal shielded address.
*
* @param signerOrProvider the Web3 provider, or signer.
* @param tokenAddress - The address of the ERC20 token being sent.
* @param amount - The amount of tokens to send.
* @param recipientInfo - (Optional) The shielded address of the recipient. If provided, the tokens will be deposited into the recipient's shielded balance. If not provided, the deposit will increase the sender's shielded balance.
*
* @returns A promise that resolves to a `ContractTransaction`.
*/
export async function sendToHinkalShieldedAddressFromPublic(
signerOrProvider: providers.Provider | Signer = getProvider(),
tokenAddress: string,
amount: BigNumberish,
recipientInfo?: string,
): Promise<ContractTransaction> {
const signer = getSigner(signerOrProvider);
const hinkalObject = await addToHinkalStore(signer);
const token = getERC20Token(tokenAddress, await signer.getChainId());
if (!token) throw Error();
const amountToPay = BigNumber.from(amount).toBigInt();
if (recipientInfo) {
return hinkalObject.depositForOther([token], [amountToPay], recipientInfo);
} else {
return hinkalObject.deposit([token], [amountToPay]);
}
}
/**
* Sends a batch of payments to Hinkal shielded addresses from a public address.
* @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum.
* @param tokenAddresses the addresses of the ERC20 tokens to send.
* @param amounts the amounts of tokens to send.
* @param recipientInfos include the shielded addresses of the recipients.
*/
export async function sendBatchPaymentsToHinkalShieldedAddressesFromPublic(
signerOrProvider: providers.Provider | Signer = getProvider(),
tokenAddresses: string[],
amounts: BigNumberish[],
recipientInfos: string[],
): Promise<ContractTransaction> {
const signer = getSigner(signerOrProvider);
const hinkalObject = await addToHinkalStore(signer);
const chainId = await signer.getChainId();
const tokens = tokenAddresses.map((tokenAddress) => {
const token = getERC20Token(tokenAddress, chainId);
if (!token) throw Error('Token cannot be found');
return token;
});
const amountsToPay = amounts.map((amount) => BigNumber.from(amount).toBigInt());
console.log({ tokens, amountsToPay, recipientInfos });
const tx = await hinkalObject.multiSendPrivateRecipients(tokens, amountsToPay, recipientInfos);
return tx;
}
/**
* Processes a transaction to pay privately a request through the ERC20 fee proxy contract.
* @param request request to pay.
* @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum.
* @param amount optionally, the amount to pay. Defaults to remaining amount of the request.
*/
export async function payErc20ProxyRequestFromHinkalShieldedAddress(
request: ClientTypes.IRequestData,
signerOrProvider: providers.Provider | Signer = getProvider(),
amount?: BigNumberish,
): Promise<RelayerTransaction> {
const signer = getSigner(signerOrProvider);
const hinkalObject = await addToHinkalStore(signer);
const { amountToPay, tokenAddress, ops } =
await prepareErc20ProxyPaymentFromHinkalShieldedAddress(request, amount);
return hinkalObject.actionPrivateWallet(
[tokenAddress],
[-amountToPay],
[false],
ops,
) as Promise<RelayerTransaction>;
}
/**
* Processes a transaction to pay privately a request through the ERC20 fee proxy.
* @param request request to pay.
* @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum.
* @param amount optionally, the amount to pay. Defaults to remaining amount of the request.
* @param feeAmount optionally, the fee amount to pay. Defaults to the fee amount of the request.
*/
export async function payErc20FeeProxyRequestFromHinkalShieldedAddress(
request: ClientTypes.IRequestData,
signerOrProvider: providers.Provider | Signer = getProvider(),
amount?: BigNumberish,
feeAmount?: BigNumberish,
): Promise<RelayerTransaction> {
const signer = getSigner(signerOrProvider);
const hinkalObject = await addToHinkalStore(signer);
const { amountToPay, tokenAddress, ops } =
await prepareErc20FeeProxyPaymentFromHinkalShieldedAddress(request, amount, feeAmount);
return hinkalObject.actionPrivateWallet(
[tokenAddress],
[-amountToPay],
[false],
ops,
) as Promise<RelayerTransaction>;
}
/**
* Prepare the transaction to privately pay a request through the ERC20 proxy contract, can be used with a Multisig contract.
* @param request request to pay
* @param amount optionally, the amount to pay. Defaults to remaining amount of the request.
*/
export async function prepareErc20ProxyPaymentFromHinkalShieldedAddress(
request: ClientTypes.IRequestData,
amount?: BigNumberish,
): Promise<IPreparedPrivateTransaction> {
validateRequest(request, ExtensionTypes.PAYMENT_NETWORK_ID.ERC20_PROXY_CONTRACT);
const { value: tokenAddress } = request.currencyInfo;
const proxyAddress = getProxyAddress(
request,
Erc20PaymentNetwork.ERC20ProxyPaymentDetector.getDeploymentInformation,
);
const tokenContract = new Contract(tokenAddress, ERC20__factory.createInterface());
const proxyContract = new Contract(proxyAddress, ERC20Proxy__factory.createInterface());
const { paymentReference, paymentAddress } = getRequestPaymentValues(request);
const amountToPay = getAmountToPay(request, amount);
const { emporiumOp } = await import('@hinkal/common');
const ops = [
emporiumOp({
contract: tokenContract,
func: 'approve',
args: [proxyContract.address, amountToPay],
}),
emporiumOp({
contract: proxyContract,
func: 'transferFromWithReference',
args: [tokenAddress, paymentAddress, amountToPay, `0x${paymentReference}`],
}),
];
return {
amountToPay: amountToPay.toBigInt(),
tokenAddress,
ops,
};
}
/**
* Prepare the transaction to privately pay a request through the ERC20 fee proxy contract, can be used with a Multisig contract.
* @param request request to pay
* @param amount optionally, the amount to pay. Defaults to remaining amount of the request.
* @param feeAmountOverride optionally, the fee amount to pay. Defaults to the fee amount of the request.
*/
export async function prepareErc20FeeProxyPaymentFromHinkalShieldedAddress(
request: ClientTypes.IRequestData,
amount?: BigNumberish,
feeAmountOverride?: BigNumberish,
): Promise<IPreparedPrivateTransaction> {
validateErc20FeeProxyRequest(request, amount, feeAmountOverride);
const { value: tokenAddress, network } = request.currencyInfo;
EvmChains.assertChainSupported(network!);
const pn = getPaymentNetworkExtension(request);
const proxyAddress = erc20FeeProxyArtifact.getAddress(network, pn?.version);
const tokenContract = new Contract(tokenAddress, ERC20__factory.createInterface());
const proxyContract = new Contract(proxyAddress, ERC20FeeProxy__factory.createInterface());
const { paymentReference, paymentAddress, feeAddress, feeAmount } =
getRequestPaymentValues(request);
const amountToPay = getAmountToPay(request, amount);
const feeToPay = String(feeAmountOverride || feeAmount || 0);
const totalAmount = amountToPay.add(BigNumber.from(feeToPay));
const { emporiumOp } = await import('@hinkal/common');
const ops = [
emporiumOp({
contract: tokenContract,
func: 'approve',
args: [proxyContract.address, totalAmount],
}),
emporiumOp({
contract: proxyContract,
func: 'transferFromWithReferenceAndFee',
args: [
tokenAddress,
paymentAddress,
amountToPay,
`0x${paymentReference}`,
feeToPay,
feeAddress,
],
}),
];
return {
amountToPay: totalAmount.toBigInt(),
tokenAddress,
ops,
};
}