-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
378 lines (300 loc) · 9.94 KB
/
index.ts
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import axios from "axios"
import { ethers, Signer } from "ethers"
import tokenABI from "./abi.json"
import onerampABI from "./abit.json"
import { createTransaction } from "./shared/transactions"
import addresses, { IfcOneNetworksAddresses } from "./src/utils/address"
import Request from "./src/utils/request"
import { KYCFormI } from "./types"
type Network = "bscTestnet" | "bsc" | "celo" | "alfajores" | "mumbai"
type Token =
| "stable"
| "usdt"
| "dai"
| "0xc0EBB770F2c9CA7eD0dDeBa58Af101695Cf1BDc1"
function getTokenAddress(tokenName: Token, network: Network) {
const tokenAddress = addresses[network][tokenName]
return tokenAddress
}
export class OneRamp {
private signer: Signer | undefined
// @ts-ignore
provider: ethers.providers.Provider | undefined
network: Network
private pubKey: string
private secretKey: string
private addresses: IfcOneNetworksAddresses
constructor(
network: Network,
pubKey: string,
secretKey: string,
// @ts-ignore
provider?: ethers.providers.Provider,
signer?: Signer
) {
this.network = network
this.provider = provider
this.signer = signer
this.addresses = addresses[this.network]
this.pubKey = pubKey
this.secretKey = secretKey
}
/*
Verify application creds middleware
This is a private function, and it will only be accessed and called from the class body
*/
private verifyCreds = async (): Promise<{
success: boolean
status: Number
message: String
store: string | null
}> => {
if (!this.pubKey || !this.secretKey) {
return {
success: false,
status: 404,
message: "No Credentials detected!",
store: null,
}
}
const request = new Request()
/*
Extract the wanted store information from the db by matching the public and secret key that was entered
THIS LINE CAN BE REPLACED WITH AN EXTRACT CALL TO THE DB
*/
const data = {
clientId: this.pubKey,
secret: this.secretKey,
}
const authenticated: any = await request.db(data)
return authenticated
}
private async requiresUserKYCApproved(): Promise<any> {
const request = new Request()
const data = {
clientId: this.pubKey,
secret: this.secretKey,
}
const approved = await request.kycApproved(data)
return approved
}
private async createUserKYC(data: KYCFormI): Promise<KYCFormI | undefined> {
const request = new Request()
const credentials = {
client: this.pubKey,
secret: this.secretKey,
}
const created = await request.createKYC(data, credentials)
return created
}
private setSigner = (signer: Signer) => {
this.signer = signer
}
// @ts-ignore
private setProvider = (provider: ethers.providers.Provider) => {
this.provider = provider
}
async offramp(
token: Token,
amount: number,
phoneNumber: string
): Promise<void> {
const result = await this.verifyCreds()
/* This will return true when the user creds are available in the db and false if they're not available */
// Verify if the user app requires KYC approved for the user here...
// const requiresKYC = await this.requiresUserKYCApproved()
// if (requiresKYC)
// throw new Error(
// "User has not completed/approved their KYC " + requiresKYC
// )
if (!result.success) throw new Error("Invalid credentials")
if (!this.signer) throw new Error("No signer set")
const signer = this.signer
if (!this.provider) throw new Error("No provider set")
const provider = this.provider
const tokenAddress = getTokenAddress(token, this.network)
if (!tokenAddress) {
throw new Error("Services for this token not supported")
}
const tokenContract = new ethers.Contract(tokenAddress, tokenABI, signer)
const approveTx = await tokenContract.approve(
addresses[this.network].contract,
// @ts-ignore
ethers.utils.parseEther(amount.toString())
)
await provider.waitForTransaction(approveTx.hash, 1)
const signerAddress = await signer.getAddress()
const allowance = await tokenContract.allowance(
signerAddress,
addresses[this.network].contract
)
// @ts-ignore
if (allowance < ethers.utils.parseEther(amount.toString()))
throw new Error(
"Insufficient allowance. Please approve more tokens before depositing."
)
const offRampAddress = addresses[this.network].contract
const oneRampContract = new ethers.Contract(
offRampAddress,
onerampABI,
signer
)
const tx = await oneRampContract.depositToken(
tokenAddress,
// @ts-ignore
ethers.utils.parseEther(amount.toString())
)
// Wait for 2 block confirmations.
await provider.waitForTransaction(tx.hash, 2)
// console.log("Deposit successful. Transaction hash:", tx.hash)
// const testTXHash = uuid()
// console.log("Deposit successful. Transaction hash:", testTXHash)
const fiat = await axios
.get("https://open.er-api.com/v6/latest/USD")
.then((res) => {
const rate = res.data.rates.UGX.toFixed(0)
const fiat = rate * amount
// console.log("Fiat amount:", fiat)
return fiat
})
// Create a new transaction in the database.
const newTransaction = {
store: result.store,
txHash: tx.hash,
// txHash: testTXHash,
amount: amount,
fiat: fiat,
network: this.network,
phone: phoneNumber,
asset: token,
status: "Pending",
}
const txData = await createTransaction(newTransaction)
return txData
}
async quote(initialAmount: number, token: Token) {
const withdrawalFeePercentage = 2.0 // Example withdrawal fee percentage
const withdrawalFee = (initialAmount * withdrawalFeePercentage) / 100
const finalAmount = initialAmount - withdrawalFee
const data = {
recives: finalAmount,
estimated_fee: withdrawalFee,
amount: initialAmount,
asset: token,
memo: "Prices may vary with local service providers",
}
return data
}
/*
This document will allow app create KYC links for their user for verifications
This can only be used under the condition that the user has enabled Require KYC verification for their app
*/
async createKYCVerification(kycData: KYCFormI) {
const result = await this.verifyCreds()
/* This will return true when the user creds are available in the db and false if they're not available */
// Verify if the user app requires KYC approved for the user here...
const requiresKYC = await this.requiresUserKYCApproved()
if (!requiresKYC)
throw new Error(
"App doesnot require users to complete/approve their KYC to make transactions "
)
if (!result.success) throw new Error("Invalid credentials")
// Creates the User's KYC request form here basing on the their payout address
const createdKYCRequest = await this.createUserKYC(kycData)
return createdKYCRequest
}
/*
This method returns all the store's active transactions
*/
async getTransactions() {}
}
/*
export class offramp {
signer: Signer | undefined
provider: ethers.providers.Provider | undefined
network: Network
addresses: IfcOneNetworksAddresses
constructor(
network: Network,
provider?: ethers.providers.Provider,
signer?: Signer
) {
this.network = network
this.provider = provider
this.signer = signer
this.addresses = addresses[this.network]
}
setSigner = (signer: Signer) => {
this.signer = signer
}
setProvider = (provider: ethers.providers.Provider) => {
this.provider = provider
}
async approve(tokenAddress: string, amount: number): Promise<boolean> {
if (!this.signer) throw new Error("No signer set")
const signer = this.signer
if (!this.provider) throw new Error("No provider set")
const provider = this.provider
const allAddresses = getAllAddresses(addresses)
if (!allAddresses.includes(tokenAddress)) {
throw new Error("Invalid token address")
}
const tokenContract = new ethers.Contract(tokenAddress, tokenABI, signer)
const approveTx = await tokenContract.approve(
addresses[this.network].contract,
ethers.utils.parseEther(amount.toString())
)
const receipt = await provider.waitForTransaction(approveTx.hash, 1)
console.log("Transaction mined:", receipt)
return true
}
async offramp(
tokenAddress: string,
amount: number,
phoneNumber: string
): Promise<any> {
if (!this.signer) throw new Error("No signer set")
const signer = this.signer
if (!this.provider) throw new Error("No provider set")
const provider = this.provider
const allAddresses = getAllAddresses(addresses)
if (!allAddresses.includes(tokenAddress)) {
throw new Error("Invalid token address")
}
const tokenContract = new ethers.Contract(tokenAddress, tokenABI, signer)
const signerAddress = await signer.getAddress()
const allowance = await tokenContract.allowance(
signerAddress,
addresses[this.network].contract
)
// console.log("Current allowance:", allowance.toString())
if (allowance < ethers.utils.parseEther(amount.toString()))
throw new Error(
"Insufficient allowance. Please approve more tokens before depositing."
)
const offRampAddress = addresses[this.network].contract
const oneRampContract = new ethers.Contract(
offRampAddress,
onerampABI,
signer
)
const tx = await oneRampContract.depositToken(
tokenAddress,
ethers.utils.parseEther(amount.toString())
)
// Wait for 2 block confirmations.
await provider.waitForTransaction(tx.hash, 2)
console.log("Deposit successful. Transaction hash:", tx.hash)
const newTransaction = {
store: "64650ac97b7e3975e9ee9133",
txHash: tx.hash,
amount: amount,
fiat: amount,
phone: phoneNumber,
asset: "cUSD",
status: "Success",
}
return newTransaction
}
}
*/