-
Notifications
You must be signed in to change notification settings - Fork 3
/
recurring_payment_script.ts
186 lines (163 loc) · 6.26 KB
/
recurring_payment_script.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
import axios, { AxiosInstance } from 'axios'
import * as xrpl from 'xrpl'
import { XrplService } from './xrpl.service'
import { EnclaveService } from './enclave.service'
import {
checkTxResponseSucceeded,
hexToUint8Array,
txnAfterSign,
txnBeforeSign,
uint8ArrayToHex,
} from './xrpl.util'
import { withLoggedExchange } from './console.helpers'
import { panic } from './panic'
import { IssuedCurrencyAmount } from 'xrpl/dist/npm/models/common'
// Create instances of XrplService and EnclaveService
const xrplService = new XrplService()
const enclaveService = new EnclaveService(createAxiosInstance())
const API_BASE_URL = 'https://wallet-staging-api.ntls.io'
const ISSUER = 'rpJv16Qmn2rQP6UC6UFsNRnVy5arkQihPP'
// Function to create an instance of Axios with default configuration
function createAxiosInstance(): AxiosInstance {
return axios.create({
baseURL: API_BASE_URL,
})
}
// Function to call the check_recurring_payments API
async function checkRecurringPayments() {
try {
const response = await axios.get(
`${API_BASE_URL}/recurring/payments/today`
)
const recurringPayments = response.data
// Process the recurring payments as needed
console.log('1. Check Recurring Payments:', recurringPayments)
for (const payment of recurringPayments) {
// 2. Create unsigned transactions
const { wallet_id, recipient, amount, currency_code } = payment
const fromAddress = wallet_id
const toAddress = recipient
let convertedAmount: string | IssuedCurrencyAmount = ''
if (currency_code === 'XRP') {
convertedAmount = xrpl.xrpToDrops(amount)
} else {
convertedAmount = {
currency: currency_code,
issuer: ISSUER,
value: amount.toString(),
}
}
const unsignedTx =
await xrplService.createUnsignedPaymentTransaction(
fromAddress,
toAddress,
convertedAmount
)
console.log('2. Create Unsigned Transaction:', unsignedTx)
// 3. Sign transactions
const { txnBeingSigned, bytesToSignEncoded } = txnBeforeSign(
unsignedTx,
payment.wallet_public_key
)
const transactionToSign = {
XrplTransaction: {
transaction_bytes: hexToUint8Array(bytesToSignEncoded),
},
}
const signRequest = {
wallet_id: fromAddress,
transaction_to_sign: transactionToSign,
}
console.log('3. Signed Transactions:')
const signResult = await withLoggedExchange(
'EnclaveService.signTransactionRecurringPayment:',
async () =>
enclaveService.signTransactionRecurringPayment(signRequest),
signRequest
)
if ('Signed' in signResult) {
const signed = signResult.Signed
if ('XrplTransactionSigned' in signed) {
const { signature_bytes } = signed.XrplTransactionSigned
const txnSignedEncoded = txnAfterSign(
txnBeingSigned,
uint8ArrayToHex(signature_bytes)
).txnSignedEncoded
// 4. Submit transactions
const txResponse = await withLoggedExchange(
'4. Submit transaction: signed, submitting:',
async () =>
xrplService.submitAndWaitForSigned(
txnSignedEncoded
),
txnSignedEncoded
)
const txSucceeded = checkTxResponseSucceeded(txResponse)
console.log(txResponse)
// 5. Call update_last_paid
if (txSucceeded.succeeded) {
const today = new Date()
console.log('Today:', today)
const ordinalValue = getDateToOrdinal(today)
console.log('ordidnalValue: ', ordinalValue)
await updateLastPaid(payment.id, ordinalValue)
console.log(
`[${ordinalValue}] Last paid date updated successfully for recurring payment ID ${payment.id}`
)
}
} else {
throw panic(
'SessionXrplService.sendTransaction: expected XrplTransactionSigned, got:',
signed
)
}
} else if ('Failed' in signResult) {
throw panic(
`signTransactionRecurringPayment failed: ${signResult.Failed}`,
signResult
)
}
}
} catch (error) {
console.error('Error occurred:', error)
}
}
// Function to call the update_last_paid API
async function updateLastPaid(
recurring_payment_id: string,
last_paid_date: number
) {
try {
await axios.put(
`${API_BASE_URL}/recurring/payment/update-last-paid-date`,
{
recurring_payment_id,
last_paid_date,
}
)
} catch (error) {
console.error('Error occurred while updating last paid date:', error)
}
}
checkRecurringPayments()
const _DAYS_IN_MONTH: number[] = [
-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
]
function isLeapYear(year: number): boolean {
// year -> 1 if leap year, else 0.
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)
}
function getDateToOrdinal(date: Date): number {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
return (
(year - 1) * 365 +
Math.floor((year - 1) / 4) -
Math.floor((year - 1) / 100) +
Math.floor((year - 1) / 400) +
_DAYS_IN_MONTH.slice(1, month).reduce((acc, curr) => acc + curr, 0) +
(month > 2 && isLeapYear(year) ? 1 : 0) +
day
)
}