Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1f5344454 | ||
|
|
6658614db0 | ||
|
|
051e475b44 | ||
|
|
2ece12d44b | ||
|
|
79b6b914aa | ||
|
|
38231b15cb | ||
|
|
a950fd2ead | ||
|
|
7421d8574b | ||
|
|
92cca8a420 | ||
|
|
f94687788d | ||
|
|
fee63db19e | ||
|
|
4a866731f3 | ||
|
|
bf686e6f08 | ||
|
|
b5c330e311 | ||
|
|
eea05adea1 | ||
|
|
a3f4587d1e | ||
|
|
4e01e9809e | ||
|
|
e7a8dd9681 | ||
|
|
0ae8a9be0f | ||
|
|
647e1b96b1 | ||
|
|
ca239fbce4 | ||
|
|
963c80aaa0 | ||
|
|
be344b97f7 | ||
|
|
59d23a2dc7 | ||
|
|
8a91be6a15 | ||
|
|
8ff1bce889 | ||
|
|
5791328de4 | ||
|
|
566aa5a486 | ||
|
|
78db081b35 | ||
|
|
c592d3fb7a | ||
|
|
5cb1d6f099 | ||
|
|
ebff24a190 | ||
|
|
5a1f9def13 | ||
|
|
448cda9022 | ||
|
|
6784a98c8e | ||
|
|
d54669a8aa | ||
|
|
5b3a1ded6d | ||
|
|
144cdb8c40 | ||
|
|
9131b9d5c4 | ||
|
|
2fdb6e81d3 | ||
|
|
07164853c3 | ||
|
|
3a1201e485 | ||
|
|
a88d36918a | ||
|
|
46665ce060 | ||
|
|
a4ed778a94 | ||
|
|
03980768c7 | ||
|
|
79a67fa942 | ||
|
|
6f1b1ef6f6 | ||
|
|
08bb49ea78 | ||
|
|
014bb8e12b | ||
|
|
efe4a3873e | ||
|
|
f46b4b7f74 | ||
|
|
e7f857d21e | ||
|
|
b0292c87dc | ||
|
|
0354e07232 | ||
|
|
1f127e237b | ||
|
|
6dcbc2ad00 | ||
|
|
d36d34fe04 | ||
|
|
e769e32b1c | ||
|
|
16a46716c0 | ||
|
|
f2516d3212 | ||
|
|
3dafd2e7e1 | ||
|
|
aa3bd5097f | ||
|
|
50f7f16c28 | ||
|
|
9be43676aa | ||
|
|
4d88040fd4 | ||
|
|
82f7bcfbed | ||
|
|
fdbecadfb7 | ||
|
|
4d6afb48e7 | ||
|
|
7eb0263193 | ||
|
|
bf068e1775 | ||
|
|
8c95b5b5b8 | ||
|
|
b321da7bba | ||
|
|
fc86061ecc | ||
|
|
62fc6947b8 | ||
|
|
efd1ce348a | ||
|
|
43c579198a | ||
|
|
e180b52c9a | ||
|
|
3ca46e7fb9 | ||
|
|
8076cd4b75 | ||
|
|
e5e847f18f | ||
|
|
54e73e48e4 | ||
|
|
451da12e09 | ||
|
|
06694a92e8 | ||
|
|
6bf42ddc1b | ||
|
|
1f92306b03 | ||
|
|
096cb9523a | ||
|
|
79982c935f | ||
|
|
d1beeafbe8 | ||
|
|
3ebfdb424c | ||
|
|
95503b75fd | ||
|
|
7ef226b722 | ||
|
|
3639dad003 | ||
|
|
bd50f293b4 | ||
|
|
482bbf92e2 | ||
|
|
275a2a3d22 | ||
|
|
cec21fa0a7 | ||
|
|
4ce3c9b2f6 | ||
|
|
a6381c4aac | ||
|
|
1e5896ac96 | ||
|
|
6ac02a9214 | ||
|
|
827bc48c1d | ||
|
|
36907635b6 | ||
|
|
aafbac7b7b | ||
|
|
5120f193cb | ||
|
|
befc24487d | ||
|
|
3203c5d9e5 | ||
|
|
7eddf82957 | ||
|
|
af023b085f | ||
|
|
11ceb32773 | ||
|
|
f6e6d485dd | ||
|
|
74ed3fdc91 | ||
|
|
2edf26857e | ||
|
|
ff2989bc18 | ||
|
|
13d3fad174 | ||
|
|
5e598cd2f3 | ||
|
|
c350868195 | ||
|
|
d458ef7ca3 | ||
|
|
8033ccfe93 | ||
|
|
10257024ca | ||
|
|
96d0b5f6c1 | ||
|
|
9ac18ade71 | ||
|
|
f4bdee12e1 | ||
|
|
1e52f40a6c | ||
|
|
24372a9639 | ||
|
|
f28ae2aa8d | ||
|
|
54eb29756a | ||
|
|
2bf1406566 | ||
|
|
46af120fd7 | ||
|
|
11592ded0b | ||
|
|
94440de2d3 | ||
|
|
68b42a098d | ||
|
|
ea113e6e90 | ||
|
|
9981df3839 | ||
|
|
68f59eba48 | ||
|
|
c659103e02 | ||
|
|
db2b5e32b6 | ||
|
|
041f7e9cef | ||
|
|
1e52ee2d44 | ||
|
|
97565fb490 | ||
|
|
1e68d067af | ||
|
|
82caa97e3b | ||
|
|
eeb7ac1f79 | ||
|
|
468fe8b0c2 | ||
|
|
48b7c0b414 | ||
|
|
c8304a05cd | ||
|
|
34127df014 | ||
|
|
f4a225baea | ||
|
|
126905400d | ||
|
|
89bd4caba4 | ||
|
|
c84ca4ab30 | ||
|
|
3be13ebb6f | ||
|
|
584998bf02 | ||
|
|
f14a7680af | ||
|
|
cd6994d611 | ||
|
|
64ab143e0e | ||
|
|
8525dd4722 | ||
|
|
90e672f7f8 | ||
|
|
cb5aed93c6 | ||
|
|
e46706370c | ||
|
|
34e7dc6b81 | ||
|
|
5a0d333f71 | ||
|
|
9f89015722 | ||
|
|
609a850e61 | ||
|
|
43614ee3c5 | ||
|
|
a603e201c1 | ||
|
|
4081e7e5ab | ||
|
|
17b0d1cad1 | ||
|
|
742d05d253 | ||
|
|
1b0df627a5 | ||
|
|
94ba4b7c5b | ||
|
|
14644e00a5 | ||
|
|
be2ef02923 | ||
|
|
6ccd93a161 | ||
|
|
2edf71dee1 | ||
|
|
86251ac054 | ||
|
|
2f4915a808 | ||
|
|
a596ebc875 | ||
|
|
5e7f9ca701 | ||
|
|
0f4346cd5f | ||
|
|
c4d5e20c7a | ||
|
|
56bf320588 | ||
|
|
e6f8112df2 | ||
|
|
30eb6659d8 | ||
|
|
240da52d11 | ||
|
|
a45003ce3d | ||
|
|
f9bdf1f18a | ||
|
|
a5467d3fbb | ||
|
|
f866db9f1b | ||
|
|
b8df9d1d72 | ||
|
|
0e1e22cebb | ||
|
|
9cfd4b6e1c | ||
|
|
8c4ead0169 | ||
|
|
2992a1f032 | ||
|
|
9e7707588f | ||
|
|
0db728dc52 | ||
|
|
6a2f3b6d6e | ||
|
|
e906090ba6 | ||
|
|
077070b2cb | ||
|
|
fff616c9d0 | ||
|
|
19504a7e2b | ||
|
|
0ed85860fc | ||
|
|
e7e1cae418 | ||
|
|
69bf33e06a | ||
|
|
ae4ed8f88e | ||
|
|
112584b850 | ||
|
|
7d926f4dae | ||
|
|
f966b31324 | ||
|
|
cd656eb455 | ||
|
|
7448512a97 | ||
|
|
84b3a81daa | ||
|
|
13388f197d | ||
|
|
0185003c19 | ||
|
|
27382565de | ||
|
|
0c175e3c82 | ||
|
|
a9a94a1413 | ||
|
|
8478d47abf | ||
|
|
a3c2693417 | ||
|
|
ec98e9d54b | ||
|
|
41f29e2c77 | ||
|
|
2e1aa7e44f | ||
|
|
b1785e047f | ||
|
|
28c9b6a923 | ||
|
|
3ecd0fcfa6 | ||
|
|
a0e5cc2790 | ||
|
|
c3140ccb32 | ||
|
|
cf0b09bf0f | ||
|
|
30457a71f5 | ||
|
|
ee63905620 | ||
|
|
953eb29877 | ||
|
|
5957b01401 | ||
|
|
f0cc80f368 | ||
|
|
bdce931178 | ||
|
|
9844fc277d | ||
|
|
f39929eab7 | ||
|
|
5176296506 | ||
|
|
e303768e08 | ||
|
|
d780dafc13 | ||
|
|
9c0f9e821d | ||
|
|
35cb4b847d | ||
|
|
534030bd2f | ||
|
|
858255fd94 | ||
|
|
c953a4a8a1 | ||
|
|
52b59bd609 | ||
|
|
d9605819e3 | ||
|
|
a6a77d84c9 | ||
|
|
1a91691eec | ||
|
|
6616232310 | ||
|
|
804da832bd | ||
|
|
0266e2be53 | ||
|
|
cf39f86361 | ||
|
|
e686b6cca0 | ||
|
|
ed5016be7b | ||
|
|
5a6be1c254 | ||
|
|
39c638e4ed | ||
|
|
3c0d765744 | ||
|
|
9e504853a3 | ||
|
|
21f45a79ba | ||
|
|
d6fb979267 | ||
|
|
f01dd47f7a | ||
|
|
1c6152f568 | ||
|
|
0e4ad019d4 | ||
|
|
a73b4e4737 | ||
|
|
062e61d6a5 | ||
|
|
bc7bced817 | ||
|
|
f7f308c639 | ||
|
|
8043da9eae | ||
|
|
3541cc02c6 | ||
|
|
5ee68958ce | ||
|
|
ab4661259f | ||
|
|
c4644e5615 | ||
|
|
6c03dab7c8 | ||
|
|
bdf6fab368 | ||
|
|
f5042b7799 | ||
|
|
3eaaf486e1 | ||
|
|
07b4fdb559 | ||
|
|
f38ad4943f | ||
|
|
9d1daeddbd | ||
|
|
9f2781cafd | ||
|
|
f334e42c83 | ||
|
|
54054d7866 | ||
|
|
669c47974d | ||
|
|
3c5f50e868 | ||
|
|
9ceff67d55 | ||
|
|
9c9100e65a | ||
|
|
f0f79846bc | ||
|
|
4062bbaf2a | ||
|
|
b6f60828bb | ||
|
|
2f62445f0f | ||
|
|
5862eb4e65 | ||
|
|
ddabbc4c81 | ||
|
|
58e38efe21 | ||
|
|
f944e34d81 | ||
|
|
8de86a2bf2 | ||
|
|
ee7a184a8f | ||
|
|
ee8c1579b9 | ||
|
|
f6bbc0ef76 | ||
|
|
a610af3277 | ||
|
|
fc3a719c41 | ||
|
|
7528d0de30 | ||
|
|
491a3480f9 | ||
|
|
dae2ced03d | ||
|
|
fff21291ec | ||
|
|
ef4b3293b3 | ||
|
|
7778acef18 | ||
|
|
0ef030caa7 | ||
|
|
f0111628fa | ||
|
|
0e5a039755 | ||
|
|
7a64a5049a | ||
|
|
6d43269ac1 | ||
|
|
bf6ea228de | ||
|
|
f11eca2186 | ||
|
|
4bc7ef9b9f | ||
|
|
e561a12ce3 | ||
|
|
31354e59c5 | ||
|
|
7b194adfc1 | ||
|
|
223f68d557 | ||
|
|
b75aae5a85 | ||
|
|
e9b7a6fa5e | ||
|
|
79dafd1145 | ||
|
|
aa1fadfd92 | ||
|
|
8df55add79 | ||
|
|
fb2c1f3e6c | ||
|
|
224419f0ef | ||
|
|
39679f527c | ||
|
|
11d8812d02 | ||
|
|
ca4cfb873c | ||
|
|
7714fd2456 | ||
|
|
06e0acb26c | ||
|
|
4081e0d524 | ||
|
|
b091292c67 | ||
|
|
96d896792a | ||
|
|
2a008295bb | ||
|
|
1e92c5289a | ||
|
|
7ffb2bbaa9 | ||
|
|
c7c107fcb0 | ||
|
|
038bf037d4 | ||
|
|
2720366f9f | ||
|
|
1a5cbc8fda | ||
|
|
807cb4dafb | ||
|
|
12a363e9fe | ||
|
|
148e6170c5 | ||
|
|
26a3295794 | ||
|
|
566b3077bd | ||
|
|
97ee1136d3 | ||
|
|
60fd6cd7f5 | ||
|
|
8ab08b9997 | ||
|
|
55596cce35 | ||
|
|
1df58c2d77 | ||
|
|
88fc5d3fa8 | ||
|
|
b302556ec3 | ||
|
|
7621caf147 | ||
|
|
718195a6d9 | ||
|
|
37a0d0b19b | ||
|
|
494a2cea61 | ||
|
|
614e6af400 | ||
|
|
7521844241 | ||
|
|
3a0fb81473 | ||
|
|
a470fb8e64 | ||
|
|
ad56be1af7 | ||
|
|
f58c133a89 | ||
|
|
bf530dc245 | ||
|
|
c623b4ebe6 | ||
|
|
b19e6566c3 | ||
|
|
51b71476c6 | ||
|
|
f93fb32fed | ||
|
|
726847e42f | ||
|
|
280a8755fd | ||
|
|
2a7633abd0 | ||
|
|
fb18f25a35 | ||
|
|
ce4df4542c | ||
|
|
9230036d3e | ||
|
|
11cd54edcf | ||
|
|
734da0aa83 | ||
|
|
af27e84351 | ||
|
|
b6b177132a | ||
|
|
0b0a95d3e2 | ||
|
|
6103838f15 | ||
|
|
1b1378c174 | ||
|
|
e1ba3b891a | ||
|
|
f81540fb19 | ||
|
|
b9e05a4e98 | ||
|
|
0859f32057 | ||
|
|
0651688fa2 | ||
|
|
f2dfae5944 | ||
|
|
454d65cd5c | ||
|
|
c34f03cedd | ||
|
|
06306bdd91 | ||
|
|
72395f792b | ||
|
|
21b0fb6892 | ||
|
|
b0f18f7b7c | ||
|
|
b691cb4f1b | ||
|
|
d3844cd0ea | ||
|
|
e4941b34ee | ||
|
|
d62d26880b | ||
|
|
8b46799a67 | ||
|
|
c379cef67a | ||
|
|
ed12938558 | ||
|
|
cab8310913 | ||
|
|
8ece8432a6 | ||
|
|
0e4b2b4455 | ||
|
|
77cd0c7460 | ||
|
|
46a314761e | ||
|
|
cad30be4b7 | ||
|
|
14866ca73b | ||
|
|
ba732ddadb | ||
|
|
c5301d8b71 | ||
|
|
d672b0a515 | ||
|
|
cb82db677f | ||
|
|
ccf3c6a214 | ||
|
|
cd402b2b4f | ||
|
|
7d2f83f5cd | ||
|
|
ff8f592428 | ||
|
|
ce241a8b37 | ||
|
|
6a2f69ac6a | ||
|
|
a5f3c6fc71 | ||
|
|
a0e05396e8 | ||
|
|
0e41f248fe | ||
|
|
cb1ed597ed | ||
|
|
02b10b4d63 | ||
|
|
eb061ee2b6 | ||
|
|
247914ecce | ||
|
|
3c1453f009 | ||
|
|
b7c4e4ebf5 | ||
|
|
a21feb136e | ||
|
|
83d422df2d | ||
|
|
654fc41d26 | ||
|
|
0a433791d0 | ||
|
|
b141a50f4c | ||
|
|
c27a714c0e | ||
|
|
1c6dbcffaf | ||
|
|
a9d4abd88a | ||
|
|
c65beabc88 | ||
|
|
837f3c3883 | ||
|
|
1bd8215d6b | ||
|
|
3fed51cb37 | ||
|
|
24f216dbaf | ||
|
|
919fc62ec4 | ||
|
|
00941770ba | ||
|
|
931a797ca0 | ||
|
|
bd513bfafe | ||
|
|
2100d2ccd5 | ||
|
|
b0e49ca2a1 | ||
|
|
e3066bd41b | ||
|
|
1ff10ce523 | ||
|
|
bd2e448008 | ||
|
|
58d6db9cee | ||
|
|
5e49e2e830 | ||
|
|
5abb5acc79 | ||
|
|
d8b1a78f6f | ||
|
|
b7d3c04e4e | ||
|
|
7ceefd2dcd | ||
|
|
7c61a1321c | ||
|
|
428150bccd | ||
|
|
42ac2205cd | ||
|
|
1daf44a0dd | ||
|
|
83b3b3a47e | ||
|
|
889875bee2 | ||
|
|
1c4edab5c7 | ||
|
|
f1cd01f7c8 | ||
|
|
507f201bd6 | ||
|
|
a7c6618437 | ||
|
|
0b8adb2ab4 | ||
|
|
0ef12745ea | ||
|
|
2988a6f1f4 | ||
|
|
ecd3a3983c | ||
|
|
34c005a3ab | ||
|
|
bfcfcc2f3c | ||
|
|
9d65fceaa9 | ||
|
|
bf5ff0fc5c | ||
|
|
98eedf378d | ||
|
|
99c9557ab3 | ||
|
|
a2b072d4be | ||
|
|
866d4ce193 | ||
|
|
b2d97b09a1 | ||
|
|
0680a3829a | ||
|
|
9aed022d43 | ||
|
|
dc4ef18526 | ||
|
|
a45f51be6f | ||
|
|
b098246a6f | ||
|
|
2cd7216423 | ||
|
|
0dc523cdf8 | ||
|
|
1e36375182 | ||
|
|
7587e87994 | ||
|
|
62758f2468 | ||
|
|
525f0f4079 | ||
|
|
ffe1e4a0b7 | ||
|
|
2d7fc6a6ec | ||
|
|
60a53b0e3a | ||
|
|
6a82a8550e | ||
|
|
5c70030dda | ||
|
|
9eb3b0092c | ||
|
|
8b8bddc99e | ||
|
|
185e14c41d | ||
|
|
7535347b0e | ||
|
|
d65d5d5613 | ||
|
|
bea39407f4 | ||
|
|
36c10092ea | ||
|
|
05b9ab33a2 | ||
|
|
ad2d3d1a89 | ||
|
|
1378c503a9 | ||
|
|
b20bea9ce9 | ||
|
|
4b86f847f6 | ||
|
|
987249485d | ||
|
|
5e8db1c73a | ||
|
|
b076f054e9 | ||
|
|
6c01039b9c | ||
|
|
9cc0a2b9dc | ||
|
|
bfb207fb34 | ||
|
|
a4186435c4 | ||
|
|
ae5e3fe5fb | ||
|
|
aeeaa7ef95 | ||
|
|
0e0392e352 | ||
|
|
a91e9ba87c | ||
|
|
16d8df2cc5 | ||
|
|
665d2c3ddb | ||
|
|
ec0aa7b29d | ||
|
|
67aba0e1a9 | ||
|
|
9c260a9f3d | ||
|
|
741009d69f | ||
|
|
8a4ce15e26 | ||
|
|
63c162bd2a | ||
|
|
9c5d7191e8 | ||
|
|
d633bd56ab | ||
|
|
f7bb776e99 | ||
|
|
b1a06b8e17 | ||
|
|
c57e80b8c3 | ||
|
|
e631969719 | ||
|
|
2df4b3c4af | ||
|
|
2a539c1146 | ||
|
|
ac5b1c2abf | ||
|
|
76980b6841 | ||
|
|
33b67fc850 | ||
|
|
13f9139055 | ||
|
|
b693e3b45f | ||
|
|
cd2064aea6 | ||
|
|
44ddaef00a | ||
|
|
8082c8863d | ||
|
|
20f173edc6 | ||
|
|
070f0073c7 | ||
|
|
80f3752021 | ||
|
|
bab60542dd | ||
|
|
f86e654a3c | ||
|
|
c98aaed49e | ||
|
|
3a567363f3 | ||
|
|
bfc5decae8 | ||
|
|
084122ef3a | ||
|
|
7730a9b9e7 | ||
|
|
41314b1ce4 | ||
|
|
49a8f2e862 | ||
|
|
b8c9711645 | ||
|
|
6f02cfbb91 | ||
|
|
79d9501c85 | ||
|
|
bb7546e647 | ||
|
|
616de30e97 | ||
|
|
b941e10da9 | ||
|
|
0c30873f26 | ||
|
|
946e20f274 | ||
|
|
3f4b9ead90 | ||
|
|
81f2966fb9 | ||
|
|
474c0d5ea8 | ||
|
|
eac611798a | ||
|
|
a32ef21be6 | ||
|
|
28097247ba | ||
|
|
d56e84e64d | ||
|
|
64f9f57470 | ||
|
|
f3a13db852 | ||
|
|
bbc323a9a3 | ||
|
|
557c9cdf65 | ||
|
|
e77caba177 | ||
|
|
12f3ecf6fe | ||
|
|
01bdc24c26 | ||
|
|
c3aa987fd9 | ||
|
|
ab8929e2c8 | ||
|
|
4c29804b6b | ||
|
|
f541a14455 | ||
|
|
86af731ba5 | ||
|
|
7c319d7564 | ||
|
|
a1fa41ce14 | ||
|
|
6d649c2a69 | ||
|
|
21b076c982 | ||
|
|
fc04b0f807 | ||
|
|
0c5679f811 | ||
|
|
1040a9bee0 | ||
|
|
14a4785015 | ||
|
|
684ec44e60 | ||
|
|
abcfc073aa | ||
|
|
53c4c0788c | ||
|
|
182843f53f | ||
|
|
355e436a74 | ||
|
|
9fe8e5f56b | ||
|
|
f7b2e4440b | ||
|
|
c60ce48f68 | ||
|
|
dbb983d019 | ||
|
|
1f9ff73ed7 | ||
|
|
09a6e03815 | ||
|
|
4b3fd9d21f | ||
|
|
6d0f1d50fd | ||
|
|
458c7a05d5 | ||
|
|
1c989b5c2a | ||
|
|
2f6a143353 | ||
|
|
09988cbd81 | ||
|
|
f96747a124 | ||
|
|
e7b17d72bf | ||
|
|
4df2fc0eec | ||
|
|
1e49233289 | ||
|
|
9683c298b5 | ||
|
|
5f0c8f2eac | ||
|
|
6d8c7a7685 | ||
|
|
d46e4f7425 | ||
|
|
3534d853ee | ||
|
|
7260c60271 | ||
|
|
97b9c5f62e | ||
|
|
05b72dd57f | ||
|
|
90ec08442e | ||
|
|
295e5e0a36 | ||
|
|
bd5f85bfa4 | ||
|
|
3767cc779e | ||
|
|
351211de9b | ||
|
|
828e8de5dd | ||
|
|
0bf3e8d944 | ||
|
|
5024d55624 | ||
|
|
7b700190c8 | ||
|
|
ed9645ecd0 | ||
|
|
90e4a2a3c8 | ||
|
|
d4e7d6ccf4 | ||
|
|
35878bc3a3 | ||
|
|
84da700d36 | ||
|
|
94ac4959e0 | ||
|
|
be6e8b8b7b | ||
|
|
8bbe9530d5 | ||
|
|
c6a5ce6a1c | ||
|
|
9f72d69c57 | ||
|
|
d773866153 | ||
|
|
f99c025692 | ||
|
|
8c8f364e87 | ||
|
|
463c802ea9 | ||
|
|
51305cb6e8 | ||
|
|
2e67bbe531 | ||
|
|
e464ae6572 | ||
|
|
cc859662f9 | ||
|
|
ca7817306e | ||
|
|
679b46db1a | ||
|
|
da514ae9f6 | ||
|
|
938f659ee1 | ||
|
|
17438708da | ||
|
|
d30fa01865 | ||
|
|
350ff3f25a | ||
|
|
1d70ded4f0 | ||
|
|
904a38f703 | ||
|
|
eb057e9ee4 | ||
|
|
bac9052264 | ||
|
|
407fad6e75 | ||
|
|
4fb39a0560 | ||
|
|
7da251dbb0 | ||
|
|
6bef5060c1 | ||
|
|
e0a429eb85 | ||
|
|
af3bddd84b | ||
|
|
d49a296c25 | ||
|
|
a6d0d1893c | ||
|
|
6eb9756399 |
@@ -1,37 +0,0 @@
|
||||
root = "."
|
||||
testdata_dir = "testdata"
|
||||
tmp_dir = "tmp"
|
||||
|
||||
[build]
|
||||
args_bin = []
|
||||
bin = "./tmp/main"
|
||||
cmd = "go build -o ./tmp/main -trimpath -ldflags \"-s -w -buildid=\" ./main"
|
||||
delay = 3000
|
||||
exclude_dir = ["assets", "tmp", "vendor", "testdata"]
|
||||
exclude_file = []
|
||||
exclude_regex = ["_test.go"]
|
||||
exclude_unchanged = false
|
||||
follow_symlink = false
|
||||
full_bin = ""
|
||||
include_dir = []
|
||||
include_ext = ["go", "tpl", "tmpl", "html"]
|
||||
kill_delay = "0s"
|
||||
log = "build-errors.log"
|
||||
send_interrupt = false
|
||||
stop_on_error = true
|
||||
|
||||
[color]
|
||||
app = ""
|
||||
build = "yellow"
|
||||
main = "magenta"
|
||||
runner = "green"
|
||||
watcher = "cyan"
|
||||
|
||||
[log]
|
||||
time = false
|
||||
|
||||
[misc]
|
||||
clean_on_exit = false
|
||||
|
||||
[screen]
|
||||
clear_on_rebuild = false
|
||||
@@ -0,0 +1,15 @@
|
||||
# 监听地址,格式为 ip:port,例如 :8080
|
||||
LISTEN=127.0.0.1:8080
|
||||
|
||||
# 日志文件保存路径
|
||||
LOG=/var/log/vupay/
|
||||
|
||||
# SQLite 数据库文件路径(如果使用 MySQL,此项可忽略)
|
||||
SQLITE=/var/lib/vupay/sqlite.db
|
||||
|
||||
# PostgreSQL 数据库
|
||||
# POSTGRESQL_DSN=postgres://user:password@localhost:5432/vupay?sslmode=disable&connect_timeout=3&timezone=Asia/Shanghai
|
||||
|
||||
# MySQL 数据库(本仓库支持;DSN 里 charset=utf8mb4&parseTime=True&loc=Local 不能省)
|
||||
# 优先级:MYSQL_DSN > POSTGRESQL_DSN > SQLITE
|
||||
# MYSQL_DSN=user:password@tcp(127.0.0.1:3306)/vupay?charset=utf8mb4&parseTime=True&loc=Local&timeout=5s
|
||||
@@ -0,0 +1,83 @@
|
||||
name: Docker Build (Gitea)
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- 'ci/**'
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
REGISTRY: git.viaeon.com
|
||||
IMAGE: git.viaeon.com/admin/vupay
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
name: Build and Push Docker Image
|
||||
runs-on: ubuntu
|
||||
env:
|
||||
RUNNER_TOOL_CACHE: /toolcache
|
||||
|
||||
steps:
|
||||
- name: Install Docker CLI
|
||||
run: |
|
||||
if ! command -v docker &> /dev/null; then
|
||||
if command -v apk &> /dev/null; then
|
||||
apk add --no-cache docker-cli git
|
||||
elif command -v apt-get &> /dev/null; then
|
||||
apt-get update && apt-get install -y docker.io git
|
||||
else
|
||||
curl -fsSL https://download.docker.com/linux/static/stable/x86_64/docker-24.0.7.tgz | tar xz -C /tmp
|
||||
mv /tmp/docker/docker /usr/local/bin/
|
||||
chmod +x /usr/local/bin/docker
|
||||
fi
|
||||
fi
|
||||
docker --version
|
||||
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
fetch-tags: true
|
||||
|
||||
- name: Prepare version
|
||||
id: ver
|
||||
run: |
|
||||
SHORT_SHA=$(git rev-parse --short=7 HEAD)
|
||||
BASE=$(git describe --tags --abbrev=0 2>/dev/null || echo "v0.0.0")
|
||||
# 分支名可能带斜杠(ci/xxx),docker tag 不允许,统一换成短横线
|
||||
REF_SLUG=$(echo "${GITHUB_REF_NAME}" | tr '/' '-')
|
||||
echo "short_sha=${SHORT_SHA}" >> "$GITHUB_OUTPUT"
|
||||
echo "ref_slug=${REF_SLUG}" >> "$GITHUB_OUTPUT"
|
||||
echo "version=${BASE}-${SHORT_SHA}" >> "$GITHUB_OUTPUT"
|
||||
echo "VERSION=${BASE}-${SHORT_SHA}"
|
||||
|
||||
- name: Login to Gitea Container Registry
|
||||
run: |
|
||||
echo "${{ secrets.TOKEN }}" | docker login "${{ env.REGISTRY }}" -u "${{ github.actor }}" --password-stdin 2>&1
|
||||
|
||||
- name: Build Docker image
|
||||
run: |
|
||||
# latest 只给 main,特性分支别把 latest 顶掉
|
||||
TAGS="-t ${{ env.IMAGE }}:${{ steps.ver.outputs.short_sha }} -t ${{ env.IMAGE }}:${{ steps.ver.outputs.ref_slug }}"
|
||||
if [ "${GITHUB_REF_NAME}" = "main" ]; then TAGS="$TAGS -t ${{ env.IMAGE }}:latest"; fi
|
||||
docker build \
|
||||
--label "org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}" \
|
||||
--label "org.opencontainers.image.revision=${{ github.sha }}" \
|
||||
--build-arg "VERSION=${{ steps.ver.outputs.version }}" \
|
||||
$TAGS .
|
||||
|
||||
- name: Push Docker image
|
||||
run: |
|
||||
docker push "${{ env.IMAGE }}:${{ steps.ver.outputs.short_sha }}" 2>&1
|
||||
docker push "${{ env.IMAGE }}:${{ steps.ver.outputs.ref_slug }}" 2>&1
|
||||
if [ "${GITHUB_REF_NAME}" = "main" ]; then docker push "${{ env.IMAGE }}:latest" 2>&1; fi
|
||||
|
||||
- name: Summary
|
||||
run: |
|
||||
echo "镜像已推送:"
|
||||
echo " ${{ env.IMAGE }}:${{ steps.ver.outputs.short_sha }}"
|
||||
echo " ${{ env.IMAGE }}:${{ steps.ver.outputs.ref_slug }}"
|
||||
echo " ${{ env.IMAGE }}:latest"
|
||||
@@ -0,0 +1,55 @@
|
||||
name: BUG 反馈|使用异常|功能建议|其它问题
|
||||
description: "提交在使用 VUPAY 过程中遇到的 BUG 反馈、使用异常、对接失败等问题"
|
||||
body:
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: 完整性要求
|
||||
description: |-
|
||||
请勾选以下所有选项以证明您已经阅读并理解了以下要求,否则该 issue 将被关闭。
|
||||
options:
|
||||
- label: 我保证阅读了相关文档和 FAQ,确认问题不是由于误解功能或配置错误引起的。
|
||||
required: true
|
||||
- label: 我提供了完整环境和日志信息,而不是出于自己的判断只给出截取的部分。
|
||||
required: true
|
||||
- label: 我搜索了 issues, 没有发现已提出的类似问题。
|
||||
required: true
|
||||
- label: 问题在 Release 最新的版本上可以成功复现
|
||||
required: true
|
||||
- label: 我理解如果没有提供足够的信息,维护者可以直接关闭该 issue,而不需要进一步的解释。
|
||||
required: true
|
||||
- label: 我明白任何人针对我提交的问题没有义务提供帮助,包括项目维护者。
|
||||
required: true
|
||||
- label: 我没有阅读这个清单,只是闭眼选中了所有的复选框,请关闭这个 Issue 。
|
||||
required: false
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: 问题类型
|
||||
description: 请选择您遇到的问题类型
|
||||
options:
|
||||
- BUG 反馈
|
||||
- 使用异常
|
||||
- 对接失败
|
||||
- 功能建议
|
||||
- 其它问题
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: 报告描述
|
||||
description: |-
|
||||
请提供问题的详细描述。以及你认为有价值的信息。
|
||||
如果问题在更新后出现,请提供**具体**出现问题的版本号。
|
||||
validations:
|
||||
required: true
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |-
|
||||
## 日志信息
|
||||
默认的日志目录在 `/var/log/vupay/` 下,请将相关时间段的日志内容粘贴在下面的代码块中。
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: 日志内容
|
||||
description: 请粘贴对应的日志信息,如果有的话
|
||||
placeholder: |
|
||||
请在这里粘贴日志内容...
|
||||
render: shell
|
||||
@@ -0,0 +1,5 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Telegram Group
|
||||
url: https://t.me/VUPAYChat
|
||||
about: Telegram 交流群组
|
||||
@@ -0,0 +1,23 @@
|
||||
name: Close inactive issues
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "30 1 * * *"
|
||||
|
||||
jobs:
|
||||
close-issues:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/stale@v9
|
||||
with:
|
||||
days-before-issue-stale: 3
|
||||
days-before-issue-close: 7
|
||||
stale-issue-label: "stale"
|
||||
stale-issue-message: "此议题由于3天内没有任何活动,现在标记为过时。"
|
||||
close-issue-message: "此议题被标记为过时并且在7天内没有活动,因此已被关闭。请随时重新打开此议题以继续讨论。"
|
||||
days-before-pr-stale: -1
|
||||
days-before-pr-close: -1
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -1,21 +1,24 @@
|
||||
name: docker-image
|
||||
|
||||
name: docker-latest
|
||||
on:
|
||||
workflow_dispatch:
|
||||
create:
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- v*
|
||||
|
||||
env:
|
||||
APP_NAME: bepusdt
|
||||
DOCKERHUB_REPO: v03413/bepusdt
|
||||
|
||||
APP_NAME: vupay
|
||||
DOCKERHUB_REPO: admin/vupay
|
||||
jobs:
|
||||
docker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: 'main'
|
||||
fetch-depth: 0
|
||||
fetch-tags: true
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
- name: Set up Docker Buildx
|
||||
@@ -26,17 +29,19 @@ jobs:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
- name: Generate App Version
|
||||
run: echo APP_VERSION=`grep -o 'Version = "[^"]*"' ./main/main.go | cut -d'"' -f2` >> $GITHUB_ENV
|
||||
run: |
|
||||
echo "APP_VERSION=$(git rev-parse --short=7 HEAD)" >> $GITHUB_ENV
|
||||
echo "VERSION_TAG=$(git describe --tags --abbrev=0)-$(git rev-parse --short=7 HEAD)" >> $GITHUB_ENV
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
platforms: |
|
||||
linux/amd64
|
||||
linux/arm64
|
||||
push: true
|
||||
build-args: |
|
||||
APP_NAME=${{ env.APP_NAME }}
|
||||
APP_VERSION=${{ env.APP_VERSION }}
|
||||
VERSION=${{ env.VERSION_TAG }}
|
||||
tags: |
|
||||
${{ env.DOCKERHUB_REPO }}:latest
|
||||
${{ env.DOCKERHUB_REPO }}:${{ env.APP_VERSION }}
|
||||
@@ -0,0 +1,48 @@
|
||||
name: docker-nightly
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 16 * * *'
|
||||
workflow_dispatch:
|
||||
env:
|
||||
APP_NAME: vupay
|
||||
DOCKER_HUB_USER: v03413
|
||||
DOCKER_HUB_REPO: admin/vupay
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: 'main'
|
||||
fetch-depth: 0
|
||||
fetch-tags: true
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ env.DOCKER_HUB_USER }}
|
||||
password: ${{ secrets.DOCKER_HUB_BETA_TOKEN }}
|
||||
- name: Generate App Version
|
||||
run: |
|
||||
echo "APP_VERSION=$(git rev-parse --short=7 HEAD)" >> $GITHUB_ENV
|
||||
echo "APP_DATE=$(date +'%Y%m%d')" >> $GITHUB_ENV
|
||||
echo "VERSION_TAG=$(git describe --tags --abbrev=0)-nightly-$(git rev-parse --short=7 HEAD)" >> $GITHUB_ENV
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
platforms: |
|
||||
linux/amd64
|
||||
linux/arm64
|
||||
push: true
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
build-args: |
|
||||
VERSION=${{ env.VERSION_TAG }}
|
||||
tags: |
|
||||
${{ env.DOCKER_HUB_REPO }}:nightly
|
||||
${{ env.DOCKER_HUB_REPO }}:nightly-${{ env.APP_DATE }}-${{ env.APP_VERSION }}
|
||||
@@ -0,0 +1,51 @@
|
||||
name: pr-check
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
types:
|
||||
- opened
|
||||
- synchronize
|
||||
- reopened
|
||||
- ready_for_review
|
||||
concurrency:
|
||||
group: pr-check-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
APP_NAME: vupay
|
||||
jobs:
|
||||
docker-build:
|
||||
name: Docker Build
|
||||
if: github.event.pull_request.draft == false
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
fetch-tags: true
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
- name: Generate App Version
|
||||
run: |
|
||||
echo "APP_VERSION=$(git rev-parse --short=7 HEAD)" >> $GITHUB_ENV
|
||||
echo "VERSION_TAG=pr-${{ github.event.pull_request.number }}-$(git rev-parse --short=7 HEAD)" >> $GITHUB_ENV
|
||||
|
||||
- name: Build Docker image (no push)
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: ./dockerfile
|
||||
platforms: linux/amd64
|
||||
push: false
|
||||
load: false
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
build-args: |
|
||||
VERSION=${{ env.VERSION_TAG }}
|
||||
tags: |
|
||||
${{ env.APP_NAME }}:pr-${{ github.event.pull_request.number }}
|
||||
@@ -2,59 +2,51 @@ name: Build and Release
|
||||
on:
|
||||
workflow_dispatch:
|
||||
create:
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- v*
|
||||
|
||||
env:
|
||||
APP_NAME: bepusdt
|
||||
BUILD_DIR: build_assets
|
||||
|
||||
jobs:
|
||||
build-release:
|
||||
strategy:
|
||||
matrix:
|
||||
goos: [ linux ]
|
||||
goarch: [ amd64 ]
|
||||
fail-fast: false
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GOOS: ${{ matrix.goos }}
|
||||
GOARCH: ${{ matrix.goarch }}
|
||||
|
||||
steps:
|
||||
- name: Checkout codebase
|
||||
uses: actions/checkout@v3
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: 'main'
|
||||
fetch-depth: 0
|
||||
- name: Show workflow information
|
||||
id: get_filename
|
||||
fetch-tags: true
|
||||
- name: Git Fetch Tags
|
||||
run: git fetch --force --tags
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '25'
|
||||
- name: Install pnpm
|
||||
run: npm install -g pnpm@10
|
||||
- name: Install frontend dependencies
|
||||
working-directory: ./web
|
||||
run: pnpm install --frozen-lockfile --shamefully-hoist
|
||||
- name: Build frontend
|
||||
working-directory: ./web
|
||||
run: pnpm run build:prod
|
||||
- name: Move frontend files to static/secure
|
||||
run: |
|
||||
export _NAME=$GOOS-$GOARCH
|
||||
echo "GOOS: $GOOS, GOARCH: $GOARCH, RELEASE_NAME: $_NAME"
|
||||
echo "OS_ARCH=$_NAME" >> $GITHUB_ENV
|
||||
mkdir -p static/secure
|
||||
cp -r web/dist/* static/secure/
|
||||
- name: Generate App Version
|
||||
run: |
|
||||
echo "VERSION_TAG=$(git describe --tags --abbrev=0)-$(git rev-parse --short=7 HEAD)" >> $GITHUB_ENV
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v4
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ^1.22
|
||||
- name: Get project dependencies
|
||||
run: go mod download
|
||||
- name: Build Bepusdt
|
||||
run: |
|
||||
CGO_ENABLED=1
|
||||
mkdir -p ${{ env.BUILD_DIR }}
|
||||
go build -v -o ${{ env.BUILD_DIR }}/${{ env.APP_NAME }} -trimpath -ldflags "-linkmode external -extldflags -static -s -w -buildid=" ./main
|
||||
- name: Prepare package
|
||||
run: |
|
||||
cp -v -R ./templates ./${{ env.BUILD_DIR }}
|
||||
cp -v -R ./static ./${{ env.BUILD_DIR }}
|
||||
cp -v ./docs/${{ env.APP_NAME }}.service ./${{ env.BUILD_DIR }}
|
||||
cp -v ./docs/Environment.conf ./${{ env.BUILD_DIR }}
|
||||
mv -v ./${{ env.BUILD_DIR }} ./${{ env.APP_NAME }}
|
||||
- name: Create ZIP archive
|
||||
run: zip -9vr ./${{ env.APP_NAME }}-${{ env.OS_ARCH }}.zip ./${{ env.APP_NAME }}
|
||||
- name: Upload files to GitHub release
|
||||
uses: svenstaro/upload-release-action@v2
|
||||
go-version: '1.26.2'
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v6
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ./${{ env.APP_NAME }}-${{ env.OS_ARCH }}.zip
|
||||
tag: ${{ github.ref }}
|
||||
distribution: goreleaser
|
||||
version: latest
|
||||
args: release --clean --verbose
|
||||
env:
|
||||
VERSION: ${{ env.VERSION_TAG }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
+16
-1
@@ -1,2 +1,17 @@
|
||||
tmp
|
||||
.idea
|
||||
.air.toml
|
||||
.DS_Store
|
||||
.env
|
||||
.idea
|
||||
conf.toml
|
||||
# Added by goreleaser init:
|
||||
dist/
|
||||
static/web
|
||||
static/secure
|
||||
*.log
|
||||
AGENTS.md
|
||||
CLAUDE.md
|
||||
data/
|
||||
logs/
|
||||
mysqldata/
|
||||
pgdata/
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
version: 2
|
||||
project_name: VUPAY
|
||||
env:
|
||||
- GO111MODULE=on
|
||||
builds:
|
||||
- env:
|
||||
- CGO_ENABLED=0
|
||||
main: ./main
|
||||
binary: vupay
|
||||
ldflags:
|
||||
- -X '{{ .ModulePath }}/app.Version={{ .Env.VERSION }}'
|
||||
- -s -w -buildid=
|
||||
goos:
|
||||
- windows
|
||||
- linux
|
||||
- darwin
|
||||
goarch:
|
||||
- amd64
|
||||
- arm64
|
||||
archives:
|
||||
- formats: [ tar.gz ]
|
||||
name_template: "{{.Os}}-{{.Arch}}{{if .Arm}}v{{.Arm}}{{end}}-{{ .ProjectName }}"
|
||||
format_overrides:
|
||||
- goos: windows
|
||||
formats: [ zip ]
|
||||
files:
|
||||
- .env.example
|
||||
- src: docs/vupay.service
|
||||
dst: .
|
||||
strip_parent: true
|
||||
changelog:
|
||||
sort: asc
|
||||
filters:
|
||||
exclude:
|
||||
- "^docs:"
|
||||
- "^test:"
|
||||
- "^chore:"
|
||||
release:
|
||||
footer: >-
|
||||
|
||||
---
|
||||
|
||||
Released by [GoReleaser](https://github.com/goreleaser/goreleaser).
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
FROM golang:1.22.2 AS builder
|
||||
|
||||
ENV GO111MODULE=on
|
||||
WORKDIR /go/release
|
||||
ADD . .
|
||||
RUN set -x \
|
||||
&& CGO_ENABLED=1 go build -trimpath -ldflags="-linkmode external -extldflags -static -s -w -buildid=" -o bepusdt ./main
|
||||
|
||||
FROM debian:latest
|
||||
|
||||
ENV DEBIAN_FRONTEND noninteractive
|
||||
ENV DEBCONF_NOWARNINGS="yes"
|
||||
ENV TZ=Asia/Shanghai
|
||||
|
||||
COPY --from=builder /go/release/bepusdt /runtime/bepusdt
|
||||
|
||||
ADD ./templates /runtime/templates
|
||||
ADD ./static /runtime/static
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends tzdata ca-certificates libc6 libgcc1 libstdc++6 \
|
||||
&& ln -fs /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
|
||||
&& dpkg-reconfigure -f noninteractive tzdata \
|
||||
&& apt-get clean && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
EXPOSE 8080
|
||||
CMD ["/runtime/bepusdt"]
|
||||
@@ -1,82 +1,104 @@
|
||||
# Bepusdt (Better Easy Payment Usdt)
|
||||
**❗️作者声明:本项目为研究学习区块链的开源项目,不提供任何形式的收费服务 (谨防诈骗)
|
||||
,不鼓励任何衍生金融属性的交易行为,不负责任何使用本项目进行的三方行为;使用过程中遇见问题请提`issue`
|
||||
或群里交流,开源项目请自重!**
|
||||
|
||||
---
|
||||
|
||||
# VUPAY (Better Easy Payment USDT)
|
||||
|
||||
<p align="center">
|
||||
<img src="./static/img/tether.svg" width="15%" alt="tether">
|
||||
<img src="./static/checkout/official/assets/img/vupay.svg" width="15%" alt="tether">
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://www.gnu.org/licenses/gpl-3.0.html"><img src="https://img.shields.io/badge/license-GPLV3-blue" alt="license GPLV3"></a>
|
||||
<a href="https://golang.org"><img src="https://img.shields.io/badge/Golang-1.22-red" alt="Go version 1.21"></a>
|
||||
<a href="https://github.com/gin-gonic/gin"><img src="https://img.shields.io/badge/Gin-v1.9-blue" alt="Gin Web Framework v1.9"></a>
|
||||
<a href="https://github.com/go-telegram-bot-api/telegram-bot-api"><img src="https://img.shields.io/badge/Telegram Bot-v5-lightgrey" alt="Golang Telegram Bot Api-v5"></a>
|
||||
<a href="https://github.com/v03413/bepusdt"><img src="https://img.shields.io/badge/Release-v1.7.16-green" alt="Release v1.7.16"></a>
|
||||
<a href="https://www.gnu.org/licenses/gpl-3.0.html">
|
||||
<img src="https://img.shields.io/github/license/admin/vupay" alt="license GPLV3">
|
||||
</a>
|
||||
<a href="https://git.viaeon.com/admin/vupay">
|
||||
<img src="https://img.shields.io/github/v/release/admin/vupay" alt="GitHub Release">
|
||||
</a>
|
||||
<a href="https://git.viaeon.com/admin/vupay">
|
||||
<img src="https://img.shields.io/github/downloads/admin/vupay/total" alt="GitHub Release">
|
||||
</a>
|
||||
<a href="https://hub.docker.com/r/admin/vupay">
|
||||
<img src="https://img.shields.io/docker/pulls/admin/vupay?style=flat-square&logo=docker" alt="Docker Pulls">
|
||||
</a>
|
||||
<a href="https://github.com/gin-gonic/gin">
|
||||
<img src="https://img.shields.io/github/stars/admin/vupay?style=flat-square&logo=github" alt="GitHub Stars">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
## 🪧 介绍
|
||||
|
||||
基本就是对`Epusdt`重新造了一次轮子,移除一些非必要依赖(`Redis MySQL`),同时加入一些新特性,让个人`USDT.TRC20`
|
||||
收款更好用、部署更便捷!
|
||||
VUPAY 是一款个人`加密货币`收款网关:多链收款、订单自动回调、后台可视化管理。
|
||||
|
||||
|
||||
## 🎉 新特性
|
||||
|
||||
- ✅ 具备`Epusdt`的所有特性,插件兼容无缝替换
|
||||
- ✅ USDT汇率实时同步交易所,且支持在以此基础上波动
|
||||
- ✅ 不依赖`MySQL Redis`环境,支持`Docker`部署
|
||||
- ✅ 支持非订单交易监控通知,钱包余额变动及时通知
|
||||
- ✅ 机器人支持查询当前实时汇率,计算实际浮动汇率
|
||||
- ✅ 机器人支持任意地址查询 USDT、TRX余额等信息
|
||||
- ✅ 订单收款成功和余额变动通知 支持指定群组推送
|
||||
### 🌟 目前支持收款网络
|
||||
|
||||
## 🛠 参数配置
|
||||
🔥 主流网络:TRON Ethereum BSC Polygon<br>
|
||||
⚡ 其他网络: X-Layer Solana Aptos Arbitrum-One Base [完整列表](./docs/trade-type.md)
|
||||
|
||||
Bepusdt 所有参数都是以传递环境变量的方式进行配置,大部分参数含默认值,少量配置即可直接使用!
|
||||
- ✅ 完全兼容 `Vupay` 插件无缝替换
|
||||
- ️✅ 支持主流区块网络 不仅限于`USDT`
|
||||
- ✅ 支持主流法定货币 汇率自动更新
|
||||
- ✅ 轻依赖 单体二进制文件 部署便捷
|
||||
- ✅ 底层区块扫描 安全确认 速度稳定
|
||||
- ✅ 原生兼容`易支付`收单 接入便捷
|
||||
- ✅ 地址独占模式 底层支持不定额收款
|
||||
- ✅ 支持MQTT消息发布 交易信息即时广播
|
||||
- ✅ 快速迭代期 超多实用特性功能等你发现
|
||||
|
||||
### 参数列表
|
||||
## 🚀 快捷启动
|
||||
|
||||
| 参数名称 | 默认值 | 用法说明 |
|
||||
|--------------------|-------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| EXPIRE_TIME | `600` | 订单有效期,单位秒 |
|
||||
| USDT_RATE | 空 | USDT汇率,默认留空则获取Okx交易所的汇率(每分钟同步一次),支持多种写法,如:`7.4` 表示固定7.4、`~1.02`表示最新汇率上浮2%、`~0.97`表示最新汇率下浮3%、`+0.3`表示最新加0.3、`-0.2`表示最新减0.2,以此类推;如参数错误则使用固定值6.4 |
|
||||
| AUTH_TOKEN | `123234` | 认证Token,对接会用到这个参数 |
|
||||
| LISTEN | `:8080` | 服务器HTTP监听地址 |
|
||||
| TRADE_IS_CONFIRMED | `0` | 是否需要网络确认,禁用可以提高回调速度,启用则可以防止交易失败 |
|
||||
| APP_URI | 空 | 应用访问地址,留空则系统自动获取,前端收银台会用到,建议设置,例如:https://token-pay.example.com |
|
||||
| WALLET_ADDRESS | 空 | 启动时需要添加的钱包地址,多个请用半角符逗号`,`分开;当然,同样也支持通过机器人添加。 |
|
||||
| TG_BOT_TOKEN | 无 | Telegram Bot Token,**必须设置**,否则无法使用 |
|
||||
| TG_BOT_ADMIN_ID | 无 | Telegram Bot 管理员ID,**必须设置**,否则无法使用 |
|
||||
| TG_BOT_GROUP_ID | 无 | Telegram 群组ID,设置之后机器人会将交易消息会推送到此群 |
|
||||
| TRON_SERVER_API | `TRON_SCAN` | 可选`TRON_SCAN`,`TRON_GRID`,推荐`TRON_GRID`和`TRON_GRID_API_KEY`搭配使用,*更准更强更及时* |
|
||||
| TRON_SCAN_API_KEY | 无 | TRONSCAN API KEY,如果收款地址较多推荐设置,可避免被官方QOS |
|
||||
| TRON_GRID_API_KEY | 无 | TRONGRID API KEY,如果收款地址较多推荐设置,可避免被官方QOS |
|
||||
Docker 快速启动,执行完命令打开地址`http://服务器IP:8080`即可看到初始页面
|
||||
|
||||
**Ps:所以综上所述,必须设置的参数有`TG_BOT_TOKEN TG_BOT_ADMIN_ID`,否则无法使用!**
|
||||
```bash
|
||||
docker run -d --restart=unless-stopped -p 8080:8080 admin/vupay:latest
|
||||
```
|
||||
|
||||
## 🚀 安装部署
|
||||
> **本仓库(admin/VUPAY)额外提供:**
|
||||
> - CI 自动构建镜像并推到 `git.viaeon.com/admin/vupay`(`.gitea/workflows/docker.yaml`)
|
||||
> - 三份 compose 示例:`docker-compose.example.yml`(SQLite)、`docker-compose.postgres.example.yml`、
|
||||
> `docker-compose.mysql.example.yml`
|
||||
> - **新增 MySQL 支持**(`MYSQL_DSN`),上游只有 SQLite/PostgreSQL;用法见
|
||||
> [Docker 部署指南 · MySQL](docs/docker/docker.md)
|
||||
## 📃 技术文档
|
||||
|
||||
- [Docker 安装教程(强烈推荐🔥)](./docs/docker.md)
|
||||
- [https 配置教程](./docs/ssl.md)
|
||||
- [Linux 手动安装教程](./docs/systemd.md)
|
||||
- [Linux 时钟同步配置](./docs/systemd-timesyncd.md)
|
||||
- [彩虹易支付对接教程](./docs/epay.md)
|
||||
- 安装:[Docker](docs/docker/docker.md) [Linux](docs/linux/install.md) [1Panel](./docs/1panel/README.md) [宝塔](./docs/bt_panel/README.md)
|
||||
- 开发:[API对接](docs/api/api.md) [订单回调](docs/notify/readme.md) [Python](https://github.com/luoyanglang/vupay-python-sdk) [PHP](https://git.viaeon.com/admin/vupay-php-sdk)
|
||||
- 对接:[独角Next](docs/api/dujiao-next/dujiao-next.md) [彩虹易支付](https://github.com/v03413/Epay-VUPAY) [whmcs](https://github.com/v03413/whmcs-gateway-vupay) [其它](docs/api/other.md)
|
||||
- 其它:[https 配置](./docs/ssl.md) [时钟同步](docs/linux/systemd-timesyncd.md) [收银台修改](docs/checkout/README.md)
|
||||
|
||||
## 🤔 常见问题
|
||||
## 🖼 功能截图
|
||||
|
||||
### 如何获取参数 TG_BOT_ADMIN_ID
|
||||
| 前台收银 | 后台订单 | 订单通知 |
|
||||
|-----------------------------------------------------------|----------------------------------------------------------|-----------------------------------------------------------------|
|
||||
| <img src=./docs/images/checkout.png alt=收银台 width=300> | <img src=./docs/images/admin.png alt=后台订单 width=300> | <img src=./docs/images/telegram.png alt=Telegram通知 width=300> |
|
||||
|
||||
Telegram 搜索`@userinfobot`机器人并启用,返回的ID就是`TG_BOT_ADMIN_ID`
|
||||
## ❓ 常见问题
|
||||
|
||||
## ⚠️ 特别注意
|
||||
- [服务器配置性能选型推荐 ⚡️](./docs/faq/server.md)
|
||||
- [服务器流量消耗说明解释](./docs/faq/bandwidth.md)
|
||||
- [后台入口账密忘记重置教程](./docs/faq/login-reset.md)
|
||||
- [Telegram 通知 Chat ID 获取教程](docs/faq/telegram-chat-id.md)
|
||||
- [区块 RPC 节点稳定性说明指南‼️](./docs/faq/rpc-endpoint.md)
|
||||
|
||||
- 订单交易强依赖时间,请确保服务器时间准确性,否则可能导致订单异常!
|
||||
- 部分功能依赖网络,请确保服务器网络纯洁性,否则可能导致功能异常!
|
||||
## 🏝️ 社区交流
|
||||
|
||||
## 🙏 感谢
|
||||
- **Telegram 群组**:[https://t.me/VUPAYChat](https://t.me/VUPAYChat)
|
||||
- **Telegram 频道**:[https://t.me/VUPAYChannel](https://t.me/VUPAYChannel)
|
||||
- **安全问题反馈/联系**:https://u.viaeon.com
|
||||
|
||||
- https://github.com/assimon/epusdt
|
||||
## 🙏 致谢
|
||||
|
||||
## 📢 声明
|
||||
|
||||
- 本项目仅供个人学习研究使用,任何人或组织在使用过程中请符合当地的法律法规,否则产生的任何后果责任自负。
|
||||
感谢为本项目作出贡献的开发者:
|
||||
|
||||
## 🌟 Stargazers over time
|
||||
<a href="https://git.viaeon.com/admin/vupay/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=admin/vupay" alt="VUPAY 贡献者清单">
|
||||
</a>
|
||||
|
||||
[](https://starchart.cc/v03413/bepusdt)
|
||||
## 🌟 Star 历史
|
||||
|
||||
[](https://www.star-history.com/?repos=v03413%2Fvupay&type=date&legend=top-left)
|
||||
@@ -0,0 +1,38 @@
|
||||
package cmd
|
||||
|
||||
import "github.com/urfave/cli/v3"
|
||||
|
||||
var SQLiteFlag = &cli.StringFlag{
|
||||
Name: "sqlite",
|
||||
Value: "/var/lib/vupay/sqlite.db",
|
||||
Usage: "SQLite 数据库文件路径",
|
||||
Sources: cli.EnvVars("SQLITE"),
|
||||
}
|
||||
|
||||
var PostgresDSNFlag = &cli.StringFlag{
|
||||
Name: "postgres",
|
||||
Value: "",
|
||||
Usage: "PostgreSQL 数据库连接字符串 (DSN),例如: postgres://user:password@localhost:5432/vupay?sslmode=disable&connect_timeout=3",
|
||||
Sources: cli.EnvVars("POSTGRESQL_DSN"),
|
||||
}
|
||||
|
||||
var MysqlDSNFlag = &cli.StringFlag{
|
||||
Name: "mysql",
|
||||
Value: "",
|
||||
Usage: "MySQL 数据库连接字符串 (DSN),例如: user:pass@tcp(127.0.0.1:3306)/vupay?charset=utf8mb4&parseTime=True&loc=Local&timeout=3s",
|
||||
Sources: cli.EnvVars("MYSQL_DSN"),
|
||||
}
|
||||
|
||||
var LogFlag = &cli.StringFlag{
|
||||
Name: "log",
|
||||
Value: "/var/log/vupay/",
|
||||
Usage: "日志文件保存路径",
|
||||
Sources: cli.EnvVars("LOG"),
|
||||
}
|
||||
|
||||
var ListenFlag = &cli.StringFlag{
|
||||
Name: "listen",
|
||||
Value: ":8080",
|
||||
Usage: "监听地址,格式为 ip:port,例如 :8080",
|
||||
Sources: cli.EnvVars("LISTEN"),
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"git.viaeon.com/admin/vupay/app/task"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/urfave/cli/v3"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
var Reset = &cli.Command{
|
||||
Name: "reset",
|
||||
Usage: "忘记密码时,此命令可重置账号密码登录入口",
|
||||
Flags: []cli.Flag{SQLiteFlag, PostgresDSNFlag, MysqlDSNFlag},
|
||||
Before: func(ctx context.Context, c *cli.Command) (context.Context, error) {
|
||||
sqlite := c.String("sqlite")
|
||||
postgres := c.String("postgres")
|
||||
mysql := c.String("mysql")
|
||||
if err := model.Init(sqlite, postgres, mysql); err != nil {
|
||||
return ctx, fmt.Errorf("数据库初始化失败 %w", err)
|
||||
}
|
||||
|
||||
return ctx, task.Init()
|
||||
},
|
||||
After: func(ctx context.Context, c *cli.Command) error {
|
||||
model.Close()
|
||||
|
||||
return nil
|
||||
},
|
||||
Action: func(ctx context.Context, cmd *cli.Command) error {
|
||||
hash := utils.Md5String(time.Now().String())
|
||||
|
||||
username := hash[8:16]
|
||||
password := hash[0:8]
|
||||
entrance := fmt.Sprintf("/%s", hash[10:20])
|
||||
encrypt, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
|
||||
model.SetK(model.AdminSecure, entrance)
|
||||
model.SetK(model.AdminUsername, username)
|
||||
model.SetK(model.AdminPassword, string(encrypt))
|
||||
|
||||
fmt.Println("重置成功,对应信息如下:")
|
||||
fmt.Printf("管理员账号:%s\n管理员密码:%s\n后台管理入口:%s\n", username, password, entrance)
|
||||
fmt.Println("请妥善保存以上信息!")
|
||||
fmt.Println("-------------------------------")
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"context"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app"
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"git.viaeon.com/admin/vupay/app/notifier"
|
||||
"git.viaeon.com/admin/vupay/app/router"
|
||||
"git.viaeon.com/admin/vupay/app/task"
|
||||
)
|
||||
|
||||
import (
|
||||
"github.com/urfave/cli/v3"
|
||||
)
|
||||
|
||||
var Start = &cli.Command{
|
||||
Name: "start",
|
||||
Usage: "启动收款网关",
|
||||
Flags: []cli.Flag{SQLiteFlag, PostgresDSNFlag, MysqlDSNFlag, LogFlag, ListenFlag},
|
||||
Before: func(ctx context.Context, c *cli.Command) (context.Context, error) {
|
||||
postgres := c.String("postgres")
|
||||
mysql := c.String("mysql")
|
||||
sqlite := c.String("sqlite")
|
||||
if err := model.Init(sqlite, postgres, mysql); err != nil {
|
||||
return ctx, fmt.Errorf("数据库初始化失败 %w", err)
|
||||
}
|
||||
|
||||
if err := log.Init(c.String("log")); err != nil {
|
||||
return ctx, fmt.Errorf("日志初始化失败 %w", err)
|
||||
}
|
||||
|
||||
return ctx, task.Init()
|
||||
},
|
||||
After: func(ctx context.Context, c *cli.Command) error {
|
||||
log.Close()
|
||||
model.Close()
|
||||
|
||||
return nil
|
||||
},
|
||||
Action: start,
|
||||
}
|
||||
|
||||
func start(ctx context.Context, cmd *cli.Command) error {
|
||||
// 开始任务调度
|
||||
task.Start(ctx)
|
||||
|
||||
// 启动 Web 服务器
|
||||
var listen = cmd.String("listen")
|
||||
var srv = &http.Server{Addr: listen, Handler: router.Handler()}
|
||||
|
||||
log.Info("web server Start listen", listen)
|
||||
|
||||
go func() {
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Error("web server error", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// 关闭 Web 服务器
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := srv.Shutdown(shutdown); err != nil {
|
||||
log.Error("Web shutdown Error", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Info("web shutdown success.")
|
||||
}()
|
||||
|
||||
notifier.Welcome()
|
||||
|
||||
fmt.Println(fmt.Sprintf("日志保存路径:%s", log.GetPath()))
|
||||
fmt.Println(fmt.Sprintf("VUPAY 启动成功(%s),当前版本:%s", listen, app.Version))
|
||||
|
||||
// 等待中断信号
|
||||
var signals = make(chan os.Signal, 1)
|
||||
signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
|
||||
<-signals
|
||||
|
||||
runtime.GC()
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app"
|
||||
"github.com/urfave/cli/v3"
|
||||
)
|
||||
|
||||
var Version = &cli.Command{
|
||||
Name: "version",
|
||||
Usage: "显示版本信息",
|
||||
Action: func(ctx context.Context, cmd *cli.Command) error {
|
||||
fmt.Println("VUPAY 版本:" + app.Version)
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package conf
|
||||
|
||||
const (
|
||||
Desc = "一款更好用的个人加密货币收款网关"
|
||||
Github = "https://git.viaeon.com/admin/vupay"
|
||||
)
|
||||
|
||||
const Debug = false
|
||||
|
||||
const (
|
||||
Pid = "1000" // 暂时固定易支付商户ID
|
||||
Api = "https://api.vupay.online"
|
||||
)
|
||||
|
||||
const (
|
||||
Ton = "ton" // The Open Network
|
||||
Bsc = "bsc" // Binance Smart Chain
|
||||
Tron = "tron"
|
||||
Aptos = "aptos"
|
||||
Solana = "solana"
|
||||
Xlayer = "xlayer"
|
||||
Plasma = "plasma"
|
||||
Polygon = "polygon"
|
||||
Arbitrum = "arbitrum"
|
||||
Ethereum = "ethereum"
|
||||
Base = "base"
|
||||
)
|
||||
|
||||
const (
|
||||
UsdtTon = "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs"
|
||||
UsdtErc20 = "0xdac17f958d2ee523a2206206994597c13d831ec7"
|
||||
UsdtBep20 = "0x55d398326f99059ff775485246999027b3197955"
|
||||
UsdtXlayer = "0x779ded0c9e1022225f8e0630b35a9b54be713736"
|
||||
UsdtPlasma = "0xb8ce59fc3717ada4c02eadf9682a9e934f625ebb"
|
||||
UsdtPolygon = "0xc2132d05d31c914a87c6611c10748aeb04b58e8f"
|
||||
UsdtArbitrum = "0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"
|
||||
UsdtSolana = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"
|
||||
SolSplToken = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
|
||||
UsdtAptos = "0x357b0b74bc833e95a115ad22604854d6b0fca151cecd94111770e5d6ffc9dc2b"
|
||||
UsdcErc20 = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
|
||||
UsdcPolygon = "0x3c499c542cef5e3811e1192ce70d8cc03d5c3359"
|
||||
UsdcXlayer = "0x74b7f16337b8972027f6196a17a631ac6de26d22"
|
||||
UsdcArbitrum = "0xaf88d065e77c8cc2239327c5edb3a432268e5831"
|
||||
UsdcBep20 = "0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d"
|
||||
UsdcBase = "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"
|
||||
UsdcSolana = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
|
||||
UsdcAptos = "0xbae207659db88bea0cbead6da0ed00aac12edcdda169e591cd41c94180b46f3b"
|
||||
)
|
||||
|
||||
const (
|
||||
UsdtTronDecimals = -6 // USDT Tron小数位数
|
||||
UsdtBscDecimals = -18 // USDT BEP20小数位数
|
||||
UsdtEthDecimals = -6 // USDT ERC20小数位数
|
||||
UsdtXlayerDecimals = -6 // USDT Xlayer小数位数
|
||||
UsdtPlasmaDecimals = -6 // USDT Plasma小数位数
|
||||
UsdtPolygonDecimals = -6 // USDT Polygon小数位数
|
||||
UsdtArbitrumDecimals = -6 // USDT Arbitrum小数位数
|
||||
UsdtAptosDecimals = -6 // USDT Aptos小数位数
|
||||
UsdtSolanaDecimals = -6 // USDT Solana小数位数
|
||||
UsdtTonDecimals = -6 // USDT Ton小数位数
|
||||
|
||||
UsdcEthDecimals = -6 // USDC ERC20小数位数
|
||||
UsdcPolygonDecimals = -6 // USDC Polygon小数位数
|
||||
UsdcXlayerDecimals = -6 // USDC Xlayer小数位数
|
||||
UsdcArbitrumDecimals = -6 // USDC Arbitrum小数位数
|
||||
UsdcBaseDecimals = -6 // USDC Base小数位数
|
||||
UsdcBscDecimals = -18 // USDC BEP20小数位数
|
||||
UsdcTronDecimals = -6 // USDC Tron小数位数
|
||||
UsdcAptosDecimals = -6 // USDC Aptos小数位数
|
||||
UsdcSolanaDecimals = -6 // USDC Solana小数位数
|
||||
|
||||
TonTonDecimals = -9 // TON Ton小数位数
|
||||
BscBnbDecimals = -18 // BSC BNB 小数位数
|
||||
EthereumEthDecimals = -18 // Ethereum ETH 小数位数
|
||||
)
|
||||
@@ -0,0 +1,6 @@
|
||||
package conf
|
||||
|
||||
const (
|
||||
AdminTokenK = "admin_token"
|
||||
AdminSecureK = "admin_secure"
|
||||
)
|
||||
@@ -0,0 +1,93 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const maxRecords = 1000
|
||||
|
||||
type stat struct {
|
||||
mu sync.RWMutex
|
||||
records []bool
|
||||
index int // 当前位置
|
||||
total int // 已记录总数
|
||||
succ int // 成功记录数
|
||||
}
|
||||
|
||||
type info struct {
|
||||
Block string `json:"block"`
|
||||
Succ string `json:"succ"`
|
||||
Time int64 `json:"time"`
|
||||
}
|
||||
|
||||
var (
|
||||
data sync.Map // map[string]*stat
|
||||
last sync.Map
|
||||
)
|
||||
|
||||
func getStat(net string) *stat {
|
||||
val, _ := data.LoadOrStore(net, &stat{
|
||||
records: make([]bool, maxRecords),
|
||||
})
|
||||
return val.(*stat)
|
||||
}
|
||||
|
||||
func RecordSuccess(net, block string) {
|
||||
last.Store(net, info{Block: block, Succ: GetSuccessRate(net), Time: time.Now().Unix()})
|
||||
s := getStat(net)
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.total >= maxRecords && !s.records[s.index] {
|
||||
s.succ++
|
||||
} else if s.total < maxRecords {
|
||||
s.succ++
|
||||
}
|
||||
|
||||
s.records[s.index] = true
|
||||
s.index = (s.index + 1) % maxRecords
|
||||
if s.total < maxRecords {
|
||||
s.total++
|
||||
}
|
||||
}
|
||||
|
||||
func RecordFailure(net string) {
|
||||
s := getStat(net)
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.total >= maxRecords && s.records[s.index] {
|
||||
s.succ--
|
||||
}
|
||||
|
||||
s.records[s.index] = false
|
||||
s.index = (s.index + 1) % maxRecords
|
||||
if s.total < maxRecords {
|
||||
s.total++
|
||||
}
|
||||
}
|
||||
|
||||
func GetStats() map[string]info {
|
||||
var m = make(map[string]info)
|
||||
last.Range(func(k, v interface{}) bool {
|
||||
m[k.(string)] = v.(info)
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
func GetSuccessRate(net string) string {
|
||||
s := getStat(net)
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
if s.total == 0 {
|
||||
return "100.00%"
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%.2f%%", float64(s.succ)/float64(s.total)*100)
|
||||
}
|
||||
@@ -1,219 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const defaultExpireTime = 600 // 订单默认有效期 10分钟
|
||||
const defaultUsdtRate = 6.4 // 默认汇率
|
||||
const defaultAuthToken = "123234" // 默认授权码
|
||||
const defaultListen = ":8080" // 默认监听地址
|
||||
const TronServerApiScan = "TRON_SCAN"
|
||||
const TronServerApiGrid = "TRON_GRID"
|
||||
|
||||
var runPath string
|
||||
|
||||
func init() {
|
||||
execPath, err := os.Executable()
|
||||
if err != nil {
|
||||
|
||||
panic(err)
|
||||
}
|
||||
|
||||
runPath = filepath.Dir(execPath)
|
||||
}
|
||||
|
||||
func GetExpireTime() time.Duration {
|
||||
if ret := help.GetEnv("EXPIRE_TIME"); ret != "" {
|
||||
sec, err := strconv.Atoi(ret)
|
||||
if err == nil && sec > 0 {
|
||||
|
||||
return time.Duration(sec)
|
||||
}
|
||||
}
|
||||
|
||||
return defaultExpireTime
|
||||
}
|
||||
|
||||
func GetUsdtRateRaw() string {
|
||||
if data := help.GetEnv("USDT_RATE"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetTronServerApi() string {
|
||||
if data := help.GetEnv("TRON_SERVER_API"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetTronScanApiKey() string {
|
||||
if data := help.GetEnv("TRON_SCAN_API_KEY"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetTronGridApiKey() string {
|
||||
if data := help.GetEnv("TRON_GRID_API_KEY"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func IsTronScanApi() bool {
|
||||
if GetTronServerApi() == TronServerApiScan {
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
return GetTronServerApi() != TronServerApiGrid
|
||||
}
|
||||
|
||||
func GetUsdtRate() (string, decimal.Decimal, float64) {
|
||||
if data := help.GetEnv("USDT_RATE"); data != "" {
|
||||
data = strings.TrimSpace(data)
|
||||
// 纯数字,固定汇率
|
||||
if help.IsNumber(data) {
|
||||
if _res, err := strconv.ParseFloat(data, 64); err == nil {
|
||||
|
||||
return "", decimal.Decimal{}, _res
|
||||
}
|
||||
}
|
||||
|
||||
// 动态交易所汇率,有波动
|
||||
if len(data) >= 2 {
|
||||
if match, err2 := regexp.MatchString(`^[~+-]\d+(\.\d+)?$`, data); match && err2 == nil {
|
||||
_value, err3 := strconv.ParseFloat(data[1:], 64)
|
||||
if err3 == nil {
|
||||
|
||||
return string(data[0]), decimal.NewFromFloat(_value), defaultUsdtRate
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 动态交易所汇率,无波动
|
||||
return "=", decimal.Decimal{}, defaultUsdtRate
|
||||
}
|
||||
|
||||
func GetAuthToken() string {
|
||||
if data := help.GetEnv("AUTH_TOKEN"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return defaultAuthToken
|
||||
}
|
||||
|
||||
func GetListen() string {
|
||||
if data := help.GetEnv("LISTEN"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return defaultListen
|
||||
}
|
||||
|
||||
func GetTradeConfirmed() bool {
|
||||
if data := help.GetEnv("TRADE_IS_CONFIRMED"); data != "" {
|
||||
if data == "1" || data == "true" {
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func GetAppUri(host string) string {
|
||||
if data := help.GetEnv("APP_URI"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return host
|
||||
}
|
||||
|
||||
func GetTGBotToken() string {
|
||||
if data := help.GetEnv("TG_BOT_TOKEN"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetTGBotAdminId() string {
|
||||
if data := help.GetEnv("TG_BOT_ADMIN_ID"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetTgBotGroupId() string {
|
||||
if data := help.GetEnv("TG_BOT_GROUP_ID"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetTgBotNotifyTarget() string {
|
||||
var groupId = GetTgBotGroupId()
|
||||
if groupId != "" {
|
||||
|
||||
return groupId
|
||||
}
|
||||
|
||||
return GetTGBotAdminId()
|
||||
}
|
||||
|
||||
func GetOutputLog() string {
|
||||
|
||||
return runPath + "/bepusdt.log"
|
||||
}
|
||||
|
||||
func GetDbPath() string {
|
||||
|
||||
return runPath + "/bepusdt.db"
|
||||
}
|
||||
|
||||
func GetTemplatePath() string {
|
||||
|
||||
return runPath + "/templates/*"
|
||||
}
|
||||
|
||||
func GetStaticPath() string {
|
||||
|
||||
return runPath + "/static/"
|
||||
}
|
||||
|
||||
func GetInitWalletAddress() []string {
|
||||
if data := help.GetEnv("WALLET_ADDRESS"); data != "" {
|
||||
|
||||
return strings.Split(strings.TrimSpace(data), ",")
|
||||
}
|
||||
|
||||
return []string{}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app"
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
type Api struct {
|
||||
api string
|
||||
}
|
||||
|
||||
func New() Api {
|
||||
return Api{
|
||||
api: conf.Api,
|
||||
}
|
||||
}
|
||||
|
||||
func (Api) get(url string) ([]byte, error) {
|
||||
client := &http.Client{Timeout: 5 * time.Second}
|
||||
req, err := http.NewRequest("GET", url, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建请求失败: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("User-Agent", fmt.Sprintf("VUPAY/%s", app.Version))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("请求失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取响应失败: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, errors.New(gjson.GetBytes(body, "error").String())
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func (Api) error(err error) {
|
||||
log.Warn("Api Error:", err.Error())
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type BoundaryResp struct {
|
||||
Start int64 `json:"start"`
|
||||
End int64 `json:"end"`
|
||||
}
|
||||
|
||||
func (a Api) GetBoundaryHeights(start, end int64, network string) (int64, int64) {
|
||||
url := fmt.Sprintf("%s/api/block/get_boundary_heights?network=%s&start=%d&end=%d",
|
||||
a.api, network, start, end)
|
||||
|
||||
body, err := a.get(url)
|
||||
if err != nil {
|
||||
a.error(err)
|
||||
return 0, 0
|
||||
}
|
||||
|
||||
var response BoundaryResp
|
||||
if err := json.Unmarshal(body, &response); err != nil {
|
||||
a.error(err)
|
||||
return 0, 0
|
||||
}
|
||||
|
||||
return response.Start, response.End
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
"git.viaeon.com/admin/vupay/app/handler/base"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"git.viaeon.com/admin/vupay/app/notifier"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Conf struct {
|
||||
}
|
||||
|
||||
type confReq struct {
|
||||
Key string `json:"key" binding:"required"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
type confGetsReq struct {
|
||||
Keys []string `json:"keys" binding:"required"`
|
||||
}
|
||||
|
||||
type confSetsReq []confReq
|
||||
|
||||
type notifierConf struct {
|
||||
Channel string `json:"channel" binding:"required"`
|
||||
Params json.RawMessage `json:"params" binding:"required"`
|
||||
}
|
||||
|
||||
func (Conf) Set(ctx *gin.Context) {
|
||||
var req confReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
model.SetK(model.ConfKey(strings.TrimSpace(req.Key)), strings.TrimSpace(req.Value))
|
||||
|
||||
defer model.RefreshC()
|
||||
|
||||
base.Ok(ctx, "配置成功")
|
||||
}
|
||||
|
||||
func (Conf) Get(ctx *gin.Context) {
|
||||
var req confReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
base.Ok(ctx, gin.H{"key": req.Key, "value": model.GetK(model.ConfKey(req.Key))})
|
||||
}
|
||||
|
||||
func (Conf) Del(ctx *gin.Context) {
|
||||
var req confReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
model.Db.Where("k = ?", req.Key).Delete(&model.Conf{})
|
||||
|
||||
base.Ok(ctx, "删除成功")
|
||||
}
|
||||
|
||||
func (Conf) Gets(ctx *gin.Context) {
|
||||
var req confGetsReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var items = make([]model.Conf, 0)
|
||||
model.Db.Where("k IN ?", req.Keys).Find(&items)
|
||||
|
||||
var data = gin.H{}
|
||||
for _, item := range items {
|
||||
data[string(item.K)] = item.V
|
||||
}
|
||||
|
||||
base.Ok(ctx, data)
|
||||
}
|
||||
|
||||
func (Conf) Sets(ctx *gin.Context) {
|
||||
var req confSetsReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
keys := make([]string, 0)
|
||||
data := make([]model.Conf, 0)
|
||||
for _, item := range req {
|
||||
var k = strings.TrimSpace(item.Key)
|
||||
var v = strings.TrimSpace(item.Value)
|
||||
keys = append(keys, k)
|
||||
data = append(data, model.Conf{K: model.ConfKey(k), V: v})
|
||||
}
|
||||
|
||||
model.Db.Where("k IN ?", keys).Delete(&model.Conf{})
|
||||
model.Db.Create(&data)
|
||||
|
||||
defer model.RefreshC()
|
||||
|
||||
base.Ok(ctx, "配置成功")
|
||||
}
|
||||
|
||||
func (Conf) Rpc(ctx *gin.Context) {
|
||||
var keys = []model.ConfKey{
|
||||
model.RpcEndpointPlasma,
|
||||
model.RpcEndpointBsc,
|
||||
model.RpcEndpointSolana,
|
||||
model.RpcEndpointXlayer,
|
||||
model.RpcEndpointPolygon,
|
||||
model.RpcEndpointArbitrum,
|
||||
model.RpcEndpointEthereum,
|
||||
model.RpcEndpointBase,
|
||||
model.RpcEndpointAptos,
|
||||
model.RpcEndpointTron,
|
||||
model.RpcEndpointTronGridApiKey,
|
||||
model.RpcGlobalConfigUrlTon,
|
||||
}
|
||||
|
||||
var rpc = make(map[model.ConfKey]string)
|
||||
var items = make([]model.Conf, 0)
|
||||
model.Db.Where("k IN ?", keys).Find(&items)
|
||||
for _, item := range items {
|
||||
rpc[item.K] = item.V
|
||||
}
|
||||
|
||||
base.Ok(ctx, gin.H{
|
||||
"rpc": rpc,
|
||||
"stats": conf.GetStats(),
|
||||
})
|
||||
}
|
||||
|
||||
func (Conf) Notifier(ctx *gin.Context) {
|
||||
var req notifierConf
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var keys = []string{string(model.NotifierChannel), string(model.NotifierParams)}
|
||||
model.Db.Where("k IN ?", keys).Delete(&model.Conf{})
|
||||
model.Db.Create(&[]model.Conf{
|
||||
{K: model.NotifierChannel, V: req.Channel},
|
||||
{K: model.NotifierParams, V: string(req.Params)},
|
||||
})
|
||||
|
||||
base.Ok(ctx, "配置成功")
|
||||
}
|
||||
|
||||
func (Conf) NotifierTest(ctx *gin.Context) {
|
||||
err := notifier.Test()
|
||||
if err != nil {
|
||||
base.Ok(ctx, "发送测试失败:"+err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
base.Ok(ctx, "发送测试成功")
|
||||
}
|
||||
|
||||
func (Conf) CheckoutList(ctx *gin.Context) {
|
||||
base.Ok(ctx, model.CheckoutList())
|
||||
}
|
||||
|
||||
func (Conf) ResetApiAuthToken(ctx *gin.Context) {
|
||||
model.SetK(model.ApiAuthToken, strings.ToUpper(utils.Md5String(utils.StrSha256(time.Now().String()))))
|
||||
|
||||
base.Ok(ctx, "重置成功")
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/handler/base"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/go-cache"
|
||||
)
|
||||
|
||||
type Dashboard struct {
|
||||
}
|
||||
|
||||
type homeReq struct {
|
||||
Fiat string `json:"fiat" binding:"required"`
|
||||
Range string `json:"range"`
|
||||
TZ string `json:"tz"`
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Force bool `json:"force"`
|
||||
}
|
||||
|
||||
type dashboardPoint struct {
|
||||
Date string `json:"date"`
|
||||
OrdersTotal int64 `json:"orders_total"`
|
||||
OrdersPaid int64 `json:"orders_paid"`
|
||||
OrdersSuccess int64 `json:"orders_success"`
|
||||
OrdersFailed int64 `json:"orders_failed"`
|
||||
GMVPaid string `json:"gmv_paid"`
|
||||
}
|
||||
|
||||
func (Dashboard) Home(ctx *gin.Context) {
|
||||
var req homeReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
rangeKey, from, to, loc, err := resolveDashboardRange(req)
|
||||
if err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
cacheKey := dashboardCacheKey(req.Fiat, rangeKey, loc.String(), from, to)
|
||||
if !req.Force {
|
||||
if data, ok := cache.Get(cacheKey); ok {
|
||||
base.Ok(ctx, data)
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
data := buildDashboardHome(req, rangeKey, from, to, loc)
|
||||
cache.Set(cacheKey, data, dashboardCacheTTL(rangeKey, to, loc))
|
||||
base.Ok(ctx, data)
|
||||
}
|
||||
|
||||
func buildDashboardHome(req homeReq, rangeKey string, from, to time.Time, loc *time.Location) gin.H {
|
||||
var rows = make([]model.Order, 0)
|
||||
model.Db.Where("fiat = ? and created_at >= ? and created_at <= ?", req.Fiat, from, to).Find(&rows)
|
||||
|
||||
var totalCount, pendingCount, confirmingCount, successCount, expiredCount, failedCount, notifyFailedCount int64
|
||||
gmvPaid := decimal.Zero
|
||||
var tokenMap = map[model.Crypto]float64{
|
||||
model.USDT: 0,
|
||||
model.USDC: 0,
|
||||
model.TRX: 0,
|
||||
model.BNB: 0,
|
||||
model.ETH: 0,
|
||||
}
|
||||
points := make([]dashboardPoint, 0)
|
||||
pointMap := make(map[string]int)
|
||||
for day := dayStart(from, loc); !day.After(dayStart(to, loc)); day = day.AddDate(0, 0, 1) {
|
||||
date := day.Format("2006-01-02")
|
||||
point := dashboardPoint{
|
||||
Date: date,
|
||||
GMVPaid: "0.00",
|
||||
}
|
||||
points = append(points, point)
|
||||
pointMap[date] = len(points) - 1
|
||||
}
|
||||
|
||||
for _, itm := range rows {
|
||||
totalCount++
|
||||
createdAt := time.Now().In(loc)
|
||||
if itm.CreatedAt != nil {
|
||||
createdAt = time.Time(*itm.CreatedAt).In(loc)
|
||||
}
|
||||
date := createdAt.Format("2006-01-02")
|
||||
pointIndex, ok := pointMap[date]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
point := &points[pointIndex]
|
||||
|
||||
point.OrdersTotal++
|
||||
|
||||
switch itm.Status {
|
||||
case model.OrderStatusWaiting:
|
||||
pendingCount++
|
||||
case model.OrderStatusConfirming:
|
||||
confirmingCount++
|
||||
case model.OrderStatusExpired:
|
||||
expiredCount++
|
||||
case model.OrderStatusSuccess:
|
||||
successCount++
|
||||
point.OrdersSuccess++
|
||||
point.OrdersPaid++
|
||||
|
||||
money, _ := decimal.NewFromString(itm.Money)
|
||||
gmvPaid = gmvPaid.Add(money)
|
||||
pointMoney, _ := decimal.NewFromString(point.GMVPaid)
|
||||
point.GMVPaid = pointMoney.Add(money).Round(2).StringFixed(2)
|
||||
|
||||
crypto := itm.Crypto
|
||||
if crypto == "" {
|
||||
if tradeCrypto, err := model.GetCrypto(itm.TradeType); err == nil {
|
||||
crypto = tradeCrypto
|
||||
}
|
||||
}
|
||||
if _, ok := tokenMap[crypto]; !ok {
|
||||
tokenMap[crypto] = 0
|
||||
}
|
||||
tokenAmount := cast.ToFloat64(itm.Amount)
|
||||
if tokenAmount == 0 {
|
||||
tokenAmount = cast.ToFloat64(itm.Money)
|
||||
}
|
||||
tokenMap[crypto] += tokenAmount
|
||||
|
||||
if itm.NotifyState == model.OrderNotifyStateFail {
|
||||
notifyFailedCount++
|
||||
}
|
||||
case model.OrderStatusFailed:
|
||||
failedCount++
|
||||
point.OrdersFailed++
|
||||
}
|
||||
}
|
||||
|
||||
successRate := "0.00"
|
||||
finishedCount := successCount + expiredCount + failedCount
|
||||
if finishedCount > 0 {
|
||||
rate := decimal.NewFromInt(successCount).Div(decimal.NewFromInt(finishedCount)).Mul(decimal.NewFromInt(100))
|
||||
successRate = rate.Round(2).StringFixed(2)
|
||||
}
|
||||
|
||||
return gin.H{
|
||||
"range": rangeKey,
|
||||
"from": from.In(loc).Format(time.RFC3339),
|
||||
"to": to.In(loc).Format(time.RFC3339),
|
||||
"timezone": loc.String(),
|
||||
"currency": req.Fiat,
|
||||
"kpi": gin.H{
|
||||
"orders_total": totalCount,
|
||||
"orders_pending": pendingCount,
|
||||
"orders_confirming": confirmingCount,
|
||||
"gmv_paid": gmvPaid.Round(2).StringFixed(2),
|
||||
"orders_success": successCount,
|
||||
"orders_failed": failedCount,
|
||||
"notify_failed": notifyFailedCount,
|
||||
"order_success_rate": successRate,
|
||||
},
|
||||
"token_map": tokenMap,
|
||||
"points": points,
|
||||
}
|
||||
}
|
||||
|
||||
func dashboardCacheKey(fiat, rangeKey, timezone string, from, to time.Time) string {
|
||||
return fmt.Sprintf("dashboard:home:v1:%s:%s:%s:%d:%d", fiat, rangeKey, timezone, from.Unix(), to.Unix())
|
||||
}
|
||||
|
||||
func dashboardCacheTTL(rangeKey string, to time.Time, loc *time.Location) time.Duration {
|
||||
switch rangeKey {
|
||||
case "today":
|
||||
return 10 * time.Second
|
||||
case "30d":
|
||||
return time.Minute
|
||||
case "custom":
|
||||
if to.Before(dayStart(time.Now().In(loc), loc)) {
|
||||
return 5 * time.Minute
|
||||
}
|
||||
|
||||
return 30 * time.Second
|
||||
default:
|
||||
return 30 * time.Second
|
||||
}
|
||||
}
|
||||
|
||||
func resolveDashboardRange(req homeReq) (string, time.Time, time.Time, *time.Location, error) {
|
||||
loc := time.Local
|
||||
if req.TZ != "" {
|
||||
if loadedLoc, err := time.LoadLocation(req.TZ); err == nil {
|
||||
loc = loadedLoc
|
||||
}
|
||||
}
|
||||
|
||||
rangeKey := req.Range
|
||||
if rangeKey == "" {
|
||||
rangeKey = "7d"
|
||||
}
|
||||
|
||||
now := time.Now().In(loc)
|
||||
switch rangeKey {
|
||||
case "today":
|
||||
start := dayStart(now, loc)
|
||||
return rangeKey, start, dayEnd(start), loc, nil
|
||||
case "30d":
|
||||
yesterday := dayStart(now, loc).AddDate(0, 0, -1)
|
||||
start := yesterday.AddDate(0, 0, -29)
|
||||
return rangeKey, start, dayEnd(yesterday), loc, nil
|
||||
case "custom":
|
||||
from, err := parseDashboardDate(req.From, loc, true)
|
||||
if err != nil {
|
||||
return "", time.Time{}, time.Time{}, nil, err
|
||||
}
|
||||
to, err := parseDashboardDate(req.To, loc, false)
|
||||
if err != nil {
|
||||
return "", time.Time{}, time.Time{}, nil, err
|
||||
}
|
||||
if to.Before(from) {
|
||||
return "", time.Time{}, time.Time{}, nil, errors.New("自定义统计周期结束时间不能早于开始时间")
|
||||
}
|
||||
|
||||
return rangeKey, from, to, loc, nil
|
||||
case "7d":
|
||||
fallthrough
|
||||
default:
|
||||
yesterday := dayStart(now, loc).AddDate(0, 0, -1)
|
||||
start := yesterday.AddDate(0, 0, -6)
|
||||
return "7d", start, dayEnd(yesterday), loc, nil
|
||||
}
|
||||
}
|
||||
|
||||
func parseDashboardDate(value string, loc *time.Location, start bool) (time.Time, error) {
|
||||
if value == "" {
|
||||
return time.Time{}, errors.New("请选择自定义统计周期")
|
||||
}
|
||||
|
||||
layouts := []string{time.RFC3339, "2006-01-02 15:04:05", "2006-01-02"}
|
||||
for _, layout := range layouts {
|
||||
t, err := time.ParseInLocation(layout, value, loc)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if layout == "2006-01-02" {
|
||||
if start {
|
||||
return dayStart(t, loc), nil
|
||||
}
|
||||
return dayEnd(t), nil
|
||||
}
|
||||
|
||||
return t.In(loc), nil
|
||||
}
|
||||
|
||||
return time.Time{}, errors.New("自定义统计周期格式错误")
|
||||
}
|
||||
|
||||
func dayStart(t time.Time, loc *time.Location) time.Time {
|
||||
local := t.In(loc)
|
||||
return time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, loc)
|
||||
}
|
||||
|
||||
func dayEnd(t time.Time) time.Time {
|
||||
start := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
|
||||
return start.Add(24*time.Hour - time.Nanosecond)
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/handler/base"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"git.viaeon.com/admin/vupay/app/task/notify"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
type Order struct {
|
||||
}
|
||||
|
||||
type oListReq struct {
|
||||
base.ListRequest
|
||||
Name string `json:"name"`
|
||||
Money string `json:"money"`
|
||||
Amount string `json:"amount"`
|
||||
OrderId string `json:"order_id"`
|
||||
TradeId string `json:"trade_id"`
|
||||
Status *uint8 `json:"status"`
|
||||
Address string `json:"address"`
|
||||
TradeType string `json:"trade_type"`
|
||||
StartAt string `json:"start_at"`
|
||||
EndAt string `json:"end_at"`
|
||||
}
|
||||
|
||||
type paidReq struct {
|
||||
base.IDRequest
|
||||
RefHash string `json:"ref_hash"`
|
||||
}
|
||||
|
||||
type createReq struct {
|
||||
Amount float64 `json:"amount" binding:"required"`
|
||||
OrderID string `json:"order_id" binding:"required"`
|
||||
Name string `json:"name"`
|
||||
Fiat model.Fiat `json:"fiat"`
|
||||
Currencies string `json:"currencies"`
|
||||
Timeout int64 `json:"timeout"`
|
||||
}
|
||||
|
||||
func (Order) Create(ctx *gin.Context) {
|
||||
var req createReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.Response(ctx, 400, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
host := utils.GetRequestHost(ctx.Request)
|
||||
|
||||
// 创建待付款订单
|
||||
order, err := model.BuildPendingOrder(model.OrderParams{
|
||||
Money: decimal.NewFromFloat(req.Amount),
|
||||
ApiType: model.OrderApiTypeAdmin, // 使用 Admin 类型
|
||||
OrderId: req.OrderID,
|
||||
Name: req.Name,
|
||||
Timeout: req.Timeout,
|
||||
Fiat: req.Fiat,
|
||||
CurrencyLimit: req.Currencies,
|
||||
})
|
||||
if err != nil {
|
||||
base.Response(ctx, 400, gin.H{
|
||||
"status": "failed",
|
||||
"message": "failed to create order: " + err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// NotifyURL RedirectURL 同为付款链接
|
||||
url := model.CheckoutUrl(host, order.TradeId)
|
||||
|
||||
// Update order with generated URLs
|
||||
hostUri := model.GetK(model.ApiAppUri)
|
||||
if hostUri == "" {
|
||||
hostUri = host
|
||||
}
|
||||
order.NotifyUrl = hostUri + "/api/v1/pay/notify"
|
||||
order.ReturnUrl = url
|
||||
|
||||
if err := model.Db.Save(&order).Error; err != nil {
|
||||
base.Response(ctx, 400, gin.H{
|
||||
"status": "failed",
|
||||
"message": "failed to update order urls: " + err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 返回响应数据
|
||||
base.Response(ctx, 200, gin.H{
|
||||
"status": "success",
|
||||
"message": "order created",
|
||||
"payment_url": url,
|
||||
})
|
||||
}
|
||||
|
||||
func (Order) List(ctx *gin.Context) {
|
||||
var req oListReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.Response(ctx, 400, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
type order struct {
|
||||
model.Order
|
||||
Wallet model.Wallet `gorm:"foreignKey:MatchAddr,TradeType;references:Address,TradeType" json:"wallet"`
|
||||
}
|
||||
|
||||
var data []order
|
||||
var db = model.Db
|
||||
|
||||
if req.Name != "" {
|
||||
db = db.Where("name LIKE ?", "%"+req.Name+"%")
|
||||
}
|
||||
if req.Money != "" {
|
||||
db = db.Where("money = ?", req.Money)
|
||||
}
|
||||
if req.Amount != "" {
|
||||
db = db.Where("amount = ?", req.Amount)
|
||||
}
|
||||
if req.OrderId != "" {
|
||||
db = db.Where("order_id like ?", "%"+req.OrderId+"%")
|
||||
}
|
||||
if req.TradeId != "" {
|
||||
db = db.Where("trade_id like ?", "%"+req.TradeId+"%")
|
||||
}
|
||||
if req.Status != nil {
|
||||
db = db.Where("status = ?", *req.Status)
|
||||
}
|
||||
if req.Address != "" {
|
||||
db = db.Where("address like ?", "%"+req.Address+"%")
|
||||
}
|
||||
if req.TradeType != "" {
|
||||
db = db.Where("trade_type = ?", req.TradeType)
|
||||
}
|
||||
if req.StartAt != "" {
|
||||
db = db.Where("created_at >= ?", req.StartAt)
|
||||
}
|
||||
if req.EndAt != "" {
|
||||
db = db.Where("created_at <= ?", req.EndAt)
|
||||
}
|
||||
|
||||
var total int64
|
||||
|
||||
db.Model(&model.Order{}).Count(&total)
|
||||
|
||||
err := db.Preload("Wallet").Limit(req.Size).Offset((req.Page - 1) * req.Size).Order("id " + req.Sort).Find(&data).Error
|
||||
if err != nil {
|
||||
base.Response(ctx, 400, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
base.Response(ctx, 200, data, total)
|
||||
}
|
||||
|
||||
func (Order) Detail(ctx *gin.Context) {
|
||||
var req base.IDRequest
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
type detail struct {
|
||||
model.Order
|
||||
TxUrl string `gorm:"-" json:"tx_url"`
|
||||
}
|
||||
|
||||
var o model.Order
|
||||
model.Db.Where("id = ?", req.ID).Find(&o)
|
||||
if o.ID == 0 {
|
||||
base.BadRequest(ctx, "订单不存在")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
base.Ok(ctx, detail{
|
||||
Order: o,
|
||||
TxUrl: o.GetTxUrl(),
|
||||
})
|
||||
}
|
||||
|
||||
func (Order) Paid(ctx *gin.Context) {
|
||||
var req paidReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var order model.Order
|
||||
model.Db.Where("id = ?", req.ID).Find(&order)
|
||||
if order.ID == 0 {
|
||||
base.BadRequest(ctx, "订单不存在")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if order.Status == model.OrderStatusCanceled {
|
||||
base.BadRequest(ctx, "交易已取消,无法补单")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
confirmedAt := time.Now()
|
||||
var update = map[string]interface{}{
|
||||
"ref_hash": req.RefHash,
|
||||
"status": model.OrderStatusSuccess,
|
||||
"confirmed_at": model.Datetime(confirmedAt),
|
||||
}
|
||||
|
||||
err := model.Db.Model(&order).Updates(update).Error
|
||||
if err != nil {
|
||||
base.Error(ctx, err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
order.RefHash = req.RefHash
|
||||
order.Status = model.OrderStatusSuccess
|
||||
order.ConfirmedAt = &confirmedAt
|
||||
|
||||
go notify.Handle(order)
|
||||
|
||||
base.Ok(ctx, "操作成功")
|
||||
}
|
||||
|
||||
func (Order) ManualNotify(ctx *gin.Context) {
|
||||
var req base.IDRequest
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var order model.Order
|
||||
model.Db.Where("id = ?", req.ID).Find(&order)
|
||||
if order.ID == 0 {
|
||||
base.BadRequest(ctx, "订单不存在")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if order.Status != model.OrderStatusSuccess {
|
||||
base.BadRequest(ctx, "订单状态不是交易成功,无法手动回调")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err := notify.Handle(order); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
base.Ok(ctx, "订单回调成功!")
|
||||
}
|
||||
|
||||
func (Order) Cancel(ctx *gin.Context) {
|
||||
var req base.IDRequest
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var order model.Order
|
||||
model.Db.Where("id = ?", req.ID).Find(&order)
|
||||
if order.ID == 0 {
|
||||
base.BadRequest(ctx, "订单不存在")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if order.Status != model.OrderStatusWaiting {
|
||||
base.BadRequest(ctx, "仅允许取消未支付订单")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err := order.SetCanceled(); err != nil {
|
||||
base.Error(ctx, err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
base.Ok(ctx, "订单取消成功")
|
||||
}
|
||||
|
||||
func (Order) Del(ctx *gin.Context) {
|
||||
var req base.IDListRequest
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err := model.Db.Delete(&model.Order{}, req.IDList).Error
|
||||
if err != nil {
|
||||
base.Error(ctx, err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
base.Ok(ctx, "删除成功")
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/handler/base"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Rate struct {
|
||||
}
|
||||
|
||||
type rateListReq struct {
|
||||
base.ListRequest
|
||||
Fiat string `json:"fiat"`
|
||||
Crypto string `json:"crypto"`
|
||||
Datetime []string `json:"datetime"`
|
||||
}
|
||||
|
||||
type rateSetSyntaxReq struct {
|
||||
Fiat string `json:"fiat"`
|
||||
Crypto string `json:"crypto"`
|
||||
Syntax string `json:"syntax"`
|
||||
}
|
||||
|
||||
func (Rate) List(ctx *gin.Context) {
|
||||
var req rateListReq
|
||||
if err := ctx.ShouldBind(&req); err != nil {
|
||||
base.Response(ctx, 400, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var data []model.Rate
|
||||
var db = model.Db
|
||||
if req.Fiat != "" {
|
||||
db = db.Where("fiat = ?", req.Fiat)
|
||||
}
|
||||
if req.Crypto != "" {
|
||||
db = db.Where("crypto = ?", req.Crypto)
|
||||
}
|
||||
if len(req.Datetime) == 2 {
|
||||
db = db.Where("created_at BETWEEN ? AND ?", req.Datetime[0], req.Datetime[1])
|
||||
}
|
||||
|
||||
var total int64
|
||||
|
||||
db.Model(&model.Rate{}).Count(&total)
|
||||
|
||||
err := db.Limit(req.Size).Offset((req.Page - 1) * req.Size).Order("id " + req.Sort).Find(&data).Error
|
||||
if err != nil {
|
||||
base.Response(ctx, 400, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
base.Response(ctx, 200, data, total)
|
||||
}
|
||||
|
||||
func (Rate) Syntax(ctx *gin.Context) {
|
||||
type Syntax struct {
|
||||
Key string `json:"key"`
|
||||
Fiat string `json:"fiat"`
|
||||
Crypto string `json:"crypto"`
|
||||
Syntax string `json:"syntax"`
|
||||
}
|
||||
|
||||
var data = make([]Syntax, 0)
|
||||
|
||||
for fiat := range model.GetSupportFiat() {
|
||||
for token := range model.GetSupportCrypto() {
|
||||
var k = fmt.Sprintf("rate_float_%s_%s", token, fiat)
|
||||
data = append(data, Syntax{
|
||||
Key: k,
|
||||
Fiat: string(fiat),
|
||||
Crypto: string(token),
|
||||
Syntax: model.GetK(model.ConfKey(k)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
base.Ok(ctx, data)
|
||||
}
|
||||
|
||||
func (Rate) SetSyntax(ctx *gin.Context) {
|
||||
var req rateSetSyntaxReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
model.SetK(model.ConfKey("rate_float_"+req.Crypto+"_"+req.Fiat), req.Syntax)
|
||||
|
||||
base.Ok(ctx, "设置成功")
|
||||
}
|
||||
|
||||
func (Rate) Sync(ctx *gin.Context) {
|
||||
err := model.CoingeckoRate()
|
||||
if err != nil {
|
||||
base.BadRequest(ctx, "同步异常: "+err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
base.Ok(ctx, "同步完成。")
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/handler/base"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Wallet struct {
|
||||
}
|
||||
|
||||
type wAddReq struct {
|
||||
Name string `json:"name"`
|
||||
Remark string `json:"remark"`
|
||||
Address string `json:"address" binding:"required"`
|
||||
TradeType string `json:"trade_type" binding:"required"`
|
||||
OtherNotify uint8 `json:"other_notify"`
|
||||
}
|
||||
|
||||
type wModReq struct {
|
||||
base.IDRequest
|
||||
Name *string `json:"name"`
|
||||
Status *uint8 `json:"status"`
|
||||
Address *string `json:"address"`
|
||||
Remark *string `json:"remark"`
|
||||
TradeType *string `json:"trade_type"`
|
||||
OtherNotify *uint8 `json:"other_notify"`
|
||||
}
|
||||
|
||||
type wListReq struct {
|
||||
base.ListRequest
|
||||
Name string `json:"name"`
|
||||
Address string `json:"address"`
|
||||
Trade string `json:"trade_type"`
|
||||
}
|
||||
|
||||
func (Wallet) Add(ctx *gin.Context) {
|
||||
var req wAddReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if !model.IsSupportedTradeType(model.TradeType(req.TradeType)) {
|
||||
base.BadRequest(ctx, fmt.Sprintf("不支持的交易类型: %s", req.TradeType))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var wallet = model.Wallet{
|
||||
Name: strings.TrimSpace(req.Name),
|
||||
Remark: req.Remark,
|
||||
Address: strings.TrimSpace(req.Address),
|
||||
MatchAddr: strings.TrimSpace(req.Address),
|
||||
TradeType: req.TradeType,
|
||||
Status: model.WaStatusEnable,
|
||||
OtherNotify: req.OtherNotify,
|
||||
}
|
||||
|
||||
if err := wallet.Validate(); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err := model.Db.Create(&wallet).Error; err != nil {
|
||||
base.Error(ctx, err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
base.Response(ctx, 200, "success")
|
||||
}
|
||||
|
||||
func (Wallet) List(ctx *gin.Context) {
|
||||
var req wListReq
|
||||
if err := ctx.ShouldBind(&req); err != nil {
|
||||
base.Response(ctx, 400, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var data []model.Wallet
|
||||
var db = model.Db
|
||||
|
||||
if req.Name != "" {
|
||||
db = db.Where("name LIKE ?", "%"+req.Name+"%")
|
||||
}
|
||||
if req.Address != "" {
|
||||
db = db.Where("address LIKE ?", "%"+req.Address+"%")
|
||||
}
|
||||
if req.Trade != "" {
|
||||
db = db.Where("trade_type LIKE ?", "%"+req.Trade+"%")
|
||||
}
|
||||
|
||||
var total int64
|
||||
|
||||
db.Model(&model.Wallet{}).Count(&total)
|
||||
|
||||
err := db.Limit(req.Size).Offset((req.Page - 1) * req.Size).Order("id " + req.Sort).Find(&data).Error
|
||||
if err != nil {
|
||||
base.Response(ctx, 400, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
base.Response(ctx, 200, data, total)
|
||||
}
|
||||
|
||||
func (Wallet) Mod(ctx *gin.Context) {
|
||||
var req wModReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var w model.Wallet
|
||||
model.Db.Where("id = ?", req.ID).Find(&w)
|
||||
if w.ID == 0 {
|
||||
base.BadRequest(ctx, "钱包不存在")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if req.Name != nil {
|
||||
w.Name = strings.TrimSpace(*req.Name)
|
||||
}
|
||||
if req.Remark != nil {
|
||||
w.Remark = *req.Remark
|
||||
}
|
||||
if req.Address != nil {
|
||||
w.Address = strings.TrimSpace(*req.Address)
|
||||
w.MatchAddr = strings.TrimSpace(*req.Address)
|
||||
}
|
||||
if req.TradeType != nil {
|
||||
if !model.IsSupportedTradeType(model.TradeType(*req.TradeType)) {
|
||||
base.BadRequest(ctx, fmt.Sprintf("不支持的交易类型: %s", *req.TradeType))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
w.TradeType = *req.TradeType
|
||||
}
|
||||
if req.Status != nil {
|
||||
w.Status = *req.Status
|
||||
}
|
||||
if req.OtherNotify != nil {
|
||||
w.OtherNotify = *req.OtherNotify
|
||||
}
|
||||
|
||||
if err := w.Validate(); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err := model.Db.Save(&w).Error; err != nil {
|
||||
base.Error(ctx, err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
base.Response(ctx, 200, "修改成功")
|
||||
}
|
||||
|
||||
func (Wallet) Del(ctx *gin.Context) {
|
||||
var req base.IDRequest
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
model.Db.Where("id = ?", req.ID).Delete(&model.Wallet{})
|
||||
|
||||
base.Response(ctx, 200, "删除成功")
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
"git.viaeon.com/admin/vupay/app/handler/base"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/go-cache"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type Auth struct {
|
||||
}
|
||||
|
||||
type authLoginReq struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
type authPasswordReq struct {
|
||||
Password string `json:"password" binding:"required"`
|
||||
NewPassword string `json:"new_password" binding:"required"`
|
||||
ConfirmPassword string `json:"confirm_password" binding:"required"`
|
||||
}
|
||||
|
||||
func (Auth) Info(ctx *gin.Context) {
|
||||
base.Ok(ctx, gin.H{
|
||||
"admin_username": model.GetK(model.AdminUsername),
|
||||
"trade_type": model.GetAllAlias(),
|
||||
"trade_fiat": model.GetSupportFiat(),
|
||||
"trade_crypto": model.GetSupportCrypto(),
|
||||
"trade_network": model.GetAllNetwork(),
|
||||
})
|
||||
}
|
||||
|
||||
func (Auth) Menu(ctx *gin.Context) {
|
||||
type meta struct {
|
||||
Title string `json:"title"`
|
||||
Hide bool `json:"hide"`
|
||||
Disable bool `json:"disable"`
|
||||
KeepAlive bool `json:"keepAlive"`
|
||||
Affix bool `json:"affix"`
|
||||
Link string `json:"link"`
|
||||
Iframe bool `json:"iframe"`
|
||||
IsFull bool `json:"isFull"`
|
||||
Roles []string `json:"roles"`
|
||||
SvgIcon string `json:"svgIcon"`
|
||||
Icon string `json:"icon"`
|
||||
Sort int `json:"sort"`
|
||||
Type int `json:"type"`
|
||||
}
|
||||
type menu struct {
|
||||
Id string `json:"id"`
|
||||
ParentId string `json:"parentId"`
|
||||
Path string `json:"path"`
|
||||
Name string `json:"name"`
|
||||
Component string `json:"component"`
|
||||
Meta meta `json:"meta"`
|
||||
Children []menu `json:"children"`
|
||||
}
|
||||
|
||||
var data = []menu{
|
||||
{
|
||||
Id: "01",
|
||||
Path: "/home",
|
||||
Name: "home",
|
||||
Component: "home/home",
|
||||
Meta: meta{
|
||||
Title: "home",
|
||||
Hide: false,
|
||||
Disable: false,
|
||||
KeepAlive: false,
|
||||
Affix: true,
|
||||
Link: "",
|
||||
Iframe: false,
|
||||
IsFull: false,
|
||||
Roles: []string{"admin"},
|
||||
SvgIcon: "home",
|
||||
Icon: "",
|
||||
Sort: 1,
|
||||
Type: 2,
|
||||
},
|
||||
Children: nil,
|
||||
},
|
||||
{
|
||||
Id: "02",
|
||||
Path: "/wallet",
|
||||
Name: "wallet",
|
||||
Component: "wallet/wallet",
|
||||
Meta: meta{
|
||||
Title: "wallet",
|
||||
Hide: false,
|
||||
Disable: false,
|
||||
KeepAlive: true,
|
||||
Affix: false,
|
||||
Link: "",
|
||||
Iframe: false,
|
||||
IsFull: false,
|
||||
Roles: []string{"admin"},
|
||||
SvgIcon: "classify",
|
||||
Icon: "",
|
||||
Sort: 1,
|
||||
Type: 2,
|
||||
},
|
||||
Children: nil,
|
||||
},
|
||||
{
|
||||
Id: "03",
|
||||
Path: "/order",
|
||||
Name: "order",
|
||||
Component: "order/order",
|
||||
Meta: meta{
|
||||
Title: "order",
|
||||
Hide: false,
|
||||
Disable: false,
|
||||
KeepAlive: true,
|
||||
Affix: false,
|
||||
Link: "",
|
||||
Iframe: false,
|
||||
IsFull: false,
|
||||
Roles: []string{"admin"},
|
||||
SvgIcon: "table",
|
||||
Icon: "",
|
||||
Sort: 1,
|
||||
Type: 2,
|
||||
},
|
||||
Children: nil,
|
||||
},
|
||||
{
|
||||
Id: "04",
|
||||
Path: "/rate",
|
||||
Name: "rate",
|
||||
Component: "rate/rate",
|
||||
Meta: meta{
|
||||
Title: "rate",
|
||||
Hide: false,
|
||||
Disable: false,
|
||||
KeepAlive: true,
|
||||
Affix: false,
|
||||
Link: "",
|
||||
Iframe: false,
|
||||
IsFull: false,
|
||||
Roles: []string{"admin"},
|
||||
SvgIcon: "directives",
|
||||
Icon: "",
|
||||
Sort: 1,
|
||||
Type: 1,
|
||||
},
|
||||
Children: []menu{
|
||||
{
|
||||
Id: "0401",
|
||||
ParentId: "04",
|
||||
Path: "/rate/list",
|
||||
Name: "rate-list",
|
||||
Component: "rate/list",
|
||||
Meta: meta{
|
||||
Title: "rate-list",
|
||||
Hide: false,
|
||||
Disable: false,
|
||||
KeepAlive: true,
|
||||
Affix: false,
|
||||
Link: "",
|
||||
Iframe: false,
|
||||
IsFull: false,
|
||||
Roles: []string{"admin"},
|
||||
SvgIcon: "",
|
||||
Icon: "icon-list",
|
||||
Sort: 1,
|
||||
Type: 2,
|
||||
},
|
||||
Children: nil,
|
||||
},
|
||||
{
|
||||
Id: "0402",
|
||||
ParentId: "04",
|
||||
Path: "/rate/syntax",
|
||||
Name: "rate-syntax",
|
||||
Component: "rate/syntax",
|
||||
Meta: meta{
|
||||
Title: "rate-syntax",
|
||||
Hide: false,
|
||||
Disable: false,
|
||||
KeepAlive: true,
|
||||
Affix: false,
|
||||
Link: "",
|
||||
Iframe: false,
|
||||
IsFull: false,
|
||||
Roles: []string{"admin"},
|
||||
SvgIcon: "",
|
||||
Icon: "icon-settings",
|
||||
Sort: 1,
|
||||
Type: 2,
|
||||
},
|
||||
Children: nil,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Id: "05",
|
||||
Path: "/system",
|
||||
Name: "system",
|
||||
Component: "system/system",
|
||||
Meta: meta{
|
||||
Title: "system",
|
||||
Hide: false,
|
||||
Disable: false,
|
||||
KeepAlive: true,
|
||||
Affix: false,
|
||||
Link: "",
|
||||
Iframe: false,
|
||||
IsFull: false,
|
||||
Roles: []string{"admin"},
|
||||
SvgIcon: "set",
|
||||
Icon: "",
|
||||
Sort: 1,
|
||||
Type: 1,
|
||||
},
|
||||
Children: []menu{
|
||||
{
|
||||
Id: "0501",
|
||||
ParentId: "05",
|
||||
Path: "/system/base/base",
|
||||
Name: "system-base",
|
||||
Component: "system/base/base",
|
||||
Meta: meta{
|
||||
Title: "system-base",
|
||||
Hide: false,
|
||||
Disable: false,
|
||||
KeepAlive: true,
|
||||
Affix: false,
|
||||
Link: "",
|
||||
Iframe: false,
|
||||
IsFull: false,
|
||||
Roles: []string{"admin"},
|
||||
SvgIcon: "",
|
||||
Icon: "icon-layers",
|
||||
Sort: 1,
|
||||
Type: 2,
|
||||
},
|
||||
Children: nil,
|
||||
},
|
||||
{
|
||||
Id: "0502",
|
||||
ParentId: "05",
|
||||
Path: "/system/rpc/rpc",
|
||||
Name: "system-rpc",
|
||||
Component: "system/rpc/rpc",
|
||||
Meta: meta{
|
||||
Title: "system-rpc",
|
||||
Hide: false,
|
||||
Disable: false,
|
||||
KeepAlive: true,
|
||||
Affix: false,
|
||||
Link: "",
|
||||
Iframe: false,
|
||||
IsFull: false,
|
||||
Roles: []string{"admin"},
|
||||
SvgIcon: "",
|
||||
Icon: "icon-thunderbolt",
|
||||
Sort: 1,
|
||||
Type: 2,
|
||||
},
|
||||
Children: nil,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Id: "06",
|
||||
Path: "/create-order",
|
||||
Name: "create-order",
|
||||
Component: "order/create-order",
|
||||
Meta: meta{
|
||||
Title: "create-order",
|
||||
Hide: false,
|
||||
Disable: false,
|
||||
KeepAlive: true,
|
||||
Affix: false,
|
||||
Link: "",
|
||||
Iframe: false,
|
||||
IsFull: false,
|
||||
Roles: []string{"admin"},
|
||||
SvgIcon: "form",
|
||||
Icon: "",
|
||||
Sort: 1,
|
||||
Type: 2,
|
||||
},
|
||||
Children: nil,
|
||||
},
|
||||
{
|
||||
Id: "07",
|
||||
Path: "/github-api-doc",
|
||||
Name: "github-api-doc",
|
||||
Component: "about/doc",
|
||||
Meta: meta{
|
||||
Title: "github-api-doc",
|
||||
Hide: false,
|
||||
Disable: false,
|
||||
KeepAlive: true,
|
||||
Affix: false,
|
||||
Link: "",
|
||||
Iframe: false,
|
||||
IsFull: false,
|
||||
Roles: []string{"admin"},
|
||||
SvgIcon: "about",
|
||||
Icon: "",
|
||||
Sort: 1,
|
||||
Type: 2,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
base.Ok(ctx, data)
|
||||
}
|
||||
|
||||
func (Auth) Login(ctx *gin.Context) {
|
||||
var req authLoginReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.Response(ctx, 400, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var username = model.GetK(model.AdminUsername)
|
||||
if req.Username != username {
|
||||
base.Response(ctx, 400, "用户名或密码错误")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var password = model.GetK(model.AdminPassword)
|
||||
if bcrypt.CompareHashAndPassword([]byte(password), []byte(req.Password)) != nil {
|
||||
base.Response(ctx, 400, "用户名或密码错误")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
rand, _ := utils.GenerateTradeId()
|
||||
|
||||
var token = utils.StrSha256(rand + ctx.ClientIP())
|
||||
|
||||
cache.Set(conf.AdminTokenK, token, time.Hour*24)
|
||||
|
||||
model.SetK(model.AdminLoginIP, ctx.ClientIP())
|
||||
model.SetK(model.AdminLoginAt, cast.ToString(time.Now().Format(time.DateTime)))
|
||||
|
||||
base.Response(ctx, 200, gin.H{"token": token, "types": model.GetAllAlias()})
|
||||
}
|
||||
|
||||
func (Auth) Logout(ctx *gin.Context) {
|
||||
cache.Set(conf.AdminTokenK, "", -1)
|
||||
|
||||
sess := sessions.Default(ctx)
|
||||
sess.Delete(conf.AdminSecureK)
|
||||
_ = sess.Save()
|
||||
|
||||
base.Response(ctx, 200, "退出成功")
|
||||
}
|
||||
|
||||
func (Auth) SetPassword(ctx *gin.Context) {
|
||||
var req authPasswordReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
base.BadRequest(ctx, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var password = model.GetK(model.AdminPassword)
|
||||
if bcrypt.CompareHashAndPassword([]byte(password), []byte(req.Password)) != nil {
|
||||
base.BadRequest(ctx, "原密码错误")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if req.ConfirmPassword != req.NewPassword {
|
||||
base.BadRequest(ctx, "两次输入的新密码不一致")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var newPassword = strings.TrimSpace(req.NewPassword)
|
||||
if len(newPassword) < 6 {
|
||||
base.BadRequest(ctx, "新密码长度不能少于6位")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
hash, _ := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
|
||||
|
||||
model.SetK(model.AdminPassword, string(hash))
|
||||
cache.Set(conf.AdminTokenK, "", -1)
|
||||
|
||||
base.Ok(ctx, "修改成功,请重新登录")
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package base
|
||||
|
||||
// ListRequest 通用列表请求
|
||||
type ListRequest struct {
|
||||
Page int `json:"page" form:"page" binding:"min=1"`
|
||||
Size int `json:"size" form:"size" binding:"min=1"`
|
||||
Keyword string `json:"keyword" form:"keyword"`
|
||||
Sort string `json:"sort" form:"sort" binding:"oneof=asc desc"`
|
||||
ID int `json:"id" form:"id"`
|
||||
Status int `json:"status" form:"status"`
|
||||
}
|
||||
|
||||
type IDRequest struct {
|
||||
ID int `json:"id" form:"id" binding:"required"` // *ID(必须)
|
||||
}
|
||||
|
||||
type IDListRequest struct {
|
||||
IDList []int `json:"ids" form:"ids" binding:"required"` // *ID列表(必须)
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package base
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Result struct {
|
||||
Code int `json:"code,omitempty"` // 状态码
|
||||
Msg string `json:"msg,omitempty"` // 状态消息
|
||||
Total int64 `json:"total,omitempty"` // 总条数
|
||||
Data interface{} `json:"data,omitempty"` // 数据
|
||||
}
|
||||
|
||||
func Typer(i any) string {
|
||||
var t string
|
||||
switch i.(type) {
|
||||
case string:
|
||||
t = "string"
|
||||
case int:
|
||||
t = "int"
|
||||
case int8:
|
||||
t = "int8"
|
||||
case int16:
|
||||
t = "int16"
|
||||
case int32:
|
||||
t = "int32"
|
||||
case int64:
|
||||
t = "int64"
|
||||
case uint:
|
||||
t = "uint"
|
||||
case uint8:
|
||||
t = "uint8"
|
||||
case uint16:
|
||||
t = "uint16"
|
||||
case uint32:
|
||||
t = "uint32"
|
||||
case uint64:
|
||||
t = "uint64"
|
||||
case map[string]string:
|
||||
t = "map[string]string"
|
||||
case map[int]string:
|
||||
t = "map[int]string"
|
||||
case map[string]int:
|
||||
t = "map[string]int"
|
||||
case map[int]int:
|
||||
t = "map[int]int"
|
||||
case []string:
|
||||
t = "[]string"
|
||||
case []int:
|
||||
t = "[]int"
|
||||
case [1]string:
|
||||
t = "array [1] string"
|
||||
case [2]string:
|
||||
t = "array [1] string"
|
||||
case [1]int:
|
||||
t = "array [1] int"
|
||||
case [2]int:
|
||||
t = "array [2] int"
|
||||
default:
|
||||
t = "unknow"
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func Response(ctx *gin.Context, code int, data ...any) {
|
||||
var d = Result{Code: code}
|
||||
|
||||
if len(data) > 0 {
|
||||
if Typer(data[0]) == "string" {
|
||||
d.Msg = data[0].(string)
|
||||
} else {
|
||||
d.Data = data[0]
|
||||
}
|
||||
if len(data) == 2 {
|
||||
d.Total = data[1].(int64)
|
||||
}
|
||||
}
|
||||
|
||||
if code >= 500 && code <= 599 {
|
||||
if len(data) > 0 {
|
||||
err, ok := data[0].(error)
|
||||
if ok {
|
||||
log.Error(err.Error())
|
||||
} else {
|
||||
log.Error(fmt.Sprintf("%v", data[0]))
|
||||
}
|
||||
}
|
||||
|
||||
d.Msg = "服务器错误"
|
||||
}
|
||||
|
||||
ctx.JSON(200, d)
|
||||
}
|
||||
|
||||
func Ok(ctx *gin.Context, data ...any) {
|
||||
Response(ctx, 200, data...)
|
||||
}
|
||||
|
||||
// Error 500 服务器错误
|
||||
func Error(ctx *gin.Context, err error) {
|
||||
Response(ctx, 500, err)
|
||||
}
|
||||
|
||||
// BadRequest 400 请求错误
|
||||
func BadRequest(ctx *gin.Context, err string) {
|
||||
Response(ctx, 400, err)
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package epay
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sort"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
const Pid = "1000" // 固定商户号
|
||||
|
||||
type Epay struct {
|
||||
}
|
||||
|
||||
type submit struct {
|
||||
Pid string `form:"pid" json:"pid" binding:"required"` // 商户号
|
||||
Type string `form:"type" json:"type" binding:"required"`
|
||||
NotifyURL string `form:"notify_url" json:"notify_url" binding:"required"`
|
||||
ReturnURL string `form:"return_url" json:"return_url" binding:"required"`
|
||||
OutTradeNo string `form:"out_trade_no" json:"out_trade_no" binding:"required"`
|
||||
Name string `form:"name" json:"name" binding:"required"`
|
||||
Money string `form:"money" json:"money" binding:"required,gt=0"`
|
||||
Sign string `form:"sign" json:"sign" binding:"required"`
|
||||
Fiat model.Fiat `form:"fiat" json:"fiat"`
|
||||
Rate string `form:"rate" json:"rate"`
|
||||
Timeout string `form:"timeout" json:"timeout"`
|
||||
Address string `form:"address" json:"address"`
|
||||
}
|
||||
|
||||
// Submit 【兼容】易支付提交
|
||||
func (e Epay) Submit(ctx *gin.Context) {
|
||||
var err error
|
||||
var data submit
|
||||
|
||||
var dataMap = make(map[string]string)
|
||||
if ctx.Request.Method != http.MethodPost {
|
||||
for key, values := range ctx.Request.URL.Query() {
|
||||
if len(values) > 0 {
|
||||
dataMap[key] = values[0]
|
||||
}
|
||||
}
|
||||
} else {
|
||||
_ = ctx.Request.ParseForm()
|
||||
for key, values := range ctx.Request.PostForm {
|
||||
if len(values) > 0 {
|
||||
dataMap[key] = values[0]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data, err = e.verify(dataMap)
|
||||
if err != nil {
|
||||
ctx.String(200, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if e.sign(dataMap, model.AuthToken()) != data.Sign {
|
||||
ctx.String(200, "签名错误")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if !utils.IsAllowedCallbackURL(data.NotifyURL) {
|
||||
ctx.String(200, "notify_url 地址不合法")
|
||||
|
||||
return
|
||||
}
|
||||
if !utils.IsAllowedCallbackURL(data.ReturnURL) {
|
||||
ctx.String(200, "return_url 地址不合法")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
money, err := decimal.NewFromString(data.Money)
|
||||
if err != nil {
|
||||
ctx.String(200, "参数 money 解析错误,"+err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var order, err2 = model.StartBuildOrder(model.OrderParams{
|
||||
Money: money,
|
||||
ApiType: model.OrderApiTypeEpay,
|
||||
Address: data.Address,
|
||||
OrderId: data.OutTradeNo,
|
||||
TradeType: model.TradeType(data.Type),
|
||||
RedirectUrl: data.ReturnURL,
|
||||
NotifyUrl: data.NotifyURL,
|
||||
Name: data.Name,
|
||||
Timeout: cast.ToInt64(data.Timeout),
|
||||
Rate: data.Rate,
|
||||
Fiat: data.Fiat,
|
||||
})
|
||||
if err2 != nil {
|
||||
ctx.String(200, fmt.Sprintf("订单创建失败:%v", err2))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 解析请求地址
|
||||
var host = "http://" + ctx.Request.Host
|
||||
if ctx.Request.TLS != nil {
|
||||
host = "https://" + ctx.Request.Host
|
||||
}
|
||||
|
||||
ctx.Redirect(http.StatusFound, model.CheckoutUrl(host, order.TradeId))
|
||||
}
|
||||
|
||||
// verify 验证请求参数
|
||||
func (e Epay) verify(data map[string]string) (submit, error) {
|
||||
var params = submit{}
|
||||
|
||||
pid, ok := data["pid"]
|
||||
if !ok || pid != Pid {
|
||||
|
||||
return params, fmt.Errorf("VUPAY 易支付兼容模式,商户号【PID】必须固定为" + Pid)
|
||||
}
|
||||
|
||||
var requiredFields = []string{"pid", "type", "out_trade_no", "notify_url", "return_url", "name", "money", "sign"}
|
||||
for _, field := range requiredFields {
|
||||
if _, ok := data[field]; !ok || data[field] == "" {
|
||||
|
||||
return params, fmt.Errorf("参数 %s 缺失或为空", field)
|
||||
}
|
||||
}
|
||||
|
||||
params.Pid = pid
|
||||
params.Type = data["type"]
|
||||
params.OutTradeNo = data["out_trade_no"]
|
||||
params.NotifyURL = data["notify_url"]
|
||||
params.ReturnURL = data["return_url"]
|
||||
params.Name = data["name"]
|
||||
params.Money = data["money"]
|
||||
params.Sign = data["sign"]
|
||||
|
||||
if address, ok := data["address"]; ok {
|
||||
params.Address = address
|
||||
}
|
||||
if rate, ok := data["rate"]; ok && rate != "" {
|
||||
params.Rate = rate
|
||||
}
|
||||
if timeout, ok := data["timeout"]; ok && timeout != "" {
|
||||
params.Timeout = timeout
|
||||
}
|
||||
|
||||
fiat, ok := data["fiat"]
|
||||
if ok && fiat != "" {
|
||||
params.Fiat = model.Fiat(fiat)
|
||||
} else {
|
||||
params.Fiat = model.CNY
|
||||
}
|
||||
|
||||
return params, nil
|
||||
}
|
||||
|
||||
func (e Epay) sign(data map[string]string, token string) string {
|
||||
var keys = make([]string, 0, len(data))
|
||||
for k := range data {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
|
||||
sort.Strings(keys)
|
||||
|
||||
signStr := ""
|
||||
for _, k := range keys {
|
||||
if k != "sign" && k != "sign_type" && data[k] != "" {
|
||||
signStr += fmt.Sprintf("%s=%s&", k, data[k])
|
||||
}
|
||||
}
|
||||
signStr = signStr[:len(signStr)-1]
|
||||
signStr += token
|
||||
|
||||
// 计算 MD5
|
||||
hash := md5.New()
|
||||
hash.Write([]byte(signStr))
|
||||
md5sum := hex.EncodeToString(hash.Sum(nil))
|
||||
|
||||
return md5sum
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
package vupay
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
type Vupay struct{}
|
||||
|
||||
type createReq struct {
|
||||
OrderID string `json:"order_id" binding:"required"`
|
||||
NotifyURL string `json:"notify_url" binding:"required"`
|
||||
RedirectURL string `json:"redirect_url" binding:"required"`
|
||||
Signature string `json:"signature" binding:"required"`
|
||||
Amount float64 `json:"amount"`
|
||||
Name string `json:"name"`
|
||||
Fiat model.Fiat `json:"fiat"`
|
||||
TradeType string `json:"trade_type"`
|
||||
Address string `json:"address"`
|
||||
Timeout int64 `json:"timeout"`
|
||||
Rate string `json:"rate"`
|
||||
}
|
||||
|
||||
type createOrderReq struct {
|
||||
OrderID string `json:"order_id" binding:"required"`
|
||||
NotifyURL string `json:"notify_url" binding:"required"`
|
||||
RedirectURL string `json:"redirect_url" binding:"required"`
|
||||
Signature string `json:"signature" binding:"required"`
|
||||
Amount float64 `json:"amount"`
|
||||
Name string `json:"name"`
|
||||
Fiat model.Fiat `json:"fiat"`
|
||||
Currencies string `json:"currencies"`
|
||||
Timeout int64 `json:"timeout"`
|
||||
}
|
||||
|
||||
type updateOrderReq struct {
|
||||
TradeID string `json:"trade_id" binding:"required"`
|
||||
Currency string `json:"currency" binding:"required"`
|
||||
Network string `json:"network" binding:"required"`
|
||||
}
|
||||
|
||||
type cancelReq struct {
|
||||
TradeID string `json:"trade_id" binding:"required"`
|
||||
Signature string `json:"signature" binding:"required"`
|
||||
}
|
||||
|
||||
type infoReq struct {
|
||||
TradeID string `json:"trade_id" binding:"required"`
|
||||
}
|
||||
|
||||
type methodsReq struct {
|
||||
TradeID string `json:"trade_id" binding:"required"`
|
||||
Currency string `json:"currency"`
|
||||
}
|
||||
|
||||
func loadPayOrder(ctx *gin.Context, tradeID string) (model.Order, bool) {
|
||||
order, ok := model.GetTradeOrder(tradeID)
|
||||
if !ok {
|
||||
ctx.JSON(200, respFailJson("order not found"))
|
||||
return model.Order{}, false
|
||||
}
|
||||
|
||||
if order.FingerprintBound() && !order.MatchFingerprint(utils.ClientFingerprint(ctx)) {
|
||||
ctx.JSON(200, respFailJson("order not found"))
|
||||
return model.Order{}, false
|
||||
}
|
||||
|
||||
return order, true
|
||||
}
|
||||
|
||||
func (Vupay) Notify(ctx *gin.Context) {
|
||||
rawData, err := ctx.GetRawData()
|
||||
if err != nil {
|
||||
ctx.String(200, "fail")
|
||||
return
|
||||
}
|
||||
|
||||
m := make(map[string]any)
|
||||
if err = json.Unmarshal(rawData, &m); err != nil {
|
||||
ctx.String(200, "fail")
|
||||
return
|
||||
}
|
||||
|
||||
sign, ok := m["signature"]
|
||||
if !ok {
|
||||
ctx.String(200, "fail")
|
||||
return
|
||||
}
|
||||
|
||||
if utils.VupaySign(m, model.AuthToken()) != sign {
|
||||
ctx.String(200, "fail")
|
||||
return
|
||||
}
|
||||
|
||||
ctx.String(200, "ok")
|
||||
}
|
||||
|
||||
func (Vupay) CreateOrder(ctx *gin.Context) {
|
||||
var req createOrderReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("CreateOrder: request error: %s", err.Error())))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if !utils.IsAllowedCallbackURL(req.NotifyURL) {
|
||||
ctx.JSON(200, respFailJson("notify_url 地址不合法"))
|
||||
|
||||
return
|
||||
}
|
||||
if !utils.IsAllowedCallbackURL(req.RedirectURL) {
|
||||
ctx.JSON(200, respFailJson("redirect_url 地址不合法"))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 解析请求地址
|
||||
host := "http://" + ctx.Request.Host
|
||||
if ctx.Request.TLS != nil {
|
||||
host = "https://" + ctx.Request.Host
|
||||
}
|
||||
|
||||
if req.Fiat == "" {
|
||||
req.Fiat = model.CNY
|
||||
}
|
||||
|
||||
// 创建待付款订单
|
||||
order, err := model.BuildPendingOrder(model.OrderParams{
|
||||
Money: decimal.NewFromFloat(req.Amount),
|
||||
ApiType: model.OrderApiTypeVupayOrder,
|
||||
OrderId: req.OrderID,
|
||||
RedirectUrl: req.RedirectURL,
|
||||
NotifyUrl: req.NotifyURL,
|
||||
Name: req.Name,
|
||||
Timeout: req.Timeout,
|
||||
Fiat: req.Fiat,
|
||||
CurrencyLimit: req.Currencies,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("CreateOrder: order create failed: %s", err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
log.Info(fmt.Sprintf("订单创建成功 商户订单:%s", req.OrderID))
|
||||
|
||||
// 返回响应数据
|
||||
ctx.JSON(200, respSuccJson(gin.H{
|
||||
"fiat": order.Fiat,
|
||||
"trade_id": order.TradeId,
|
||||
"order_id": order.OrderId,
|
||||
"name": order.Name,
|
||||
"status": order.Status,
|
||||
"amount": order.Money,
|
||||
"expiration_time": uint64(order.ExpiredAt.Sub(time.Now()).Seconds()),
|
||||
"payment_url": model.CheckoutUrl(host, order.TradeId),
|
||||
"network": order.GetMethods(""),
|
||||
"reselect": order.CanReselectPayment(),
|
||||
}))
|
||||
}
|
||||
|
||||
func (Vupay) UpdateOrder(ctx *gin.Context) {
|
||||
// 接收 trade_id, currency, network 三个参数
|
||||
var req updateOrderReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("UpdateOrder: request error: %s", err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
// 解析请求地址
|
||||
host := "http://" + ctx.Request.Host
|
||||
if ctx.Request.TLS != nil {
|
||||
host = "https://" + ctx.Request.Host
|
||||
}
|
||||
|
||||
order, ok := loadPayOrder(ctx, req.TradeID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// 仅待付订单才可更新订单
|
||||
if order.Status != model.OrderStatusWaiting {
|
||||
ctx.JSON(200, respFailJson("update order failed: order status does not allow payment updates"))
|
||||
return
|
||||
}
|
||||
|
||||
if order.TradeType != "" && !order.CanReselectPayment() {
|
||||
ctx.JSON(200, respFailJson("update order failed: order status does not allow payment updates"))
|
||||
return
|
||||
}
|
||||
|
||||
fp := utils.ClientFingerprint(ctx)
|
||||
|
||||
// 拒绝过期订单
|
||||
remaining := time.Until(order.ExpiredAt)
|
||||
if remaining <= 0 {
|
||||
ctx.JSON(200, respFailJson("update order failed: order expired"))
|
||||
return
|
||||
}
|
||||
|
||||
// 根据 currency 和 network 解析出 TradeType
|
||||
tradeType, err := model.GetTradeTypeByCurrencyAndNetwork(req.Currency, req.Network)
|
||||
if err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("UpdateOrder: unsupported payment method: %s - %s", req.Currency, req.Network)))
|
||||
return
|
||||
}
|
||||
|
||||
// 重建订单(更新支付方式)
|
||||
// 注意:RebuildOrder 需要 OrderParams,我们需要从现有订单构造参数
|
||||
money, _ := decimal.NewFromString(order.Money)
|
||||
params := model.OrderParams{
|
||||
Money: money,
|
||||
OrderId: order.OrderId,
|
||||
TradeType: tradeType, // 新的交易类型
|
||||
RedirectUrl: order.ReturnUrl,
|
||||
NotifyUrl: order.NotifyUrl,
|
||||
Name: order.Name,
|
||||
Timeout: int64(math.Ceil(remaining.Seconds())),
|
||||
Fiat: order.Fiat,
|
||||
ClientFingerprint: fp,
|
||||
}
|
||||
|
||||
newOrder, err := model.RebuildOrder(order, params)
|
||||
if err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("update order failed: %s", err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
// 返回响应数据
|
||||
ctx.JSON(200, respSuccJson(gin.H{
|
||||
"fiat": newOrder.Fiat,
|
||||
"trade_type": newOrder.TradeType,
|
||||
"trade_id": newOrder.TradeId,
|
||||
"order_id": newOrder.OrderId,
|
||||
"status": newOrder.Status,
|
||||
"amount": newOrder.Money,
|
||||
"actual_amount": newOrder.Amount,
|
||||
"token": newOrder.Address,
|
||||
"expiration_time": uint64(newOrder.ExpiredAt.Sub(time.Now()).Seconds()),
|
||||
"payment_url": model.CheckoutUrl(host, newOrder.TradeId),
|
||||
}))
|
||||
}
|
||||
|
||||
func (Vupay) CreateTransaction(ctx *gin.Context) {
|
||||
var req createReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("请求参数错误:%s", err.Error())))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if !utils.IsAllowedCallbackURL(req.NotifyURL) {
|
||||
ctx.JSON(200, respFailJson("notify_url 地址不合法"))
|
||||
|
||||
return
|
||||
}
|
||||
if !utils.IsAllowedCallbackURL(req.RedirectURL) {
|
||||
ctx.JSON(200, respFailJson("redirect_url 地址不合法"))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if req.Fiat == "" {
|
||||
req.Fiat = model.CNY
|
||||
}
|
||||
if req.TradeType == "" {
|
||||
req.TradeType = string(model.UsdtTrc20)
|
||||
}
|
||||
|
||||
order, err := model.StartBuildOrder(model.OrderParams{
|
||||
Money: decimal.NewFromFloat(req.Amount),
|
||||
ApiType: model.OrderApiTypeVupay,
|
||||
Address: req.Address,
|
||||
AddressLocked: req.Amount == 0,
|
||||
OrderId: req.OrderID,
|
||||
TradeType: model.TradeType(req.TradeType),
|
||||
RedirectUrl: req.RedirectURL,
|
||||
NotifyUrl: req.NotifyURL,
|
||||
Name: req.Name,
|
||||
Timeout: req.Timeout,
|
||||
Rate: req.Rate,
|
||||
Fiat: req.Fiat,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("订单创建失败:%s", err.Error())))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Info(fmt.Sprintf("订单创建成功 商户订单:%s", req.OrderID))
|
||||
|
||||
// 返回响应数据
|
||||
ctx.JSON(200, respSuccJson(gin.H{
|
||||
"fiat": order.Fiat,
|
||||
"trade_type": order.TradeType,
|
||||
"trade_id": order.TradeId,
|
||||
"order_id": order.OrderId,
|
||||
"status": order.Status,
|
||||
"amount": order.Money,
|
||||
"actual_amount": order.Amount,
|
||||
"token": order.Address,
|
||||
"expiration_time": uint64(order.ExpiredAt.Sub(time.Now()).Seconds()),
|
||||
"payment_url": model.CheckoutUrl(utils.GetRequestHost(ctx.Request), order.TradeId),
|
||||
}))
|
||||
}
|
||||
|
||||
func (Vupay) CancelTransaction(ctx *gin.Context) {
|
||||
var req cancelReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("请求参数错误:%s", err.Error())))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
order, ok := model.GetTradeOrder(req.TradeID)
|
||||
if !ok {
|
||||
ctx.JSON(200, respFailJson("订单不存在"))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if order.Status != model.OrderStatusWaiting {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("当前订单(%s)状态不允许取消", req.TradeID)))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err := order.SetCanceled(); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("订单取消失败:%s", err.Error())))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(200, respSuccJson(gin.H{"trade_id": req.TradeID}))
|
||||
}
|
||||
|
||||
func (Vupay) Checkout(ctx *gin.Context) {
|
||||
tradeId := ctx.Param("trade_id")
|
||||
if _, ok := model.GetTradeOrder(tradeId); !ok {
|
||||
ctx.String(200, "order not found")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 收银台模板
|
||||
tmpl := model.GetC(model.PaymentCheckout) + "/checkout.html"
|
||||
|
||||
ctx.HTML(200, tmpl, gin.H{"trade_id": tradeId})
|
||||
}
|
||||
|
||||
func (Vupay) GetMethods(ctx *gin.Context) {
|
||||
var req methodsReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("request error: %s", err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
order, ok := loadPayOrder(ctx, req.TradeID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if order.Status != model.OrderStatusWaiting {
|
||||
ctx.JSON(200, respFailJson("error: Invalid order status"))
|
||||
return
|
||||
}
|
||||
|
||||
if order.TradeType != "" && !order.CanReselectPayment() {
|
||||
ctx.JSON(200, respFailJson("error: The order status does not allow retrieving the payment method"))
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(200, respSuccJson(gin.H{
|
||||
"methods": order.GetMethods(model.Crypto(req.Currency)),
|
||||
"network_sort": model.GetC(model.PaymentNetworkSort),
|
||||
}))
|
||||
}
|
||||
|
||||
func (Vupay) Info(ctx *gin.Context) {
|
||||
var req infoReq
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("参数错误:%s", err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
order, ok := loadPayOrder(ctx, req.TradeID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(200, respSuccJson(gin.H{
|
||||
"network": order.Network(), // 网络信息
|
||||
"trade_id": order.TradeId, // 交易编号
|
||||
"order_id": order.OrderId, // 商户订单
|
||||
"trade_type": order.TradeType, // 交易类型
|
||||
"status": order.Status, // 订单状态
|
||||
"money": order.Money, // 订单金额
|
||||
"actual_amount": order.Amount, // 实付数额
|
||||
"token": order.Address, // 收款地址
|
||||
"fiat": order.Fiat, // 法币类型
|
||||
"name": order.Name, // 商品名称
|
||||
"expired_at": order.ExpiredAt.Unix(), // 截止时间
|
||||
"created_at": order.CreatedAt.Time().Unix(), // 创建时间
|
||||
"trade_url": order.GetTxUrl(), // 链上详情
|
||||
"support_url": model.GetC(model.PaymentSupportUrl), // 客服链接
|
||||
"redirect_url": order.RedirectUrl(), // 跳转地址
|
||||
"reselect": order.CanReselectPayment(), // 是否允许确认交易类型后重选
|
||||
}))
|
||||
}
|
||||
|
||||
func (Vupay) SignVerify(ctx *gin.Context) {
|
||||
rawData, err := ctx.GetRawData()
|
||||
if err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("json 数据读取错误 %s", err.Error())))
|
||||
ctx.Abort()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
m := make(map[string]any)
|
||||
if err = json.Unmarshal(rawData, &m); err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("json 数据解析错误 %s", err.Error())))
|
||||
ctx.Abort()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
sign, ok := m["signature"]
|
||||
if !ok {
|
||||
ctx.JSON(200, respFailJson("签名丢失"))
|
||||
ctx.Abort()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if utils.VupaySign(m, model.AuthToken()) != sign {
|
||||
ctx.JSON(200, respFailJson("签名错误"))
|
||||
ctx.Abort()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Request.Body = io.NopCloser(bytes.NewBuffer(rawData)) // 回写数据
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
func respFailJson(message string) gin.H {
|
||||
|
||||
return gin.H{"status_code": 400, "message": message}
|
||||
}
|
||||
|
||||
func respSuccJson(data interface{}) gin.H {
|
||||
return gin.H{"status_code": 200, "message": "success", "data": data, "request_id": ""}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
package help
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"fmt"
|
||||
"github.com/google/uuid"
|
||||
"os"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// IsExist 判断文件是否存在
|
||||
func IsExist(path string) bool {
|
||||
_, err := os.Stat(path)
|
||||
if err == nil {
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if os.IsExist(err) {
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func GetEnv(key string) string {
|
||||
|
||||
return os.Getenv(key)
|
||||
}
|
||||
|
||||
func GenerateSignature(data map[string]interface{}, token string) string {
|
||||
keys := make([]string, 0, len(data))
|
||||
for k := range data {
|
||||
if k == "signature" {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
var sign strings.Builder
|
||||
for _, k := range keys {
|
||||
v := data[k]
|
||||
if v == nil || v == "" {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
sign.WriteString(k)
|
||||
sign.WriteString("=")
|
||||
sign.WriteString(fmt.Sprintf("%v", v))
|
||||
sign.WriteString("&")
|
||||
}
|
||||
|
||||
signString := strings.TrimRight(sign.String(), "&")
|
||||
|
||||
return Md5String(signString + token)
|
||||
}
|
||||
|
||||
func GenerateTradeId() string {
|
||||
|
||||
return uuid.New().String()
|
||||
}
|
||||
|
||||
func Md5String(text string) string {
|
||||
|
||||
return fmt.Sprintf("%x", md5.Sum([]byte(text)))
|
||||
}
|
||||
|
||||
func Ec(str string) string {
|
||||
escapeChars := []string{"_", "*", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!"}
|
||||
|
||||
for _, char := range escapeChars {
|
||||
str = strings.ReplaceAll(str, char, "\\"+char)
|
||||
}
|
||||
|
||||
return str
|
||||
}
|
||||
|
||||
func IsNumber(s string) bool {
|
||||
match, err := regexp.MatchString(`^\d+\.?\d*$`, s)
|
||||
|
||||
return match && err == nil
|
||||
}
|
||||
|
||||
func IsValidTRONWalletAddress(address string) bool {
|
||||
match, err := regexp.MatchString(`^T[a-zA-Z0-9]{33}$`, address)
|
||||
|
||||
return match && err == nil
|
||||
}
|
||||
|
||||
func MaskAddress(address string) string {
|
||||
if len(address) <= 20 {
|
||||
|
||||
return address
|
||||
}
|
||||
|
||||
return address[:8] + " ***** " + address[len(address)-10:]
|
||||
}
|
||||
+66
-21
@@ -1,17 +1,24 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/natefinch/lumberjack"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var logger *logrus.Logger
|
||||
var (
|
||||
Task *logrus.Logger
|
||||
be *logrus.Logger
|
||||
loggers []*lumberjack.Logger
|
||||
logPath string
|
||||
)
|
||||
|
||||
func init() {
|
||||
var level, logFile = logrus.InfoLevel, config.GetOutputLog()
|
||||
logger = logrus.New()
|
||||
func newLogger(file string) (*logrus.Logger, error) {
|
||||
logger := logrus.New()
|
||||
logger.SetFormatter(&logrus.TextFormatter{
|
||||
ForceColors: true,
|
||||
ForceQuote: true,
|
||||
@@ -19,38 +26,76 @@ func init() {
|
||||
FullTimestamp: true,
|
||||
})
|
||||
|
||||
logger.SetLevel(level)
|
||||
|
||||
output, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
|
||||
if err != nil {
|
||||
|
||||
panic(err)
|
||||
logger.SetLevel(logrus.InfoLevel)
|
||||
output := &lumberjack.Logger{
|
||||
Filename: file,
|
||||
MaxSize: 300,
|
||||
MaxBackups: 5,
|
||||
MaxAge: 7,
|
||||
Compress: true,
|
||||
}
|
||||
|
||||
logger.SetOutput(output)
|
||||
loggers = append(loggers, output)
|
||||
|
||||
return logger, nil
|
||||
}
|
||||
|
||||
func Init(dir string) error {
|
||||
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
|
||||
return fmt.Errorf("创建日志目录失败:%w", err)
|
||||
}
|
||||
|
||||
var err error
|
||||
|
||||
be, err = newLogger(filepath.Join(dir, "vupay.log"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
Task, err = newLogger(filepath.Join(dir, "task.log"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logPath = dir
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func Debug(args ...interface{}) {
|
||||
|
||||
logger.Debugln(args...)
|
||||
be.Debugln(args...)
|
||||
}
|
||||
|
||||
func Info(args ...interface{}) {
|
||||
|
||||
logger.Infoln(args...)
|
||||
be.Infoln(args...)
|
||||
}
|
||||
|
||||
func Error(args ...interface{}) {
|
||||
|
||||
logger.Errorln(args...)
|
||||
be.Errorln(args...)
|
||||
}
|
||||
|
||||
func Warn(args ...interface{}) {
|
||||
|
||||
logger.Warnln(args...)
|
||||
be.Warnln(args...)
|
||||
}
|
||||
|
||||
func GetWriter() *io.PipeWriter {
|
||||
|
||||
return logger.Writer()
|
||||
return be.Writer()
|
||||
}
|
||||
|
||||
func GetPath() string {
|
||||
return logPath
|
||||
}
|
||||
|
||||
func Close() {
|
||||
for _, f := range loggers {
|
||||
if f != nil {
|
||||
if err := f.Close(); err != nil {
|
||||
_, _ = fmt.Fprintln(os.Stderr, fmt.Sprintf("日志句柄资源关闭错误:%s", err.Error()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loggers = nil
|
||||
}
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
const StatusEnable = 1
|
||||
const StatusDisable = 0
|
||||
const OtherNotifyEnable = 1
|
||||
const OtherNotifyDisable = 0
|
||||
|
||||
type WalletAddress struct {
|
||||
Id int64 `gorm:"primary_key;AUTO_INCREMENT"`
|
||||
Address string `gorm:"type:varchar(255);not null;unique"`
|
||||
Status int `gorm:"type:tinyint(1);not null;default:1"`
|
||||
OtherNotify int `gorm:"type:tinyint(1);not null;default:1"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime;type:timestamp;not null"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime;type:timestamp;not null"`
|
||||
}
|
||||
|
||||
// 启动时添加初始钱包地址
|
||||
func addStartWalletAddress() {
|
||||
var _wa WalletAddress
|
||||
|
||||
for _, address := range config.GetInitWalletAddress() {
|
||||
if help.IsValidTRONWalletAddress(address) {
|
||||
var _res2 = DB.Where("address = ?", address).First(&_wa)
|
||||
if errors.Is(_res2.Error, gorm.ErrRecordNotFound) {
|
||||
var _row = WalletAddress{Address: address, Status: StatusEnable}
|
||||
var _res = DB.Create(&_row)
|
||||
if _res.Error == nil && _res.RowsAffected == 1 {
|
||||
fmt.Println("✅钱包地址添加成功:", address)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (wa *WalletAddress) TableName() string {
|
||||
|
||||
return "wallet_address"
|
||||
}
|
||||
|
||||
func (wa *WalletAddress) SetStatus(status int) {
|
||||
wa.Status = status
|
||||
DB.Save(wa)
|
||||
}
|
||||
|
||||
func (wa *WalletAddress) SetOtherNotify(notify int) {
|
||||
wa.OtherNotify = notify
|
||||
|
||||
DB.Save(wa)
|
||||
}
|
||||
|
||||
func (wa *WalletAddress) Delete() {
|
||||
DB.Delete(wa)
|
||||
}
|
||||
|
||||
func GetAvailableAddress() []WalletAddress {
|
||||
var rows []WalletAddress
|
||||
|
||||
DB.Where("status = ?", StatusEnable).Find(&rows)
|
||||
|
||||
return rows
|
||||
}
|
||||
|
||||
func GetOtherNotify(address string) bool {
|
||||
var row WalletAddress
|
||||
var res = DB.Where("status = ? and address = ?", StatusEnable, address).First(&row)
|
||||
if res.Error != nil {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return row.OtherNotify == 1
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package model
|
||||
|
||||
type Checkout struct {
|
||||
Name string `json:"name"`
|
||||
Author string `json:"author"`
|
||||
Desc string `json:"desc"`
|
||||
Link string `json:"link"`
|
||||
}
|
||||
|
||||
var checkoutMap = make(map[string]Checkout)
|
||||
|
||||
// RegisterCheckout 注册收银台模板
|
||||
func RegisterCheckout(name string, checkout Checkout) {
|
||||
checkoutMap[name] = checkout
|
||||
}
|
||||
|
||||
func CheckoutList() map[string]Checkout {
|
||||
return checkoutMap
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/go-cache"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var confCache sync.Map
|
||||
var defaultConf = map[ConfKey]string{
|
||||
ApiAppUri: "",
|
||||
RateSyncInterval: "3600",
|
||||
AtomUSDT: "0.01",
|
||||
AtomUSDC: "0.01",
|
||||
AtomTRX: "0.01",
|
||||
AtomBNB: "0.00001",
|
||||
AtomETH: "0.000001",
|
||||
AtomGRAM: "0.01",
|
||||
MonitorMinAmount: "0.01",
|
||||
PaymentMinAmount: "0.01",
|
||||
PaymentMaxAmount: "99999",
|
||||
RpcEndpointTron: "grpc.trongrid.io:50051",
|
||||
RpcEndpointBsc: "https://binance-smart-chain-public.nodies.app/",
|
||||
RpcEndpointSolana: "https://solana-rpc.publicnode.com/",
|
||||
RpcEndpointXlayer: "https://xlayerrpc.okx.com/",
|
||||
RpcEndpointPolygon: "https://polygon-public.nodies.app/",
|
||||
RpcEndpointArbitrum: "https://arb1.arbitrum.io/rpc",
|
||||
RpcEndpointEthereum: "https://ethereum-public.nodies.app/",
|
||||
RpcEndpointBase: "https://base-public.nodies.app/",
|
||||
RpcEndpointAptos: "https://aptos-rest.publicnode.com/",
|
||||
RpcEndpointPlasma: "https://rpc.plasma.to/",
|
||||
RpcGlobalConfigUrlTon: "https://ton.org/global-config.json",
|
||||
NotifyMaxRetry: "10",
|
||||
BlockHeightMaxDiff: "1000",
|
||||
BlockOffsetConfirm: "0",
|
||||
PaymentTimeout: "1200", // 20分钟
|
||||
PaymentCheckout: "official", // 官方模板
|
||||
PaymentMatchMode: string(Classic),
|
||||
PaymentSupportUrl: "",
|
||||
PaymentLookbackHour: "3",
|
||||
PaymentNetworkSort: "",
|
||||
SystemInstallLock: "0",
|
||||
RateSyncCoingeckoApiUrl: "https://api.coingecko.com",
|
||||
RateSyncHistoryDays: "30",
|
||||
MqttTopicPrefix: "vupay",
|
||||
HomeRedirectUrl: "",
|
||||
}
|
||||
|
||||
type Conf struct {
|
||||
K ConfKey `gorm:"column:k;type:varchar(32);not null;primaryKey" json:"key"`
|
||||
V string `gorm:"column:v;type:varchar(512);not null" json:"val"`
|
||||
}
|
||||
|
||||
func (c Conf) TableName() string {
|
||||
|
||||
return "vupay_conf"
|
||||
}
|
||||
|
||||
func SetK(k ConfKey, v string) {
|
||||
if err = Db.Transaction(func(db *gorm.DB) error {
|
||||
if err2 := db.Where("k = ?", k).Delete(&Conf{}).Error; err2 != nil {
|
||||
|
||||
return err2
|
||||
}
|
||||
if err2 := db.Create(&Conf{K: k, V: v}).Error; err2 != nil {
|
||||
|
||||
return err2
|
||||
}
|
||||
|
||||
defer RefreshC()
|
||||
|
||||
return nil
|
||||
}); err != nil {
|
||||
_, _ = fmt.Fprintln(os.Stderr, fmt.Sprintf("设置配置项 %s 错误:%s", k, err.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
func GetK(k ConfKey) string {
|
||||
var row Conf
|
||||
|
||||
var tx = Db.Where("k = ?", k).Limit(1).Find(&row)
|
||||
if tx.Error == nil {
|
||||
|
||||
return row.V
|
||||
}
|
||||
|
||||
_, _ = fmt.Fprintln(os.Stderr, fmt.Sprintf("获取配置项 %s 错误:%s", k, tx.Error.Error()))
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetVs(keys []ConfKey) map[ConfKey]string {
|
||||
var rows = make([]Conf, 0)
|
||||
Db.Where("k IN ?", keys).Find(&rows)
|
||||
|
||||
var result = make(map[ConfKey]string)
|
||||
for _, row := range rows {
|
||||
result[row.K] = row.V
|
||||
}
|
||||
|
||||
for _, k := range keys {
|
||||
if _, ok := result[k]; !ok {
|
||||
result[k] = ""
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// GetC 从缓存获取配置,适用于高频读取,依赖 RefreshC 刷新缓存
|
||||
func GetC(k ConfKey) string {
|
||||
value, ok := confCache.Load(k)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
|
||||
return value.(string)
|
||||
}
|
||||
|
||||
func RefreshC() {
|
||||
var rows = make([]Conf, 0)
|
||||
Db.Find(&rows)
|
||||
|
||||
for _, row := range rows {
|
||||
confCache.Store(row.K, row.V)
|
||||
}
|
||||
}
|
||||
|
||||
func CheckoutUrl(host, id string) string {
|
||||
uri := GetK(ApiAppUri)
|
||||
if uri == "" {
|
||||
uri = host
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s/pay/checkout/%s", uri, id)
|
||||
}
|
||||
|
||||
func ConfInit() {
|
||||
var hash = utils.StrSha256(utils.Md5String(time.Now().String()))
|
||||
var secure = "/" + hash[:10]
|
||||
var token = strings.ToUpper(utils.Md5String(hash[18:28]))
|
||||
var username = hash[10:20]
|
||||
var password = hash[20:30]
|
||||
var encrypt, _ = bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
var data = map[ConfKey]string{
|
||||
ApiAuthToken: token,
|
||||
AdminSecret: utils.StrSha256(hash),
|
||||
AdminSecure: secure,
|
||||
AdminUsername: username,
|
||||
AdminPassword: string(encrypt),
|
||||
}
|
||||
var rows = make([]Conf, 0)
|
||||
for k, v := range data {
|
||||
rows = append(rows, Conf{K: k, V: v})
|
||||
}
|
||||
for k, v := range defaultConf {
|
||||
rows = append(rows, Conf{K: k, V: v})
|
||||
}
|
||||
|
||||
fmt.Println()
|
||||
fmt.Println("╔═══════════════════════════════════════════════════════════════════════")
|
||||
fmt.Println("║ 🎉 欢迎使用 VUPAY - 首次运行检测,初始化配置完成")
|
||||
fmt.Println("╚═══════════════════════════════════════════════════════════════════════")
|
||||
fmt.Println()
|
||||
fmt.Println("┏━━ 🔐 后台登录信息 (请立即保存!)")
|
||||
fmt.Println("┃")
|
||||
fmt.Printf("┃ 👤 登录账号: %s\n", username)
|
||||
fmt.Printf("┃ 🔑 登录密码: %s\n", password)
|
||||
fmt.Printf("┃ 🛡️ 安全入口: %s\n", secure)
|
||||
fmt.Println("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
|
||||
fmt.Println()
|
||||
fmt.Println("┏━━ 🔌 API 对接信息")
|
||||
fmt.Println("┃")
|
||||
fmt.Printf("┃ 🎫 对接令牌: %s\n", token)
|
||||
fmt.Println("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
|
||||
fmt.Println()
|
||||
fmt.Println("⚠️ 重要提示:")
|
||||
fmt.Println(" • 以上信息仅显示一次,请务必妥善保存至安全位置")
|
||||
fmt.Println(" • 登录密码遗忘可通过 'reset' 命令重置")
|
||||
fmt.Println(" • API 令牌可在网页后台进行修改")
|
||||
fmt.Println(" • 建议定期更换密码以确保账户安全")
|
||||
fmt.Println()
|
||||
fmt.Println("═══════════════════════════════════════════════════════════════════════")
|
||||
fmt.Println()
|
||||
|
||||
Db.Create(&rows)
|
||||
|
||||
// 数据丢到缓存,前台首次访问时会展示这部分初始化信息;明文密码只这一次保存到缓存,不写入数据库
|
||||
cache.Set(string(SystemInstallLock), gin.H{
|
||||
"username": username,
|
||||
"password": password,
|
||||
"secure": secure,
|
||||
"token": token,
|
||||
}, -1)
|
||||
}
|
||||
|
||||
func AuthToken() string {
|
||||
|
||||
return GetK(ApiAuthToken)
|
||||
}
|
||||
|
||||
func IsInstalled() bool {
|
||||
return GetC(SystemInstallLock) == "1"
|
||||
}
|
||||
|
||||
func InstallLock() {
|
||||
SetK(SystemInstallLock, "1")
|
||||
}
|
||||
|
||||
func GetInstallInfo() gin.H {
|
||||
if info, ok := cache.Get(string(SystemInstallLock)); ok {
|
||||
|
||||
return info.(gin.H)
|
||||
}
|
||||
|
||||
return gin.H{}
|
||||
}
|
||||
|
||||
func GetTronGridApiKeys() []string {
|
||||
arr := strings.Split(GetC(RpcEndpointTronGridApiKey), ",")
|
||||
keys := make([]string, 0)
|
||||
for _, v := range arr {
|
||||
if v != "" {
|
||||
keys = append(keys, v)
|
||||
}
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
func FillDefaultConf() {
|
||||
var existKeys []string
|
||||
Db.Model(&Conf{}).Pluck("k", &existKeys)
|
||||
|
||||
existSet := make(map[ConfKey]struct{}, len(existKeys))
|
||||
for _, k := range existKeys {
|
||||
existSet[ConfKey(k)] = struct{}{}
|
||||
}
|
||||
|
||||
var rows []Conf
|
||||
for k, v := range defaultConf {
|
||||
if _, ok := existSet[k]; !ok {
|
||||
rows = append(rows, Conf{K: k, V: v})
|
||||
}
|
||||
}
|
||||
if len(rows) > 0 {
|
||||
Db.Create(&rows)
|
||||
}
|
||||
}
|
||||
|
||||
func GetLookbackHour() time.Duration {
|
||||
var hour = time.Hour * -1
|
||||
var num = cast.ToInt(GetC(PaymentLookbackHour))
|
||||
|
||||
return time.Duration(num) * hour
|
||||
}
|
||||
+121
-38
@@ -1,45 +1,128 @@
|
||||
package model
|
||||
|
||||
const installSql = `
|
||||
-- trade_orders definition
|
||||
import "github.com/shopspring/decimal"
|
||||
|
||||
CREATE TABLE trade_orders (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
order_id TEXT NOT NULL, -- 客户订单ID
|
||||
trade_id TEXT UNIQUE NOT NULL, -- 本地订单ID
|
||||
trade_hash TEXT NULL, -- 交易哈希
|
||||
usdt_rate TEXT NOT NULL, -- USDT汇率
|
||||
amount TEXT NOT NULL, -- USDT交易数额
|
||||
money TEXT NOT NULL, -- 订单交易金额
|
||||
address TEXT NOT NULL, -- 收款地址
|
||||
from_address TEXT NOT NULL, -- 支付地址
|
||||
status INTEGER DEFAULT 1 NOT NULL, -- 交易状态 1:等待支付 2:支付成功 3:订单过期
|
||||
return_url TEXT NULL, -- 同步地址
|
||||
notify_url TEXT NOT NULL, -- 异步地址
|
||||
notify_num INTEGER DEFAULT 0, -- 回调次数
|
||||
notify_state INTEGER DEFAULT 0, -- 回调状态 1:成功 0:失败
|
||||
expired_at TIMESTAMP NOT NULL, -- 订单失效时间
|
||||
created_at TIMESTAMP NOT NULL, -- 订单创建时间
|
||||
confirmed_at TIMESTAMP NULL, -- 交易确认时间
|
||||
updated_at TIMESTAMP NULL -- 最后更新时间
|
||||
);
|
||||
type ConfKey string
|
||||
type Fiat string
|
||||
type CoinId string
|
||||
type Crypto string
|
||||
type TradeType string
|
||||
type MatchMode string
|
||||
type Network string
|
||||
type Range struct {
|
||||
MinAmount decimal.Decimal
|
||||
MaxAmount decimal.Decimal
|
||||
}
|
||||
type TradeTypeConf struct {
|
||||
Alias string // 类型别名,主要用户前端展示
|
||||
NetworkName string // 网络名称,用于前端展示
|
||||
Network Network // 所属区块链网络
|
||||
Crypto Crypto // 币种类型
|
||||
Native bool // 是否原生币
|
||||
Contract string // 合约地址,原生币为空
|
||||
Decimal int32 // 小数位
|
||||
AmountRange Range // 合法数额范围;这里特指则扫块时[数额范围],目前偷懒全部写死一个大概合理的范围,后面有问题再说...
|
||||
ExplorerFmt string // 区块浏览器交易链接格式化字符串,%s 位置替换为交易哈希
|
||||
EndpointKey ConfKey // RPC 端点配置键
|
||||
AddrCaseSens bool // 钱包地址是否大小写敏感,如果为 false 则会统一转为小写比较
|
||||
}
|
||||
|
||||
-- wallet_address definition
|
||||
const (
|
||||
AdminUsername ConfKey = "admin_username"
|
||||
AdminPassword ConfKey = "admin_password"
|
||||
AdminSecure ConfKey = "admin_secure"
|
||||
AdminSecret ConfKey = "admin_secret"
|
||||
AdminLoginIP ConfKey = "admin_login_ip"
|
||||
AdminLoginAt ConfKey = "admin_login_at"
|
||||
|
||||
CREATE TABLE wallet_address (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
address TEXT UNIQUE NOT NULL, -- 钱包地址
|
||||
status INTEGER DEFAULT 1 NOT NULL, -- 地址状态 1启动 0禁止
|
||||
other_notify INTEGER DEFAULT 1 NOT NULL, -- 其它转账通知 1启动 0禁止
|
||||
created_at TIMESTAMP NULL,
|
||||
updated_at TIMESTAMP NULL
|
||||
);
|
||||
ApiAuthToken ConfKey = "api_auth_token" // API 对接令牌
|
||||
ApiAppUri ConfKey = "api_app_uri" // API 对接地址(收银台地址)
|
||||
|
||||
-- notify_record definition
|
||||
AtomUSDT ConfKey = "atom_usdt"
|
||||
AtomUSDC ConfKey = "atom_usdc"
|
||||
AtomTRX ConfKey = "atom_trx"
|
||||
AtomBNB ConfKey = "atom_bnb"
|
||||
AtomETH ConfKey = "atom_eth"
|
||||
AtomGRAM ConfKey = "atom_gram"
|
||||
|
||||
CREATE TABLE notify_record (
|
||||
txid TEXT PRIMARY KEY NOT NULL, -- 交易哈希
|
||||
created_at TIMESTAMP NOT NULL, -- 创建时间
|
||||
updated_at TIMESTAMP NULL -- 更新时间
|
||||
);
|
||||
`
|
||||
MonitorMinAmount ConfKey = "monitor_min_amount" // 监控最小金额,低于此金额的入账不进行通知
|
||||
PaymentMinAmount ConfKey = "payment_min_amount"
|
||||
PaymentMaxAmount ConfKey = "payment_max_amount"
|
||||
PaymentTimeout ConfKey = "payment_timeout" // 订单支付超时时间,单位秒
|
||||
PaymentCheckout ConfKey = "payment_checkout" // 收银台模板
|
||||
PaymentMatchMode ConfKey = "payment_match_mode" // 订单金额匹配模式
|
||||
PaymentSupportUrl ConfKey = "payment_support_url" // 订单支付客服链接
|
||||
PaymentLookbackHour ConfKey = "payment_lookback_hour" // 订单回溯时间
|
||||
PaymentNetworkSort ConfKey = "payment_network_sort" // 收银台网络顺序,逗号分隔
|
||||
|
||||
RpcEndpointPlasma ConfKey = "rpc_endpoint_plasma" // Plasma RPC节点
|
||||
RpcEndpointBsc ConfKey = "rpc_endpoint_bsc" // BSC RPC节点
|
||||
RpcEndpointSolana ConfKey = "rpc_endpoint_solana" // Solana RPC节点
|
||||
RpcEndpointXlayer ConfKey = "rpc_endpoint_xlayer" // Xlayer RPC节点
|
||||
RpcEndpointPolygon ConfKey = "rpc_endpoint_polygon" // Polygon RPC节点
|
||||
RpcEndpointArbitrum ConfKey = "rpc_endpoint_arbitrum" // Arbitrum RPC节点
|
||||
RpcEndpointEthereum ConfKey = "rpc_endpoint_ethereum" // Ethereum RPC节点
|
||||
RpcEndpointBase ConfKey = "rpc_endpoint_base" // Base RPC节点
|
||||
RpcEndpointAptos ConfKey = "rpc_endpoint_aptos" // APTOS RPC节点
|
||||
RpcEndpointTron ConfKey = "rpc_endpoint_tron" // TRON RPC节点
|
||||
RpcEndpointTronGridApiKey ConfKey = "rpc_endpoint_tron_grid_api_key" // TRON RPC节点 TronGrid Api Key
|
||||
RpcGlobalConfigUrlTon ConfKey = "rpc_global_config_url_ton" // Ton Global Config Url
|
||||
|
||||
RateSyncCoingeckoApiUrl ConfKey = "rate_sync_coingecko_api_url" // 汇率同步 Coingecko Api URL
|
||||
RateSyncCoingeckoApiKey ConfKey = "rate_sync_coingecko_api_key" // 汇率同步 Coingecko Api Key
|
||||
RateSyncInterval ConfKey = "rate_sync_interval" // 汇率同步间隔,单位秒
|
||||
RateSyncHistoryDays ConfKey = "rate_sync_history_days" // 历史汇率保存天数
|
||||
|
||||
NotifyMaxRetry ConfKey = "notify_max_retry" // 最大重试次数,订单回调失败
|
||||
BlockHeightMaxDiff ConfKey = "block_height_max_diff" // 区块高度最大差值,超过此值则以当前区块高度为准,重新开始扫描
|
||||
BlockOffsetConfirm ConfKey = "block_offset_confirm" // 区块偏移确认数,扫描时以当前区块高度减去此偏移量为准,避免重链导致的订单回调失败
|
||||
|
||||
MqttHost ConfKey = "mqtt_host"
|
||||
MqttPort ConfKey = "mqtt_port"
|
||||
MqttUser ConfKey = "mqtt_user"
|
||||
MqttPass ConfKey = "mqtt_pass"
|
||||
MqttPublishQos ConfKey = "mqtt_publish_qos"
|
||||
MqttTopicPrefix ConfKey = "mqtt_topic_prefix" // 消息发布 Topic 路径前缀
|
||||
MqttNetworks ConfKey = "mqtt_networks" // 需要持续监控的区块网络
|
||||
|
||||
NotifierParams ConfKey = "notifier_params" // 通知参数 (token, chat_id, email
|
||||
NotifierChannel ConfKey = "notifier_channel" // 通知渠道 (telegram, wechat, email
|
||||
|
||||
SystemInstallLock ConfKey = "system_install_lock" // 系统安装锁
|
||||
HomeRedirectUrl ConfKey = "home_redirect_url"
|
||||
)
|
||||
const (
|
||||
CNY Fiat = "CNY"
|
||||
USD Fiat = "USD"
|
||||
JPY Fiat = "JPY"
|
||||
EUR Fiat = "EUR"
|
||||
GBP Fiat = "GBP"
|
||||
)
|
||||
const (
|
||||
USDT Crypto = "USDT"
|
||||
USDC Crypto = "USDC"
|
||||
TRX Crypto = "TRX"
|
||||
BNB Crypto = "BNB"
|
||||
ETH Crypto = "ETH"
|
||||
GRAM Crypto = "GRAM" // 其实就是 Ton
|
||||
)
|
||||
const (
|
||||
Classic MatchMode = "classic" // 经典模式,精确匹配
|
||||
HasPrefix MatchMode = "has_prefix" // 前缀匹配,按原子精度截断后比较,只容忍精度以下的多付
|
||||
RoundOff MatchMode = "round_off" // 数值修约,四舍五入,允许容错
|
||||
)
|
||||
|
||||
// USD 交易类型常见扫描范围
|
||||
var usdGeneralRange = Range{
|
||||
MinAmount: decimal.NewFromFloat(0.01),
|
||||
MaxAmount: decimal.NewFromFloat(1000000),
|
||||
}
|
||||
|
||||
// registry 交易类型注册表【由init函数自动维护】
|
||||
var networkTradesMap = make(map[Network][]TradeType)
|
||||
var networkEndpointMap = make(map[Network]ConfKey)
|
||||
var contractTradeMap = make(map[string]TradeType)
|
||||
var contractDecimalMap = make(map[string]int32)
|
||||
var tradeAmountRangeMap = make(map[TradeType]Range)
|
||||
var explorerUrlMap = make(map[TradeType]string)
|
||||
var cryptoAtomKeys = make(map[Crypto]ConfKey)
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
var localLocation = time.Local
|
||||
|
||||
type Datetime time.Time
|
||||
|
||||
func (d *Datetime) MarshalJSON() ([]byte, error) {
|
||||
tTime := time.Time(*d).In(localLocation)
|
||||
return []byte(fmt.Sprintf("\"%v\"", tTime.Format("2006-01-02 15:04:05"))), nil
|
||||
}
|
||||
|
||||
func (d Datetime) Value() (driver.Value, error) {
|
||||
var zeroTime time.Time
|
||||
tlt := time.Time(d)
|
||||
if tlt.UnixNano() == zeroTime.UnixNano() {
|
||||
return nil, nil
|
||||
}
|
||||
return tlt, nil
|
||||
}
|
||||
|
||||
func (d *Datetime) Scan(v interface{}) error {
|
||||
if value, ok := v.(time.Time); ok {
|
||||
*d = Datetime(value)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("can not convert %v to timestamp", v)
|
||||
}
|
||||
|
||||
func (d *Datetime) String() string {
|
||||
return time.Time(*d).In(localLocation).Format(time.DateTime)
|
||||
}
|
||||
|
||||
func (d *Datetime) Year() string {
|
||||
return time.Time(*d).In(localLocation).Format("2006")
|
||||
}
|
||||
|
||||
func (d *Datetime) Before(u time.Time) bool {
|
||||
return time.Time(*d).Before(u)
|
||||
}
|
||||
|
||||
func (d *Datetime) Time() time.Time {
|
||||
return time.Time(*d).In(localLocation)
|
||||
}
|
||||
|
||||
func (d *Datetime) Format(layout string) string {
|
||||
return time.Time(*d).In(localLocation).Format(layout)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// 202607081430 - 删除 vupay_order.trade_type_reselect 列
|
||||
func m202607081430DropOrderTradeTypeReselect() *gormigrate.Migration {
|
||||
return &gormigrate.Migration{
|
||||
ID: "202607081430_drop_order_trade_type_reselect",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
if !tx.Migrator().HasTable("vupay_order") {
|
||||
return nil
|
||||
}
|
||||
if tx.Migrator().HasColumn("vupay_order", "trade_type_reselect") {
|
||||
return tx.Exec("ALTER TABLE vupay_order DROP COLUMN trade_type_reselect").Error
|
||||
}
|
||||
return nil
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
if !tx.Migrator().HasTable("vupay_order") {
|
||||
return nil
|
||||
}
|
||||
if !tx.Migrator().HasColumn("vupay_order", "trade_type_reselect") {
|
||||
return tx.Exec("ALTER TABLE vupay_order ADD COLUMN trade_type_reselect INTEGER NOT NULL DEFAULT 0").Error
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const TableName = "vupay_migration"
|
||||
|
||||
var migrations = []*gormigrate.Migration{
|
||||
m202607081430DropOrderTradeTypeReselect(),
|
||||
}
|
||||
|
||||
func Run(db *gorm.DB, initModels []any) error {
|
||||
if err := db.AutoMigrate(initModels...); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
options := &gormigrate.Options{TableName: TableName}
|
||||
|
||||
// 旧版升级/全新安装,构建迁移表
|
||||
if !db.Migrator().HasTable(TableName) {
|
||||
if err := db.Exec("CREATE TABLE " + TableName + " (id VARCHAR(255) PRIMARY KEY)").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
m := gormigrate.New(db, options, migrations)
|
||||
|
||||
return m.Migrate()
|
||||
}
|
||||
+178
-19
@@ -1,35 +1,194 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"gorm.io/driver/sqlite"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/model/migration"
|
||||
"github.com/glebarez/sqlite"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var DB *gorm.DB
|
||||
var _err error
|
||||
var Db *gorm.DB
|
||||
var err error
|
||||
|
||||
func Init() error {
|
||||
var dbPath = config.GetDbPath()
|
||||
if !help.IsExist(dbPath) {
|
||||
DB, _err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
|
||||
if _err != nil {
|
||||
type Id struct {
|
||||
ID int64 `gorm:"column:id;primaryKey;autoIncrement;not null;comment:主键ID" json:"id"`
|
||||
}
|
||||
|
||||
return _err
|
||||
type AutoTimeAt struct {
|
||||
CreatedAt *Datetime `gorm:"column:created_at;not null;comment:记录创建时间;index" json:"created_at"`
|
||||
UpdatedAt *Datetime `gorm:"column:updated_at;not null;comment:最后更新时间" json:"updated_at"`
|
||||
}
|
||||
|
||||
// Init 按优先级选择数据库:MySQL DSN > PostgreSQL DSN > SQLite 文件。
|
||||
// 三者互斥,填了哪个用哪个;都不填就走 SQLite(默认)。
|
||||
func Init(db, postgresDSN, mysqlDSN string) error {
|
||||
switch {
|
||||
case mysqlDSN != "":
|
||||
return initMysql(mysqlDSN)
|
||||
case postgresDSN != "":
|
||||
return initPostgres(postgresDSN)
|
||||
default:
|
||||
return initSqlite(db)
|
||||
}
|
||||
}
|
||||
|
||||
func initSqlite(db string) error {
|
||||
if err := os.MkdirAll(filepath.Dir(db), os.ModePerm); err != nil {
|
||||
|
||||
return fmt.Errorf("创建数据库目录失败:%w", err)
|
||||
}
|
||||
|
||||
dsn := fmt.Sprintf("%s?cache=shared&mode=rwc"+
|
||||
"&_pragma=cache_size(-32000)"+ // 32MB 缓存,平衡内存占用
|
||||
"&_pragma=journal_mode(WAL)"+
|
||||
"&_pragma=busy_timeout(8000)"+ // 8 秒超时,兼顾慢速磁盘
|
||||
"&_pragma=synchronous(NORMAL)"+ // NORMAL 模式,性能与安全平衡
|
||||
"&_pragma=wal_autocheckpoint(1500)", // 适中的 checkpoint 频率
|
||||
db)
|
||||
Db, err = gorm.Open(sqlite.Open(dsn), &gorm.Config{})
|
||||
if err != nil {
|
||||
|
||||
return fmt.Errorf("数据库初始化失败:%w", err)
|
||||
}
|
||||
|
||||
{
|
||||
sqlDB, err := Db.DB()
|
||||
if err != nil {
|
||||
|
||||
return fmt.Errorf("获取数据库连接失败:%w", err)
|
||||
}
|
||||
sqlDB.SetMaxOpenConns(5)
|
||||
sqlDB.SetMaxIdleConns(3)
|
||||
sqlDB.SetConnMaxLifetime(0)
|
||||
}
|
||||
|
||||
if err = AutoMigrate(); err != nil {
|
||||
|
||||
return fmt.Errorf("数据库结构迁移失败:%w", err)
|
||||
}
|
||||
|
||||
var count int64
|
||||
Db.Model(&Conf{}).Count(&count)
|
||||
if count == 0 {
|
||||
ConfInit()
|
||||
}
|
||||
|
||||
FillDefaultConf()
|
||||
RefreshC()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func initPostgres(dsn string) error {
|
||||
// 首次启动可能出现 SLOW SQL 告警,这是由于连接池首次连接预热引起的,后续连接将正常
|
||||
|
||||
var err error
|
||||
Db, err = gorm.Open(postgres.New(postgres.Config{DSN: dsn, PreferSimpleProtocol: true}), &gorm.Config{})
|
||||
if err != nil {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
{
|
||||
sqlDB, err := Db.DB()
|
||||
if err != nil {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
DB.Exec(installSql)
|
||||
addStartWalletAddress()
|
||||
|
||||
return nil
|
||||
sqlDB.SetMaxIdleConns(10)
|
||||
sqlDB.SetMaxOpenConns(100)
|
||||
sqlDB.SetConnMaxLifetime(30 * time.Minute)
|
||||
sqlDB.SetConnMaxIdleTime(10 * time.Minute)
|
||||
}
|
||||
|
||||
DB, _err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
|
||||
if _err == nil {
|
||||
if err = AutoMigrate(); err != nil {
|
||||
|
||||
addStartWalletAddress()
|
||||
return err
|
||||
}
|
||||
|
||||
return _err
|
||||
var count int64
|
||||
Db.Model(&Conf{}).Count(&count)
|
||||
if count == 0 {
|
||||
ConfInit()
|
||||
}
|
||||
|
||||
FillDefaultConf()
|
||||
RefreshC()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func AutoMigrate() error {
|
||||
return migration.Run(Db, []any{
|
||||
&Wallet{},
|
||||
&Order{},
|
||||
&NotifyRecord{},
|
||||
&Conf{},
|
||||
&Rate{},
|
||||
})
|
||||
}
|
||||
|
||||
func Close() {
|
||||
if Db == nil {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
sqlDB, err := Db.DB()
|
||||
if err != nil {
|
||||
_, _ = fmt.Fprintln(os.Stderr, fmt.Sprintf("数据库资源句柄获取异常:%s", err.Error()))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err := sqlDB.Close(); err != nil {
|
||||
|
||||
_, _ = fmt.Fprintln(os.Stderr, fmt.Sprintf("数据库资源关闭错误:%s", err.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
func initMysql(dsn string) error {
|
||||
// 建议 DSN 里带上 charset=utf8mb4&parseTime=True&loc=Local,
|
||||
// 否则中文/时间字段会出问题:中文变 ?,时间按 UTC 存进去。
|
||||
Db, err = gorm.Open(mysql.New(mysql.Config{
|
||||
DSN: dsn,
|
||||
DefaultStringSize: 256,
|
||||
SkipInitializeWithVersion: false,
|
||||
}), &gorm.Config{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
{
|
||||
sqlDB, err := Db.DB()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sqlDB.SetMaxIdleConns(10)
|
||||
sqlDB.SetMaxOpenConns(100)
|
||||
sqlDB.SetConnMaxLifetime(30 * time.Minute)
|
||||
sqlDB.SetConnMaxIdleTime(10 * time.Minute)
|
||||
}
|
||||
|
||||
if err = AutoMigrate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var count int64
|
||||
Db.Model(&Conf{}).Count(&count)
|
||||
if count == 0 {
|
||||
ConfInit()
|
||||
}
|
||||
|
||||
FillDefaultConf()
|
||||
RefreshC()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package model
|
||||
|
||||
type NotifyRecord struct {
|
||||
Id
|
||||
Txid string `gorm:"type:varchar(128);uniqueIndex;not null;comment:交易哈希"`
|
||||
AutoTimeAt
|
||||
}
|
||||
|
||||
func (nr NotifyRecord) TableName() string {
|
||||
|
||||
return "vupay_notify"
|
||||
}
|
||||
|
||||
func IsNeedNotifyByTxid(txid string) bool {
|
||||
var record NotifyRecord
|
||||
var res = Db.Where("txid = ?", txid).Limit(1).Find(&record)
|
||||
if res.RowsAffected > 0 {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
var order Order
|
||||
var res2 = Db.Where("ref_hash = ?", txid).Limit(1).Find(&order)
|
||||
if res2.RowsAffected > 0 {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
"git.viaeon.com/admin/vupay/app/core"
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
const (
|
||||
OrderNotifyStateSucc = 1 // 回调成功
|
||||
OrderNotifyStateFail = 0 // 回调失败
|
||||
|
||||
OrderStatusWaiting = 1 // 等待支付
|
||||
OrderStatusSuccess = 2 // 交易确认成功
|
||||
OrderStatusExpired = 3 // 订单过期
|
||||
OrderStatusCanceled = 4 // 订单取消
|
||||
OrderStatusConfirming = 5 // 等待交易确认
|
||||
OrderStatusFailed = 6 // 交易确认失败
|
||||
|
||||
BscBnb TradeType = "bsc.bnb"
|
||||
EthereumEth TradeType = "ethereum.eth"
|
||||
TronTrx TradeType = "tron.trx"
|
||||
TonGram TradeType = "ton.gram"
|
||||
|
||||
UsdtTrc20 TradeType = "usdt.trc20"
|
||||
UsdcTrc20 TradeType = "usdc.trc20"
|
||||
UsdtPolygon TradeType = "usdt.polygon"
|
||||
UsdcPolygon TradeType = "usdc.polygon"
|
||||
UsdtArbitrum TradeType = "usdt.arbitrum"
|
||||
UsdcArbitrum TradeType = "usdc.arbitrum"
|
||||
UsdtErc20 TradeType = "usdt.erc20"
|
||||
UsdcErc20 TradeType = "usdc.erc20"
|
||||
UsdtBep20 TradeType = "usdt.bep20"
|
||||
UsdcBep20 TradeType = "usdc.bep20"
|
||||
UsdtXlayer TradeType = "usdt.xlayer"
|
||||
UsdcXlayer TradeType = "usdc.xlayer"
|
||||
UsdcBase TradeType = "usdc.base"
|
||||
UsdtSolana TradeType = "usdt.solana"
|
||||
UsdcSolana TradeType = "usdc.solana"
|
||||
UsdtAptos TradeType = "usdt.aptos"
|
||||
UsdcAptos TradeType = "usdc.aptos"
|
||||
UsdtPlasma TradeType = "usdt.plasma"
|
||||
UsdtTon TradeType = "usdt.ton"
|
||||
)
|
||||
|
||||
const (
|
||||
OrderApiTypeVupay = "vupay" // vupay
|
||||
OrderApiTypeVupayOrder = "vupay_order" // vupay create-order
|
||||
OrderApiTypeEpay = "epay" // 彩虹易支付
|
||||
OrderApiTypeAdmin = "admin" // 管理后台
|
||||
)
|
||||
|
||||
type Order struct {
|
||||
Id
|
||||
OrderId string `gorm:"column:order_id;type:varchar(128);not null;index;comment:商户ID" json:"order_id"`
|
||||
TradeId string `gorm:"column:trade_id;type:varchar(128);not null;uniqueIndex;comment:本地ID" json:"trade_id"`
|
||||
TradeType TradeType `gorm:"column:trade_type;type:varchar(20);not null;index;index:idx_order_status_trade,priority:2;comment:交易类型" json:"trade_type"`
|
||||
Fiat Fiat `gorm:"column:fiat;type:varchar(16);not null;index;default:CNY;comment:法定货币" json:"fiat"`
|
||||
Crypto Crypto `gorm:"column:crypto;type:varchar(16);not null;index;default:USDT;comment:加密货币" json:"crypto"`
|
||||
CurrencyLimit string `gorm:"column:currency_limit;type:varchar(255);not null;default:'';comment:限定币种" json:"currency_limit"`
|
||||
Rate string `gorm:"column:rate;type:varchar(10);not null;comment:交易汇率" json:"rate"`
|
||||
Amount string `gorm:"column:amount;type:varchar(32);not null;default:0.00;comment:交易数额" json:"amount"`
|
||||
Money string `gorm:"column:money;type:varchar(32);not null;default:0.00;comment:交易金额" json:"money"`
|
||||
Address string `gorm:"column:address;type:varchar(128);index;not null;comment:收款地址" json:"address"`
|
||||
FromAddress string `gorm:"column:from_address;type:varchar(128);not null;default:'';comment:支付地址" json:"from_address"`
|
||||
MatchAddress string `gorm:"column:match_address;type:varchar(128);not null;default:'';comment:校验地址" json:"match_address"`
|
||||
AddressLocked bool `gorm:"column:address_locked;not null;default:false;comment:地址锁定 1:独占 0:共享" json:"address_locked"`
|
||||
Status int `gorm:"column:status;not null;default:1;index;index:idx_order_notify_retry,priority:1;index:idx_order_status_trade,priority:1;comment:交易状态" json:"status"`
|
||||
Name string `gorm:"column:name;type:varchar(64);not null;default:'';comment:商品名称" json:"name"`
|
||||
ApiType string `gorm:"column:api_type;type:varchar(20);not null;default:'vupay';comment:API类型" json:"api_type"`
|
||||
ReturnUrl string `gorm:"column:return_url;type:varchar(1024);not null;default:'';comment:同步地址" json:"return_url"`
|
||||
NotifyUrl string `gorm:"column:notify_url;type:varchar(1024);not null;default:'';comment:异步地址" json:"notify_url"`
|
||||
NotifyNum int `gorm:"column:notify_num;not null;default:0;index:idx_order_notify_retry,priority:3;comment:回调次数" json:"notify_num"`
|
||||
NotifyState int `gorm:"column:notify_state;not null;default:0;index:idx_order_notify_retry,priority:2;comment:回调状态 1:成功 0:失败" json:"notify_state"`
|
||||
RefHash string `gorm:"column:ref_hash;type:varchar(128);not null;default:'';index;comment:交易哈希" json:"ref_hash"`
|
||||
RefBlockNum int `gorm:"column:ref_block_num;not null;default:0;comment:区块索引" json:"ref_block_num"`
|
||||
ExpiredAt time.Time `gorm:"column:expired_at;not null;comment:失效时间" json:"expired_at"`
|
||||
ConfirmedAt *time.Time `gorm:"column:confirmed_at;not null;comment:交易确认时间" json:"confirmed_at"`
|
||||
ClientFingerprint string `gorm:"column:client_fingerprint;type:varchar(64);not null;default:'';comment:'客户端指纹'" json:"-"`
|
||||
AutoTimeAt
|
||||
}
|
||||
|
||||
type MethodItem struct {
|
||||
Amount string `json:"amount"`
|
||||
ActualAmount string `json:"actual_amount"`
|
||||
Fiat string `json:"fiat"`
|
||||
ExchangeRate string `json:"exchange_rate"`
|
||||
Currency string `json:"currency"`
|
||||
Network string `json:"network"`
|
||||
TokenNetName string `json:"token_net_name"`
|
||||
TokenCustomName string `json:"token_custom_name"`
|
||||
IsPopular bool `json:"is_popular"`
|
||||
}
|
||||
|
||||
func (o *Order) SetCanceled() error {
|
||||
core.New()
|
||||
o.Status = OrderStatusCanceled
|
||||
|
||||
return Db.Save(o).Error
|
||||
}
|
||||
|
||||
// CanReselectPayment 判断订单是否支持重选交易类型
|
||||
func (o *Order) CanReselectPayment() bool {
|
||||
if o.Status != OrderStatusWaiting {
|
||||
return false
|
||||
}
|
||||
|
||||
if o.ApiType != OrderApiTypeVupayOrder && o.ApiType != OrderApiTypeAdmin {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (o *Order) FingerprintBound() bool {
|
||||
return o.ClientFingerprint != ""
|
||||
}
|
||||
|
||||
func (o *Order) MatchFingerprint(fingerprint string) bool {
|
||||
return !o.FingerprintBound() || o.ClientFingerprint == fingerprint
|
||||
}
|
||||
|
||||
func (o *Order) SetExpired() {
|
||||
o.Status = OrderStatusExpired
|
||||
|
||||
Db.Save(o)
|
||||
}
|
||||
|
||||
func (o *Order) SetSuccess() {
|
||||
o.Status = OrderStatusSuccess
|
||||
|
||||
Db.Save(o)
|
||||
}
|
||||
|
||||
func (o *Order) SetFailed() {
|
||||
o.Status = OrderStatusFailed
|
||||
|
||||
Db.Save(o)
|
||||
}
|
||||
|
||||
func (o *Order) MarkConfirming(blockNum int, from, hash string, at time.Time, amount decimal.Decimal) error {
|
||||
o.FromAddress = from
|
||||
o.ConfirmedAt = &at
|
||||
o.RefHash = hash
|
||||
o.RefBlockNum = blockNum
|
||||
o.Status = OrderStatusConfirming
|
||||
if o.AddressLocked {
|
||||
rate, _ := decimal.NewFromString(o.Rate)
|
||||
o.Amount = amount.String()
|
||||
o.Money = rate.Mul(amount).String()
|
||||
}
|
||||
|
||||
return Db.Save(o).Error
|
||||
}
|
||||
|
||||
func (o *Order) SetNotifyState(state int) error {
|
||||
o.NotifyNum += 1
|
||||
o.NotifyState = state
|
||||
|
||||
return Db.Save(o).Error
|
||||
}
|
||||
|
||||
func (o *Order) GetStatusLabel() string {
|
||||
label := "🟢收款成功"
|
||||
if o.Status == OrderStatusExpired {
|
||||
label = "🔴交易过期"
|
||||
}
|
||||
if o.Status == OrderStatusWaiting {
|
||||
label = "🟡等待支付"
|
||||
}
|
||||
if o.Status == OrderStatusCanceled {
|
||||
label = "⚪️订单取消"
|
||||
}
|
||||
|
||||
return label
|
||||
}
|
||||
|
||||
func (o *Order) GetStatusEmoji() string {
|
||||
label := "🟢"
|
||||
if o.Status == OrderStatusExpired {
|
||||
label = "🔴"
|
||||
}
|
||||
if o.Status == OrderStatusWaiting {
|
||||
label = "🟡"
|
||||
}
|
||||
if o.Status == OrderStatusCanceled {
|
||||
label = "⚪️"
|
||||
}
|
||||
|
||||
return label
|
||||
}
|
||||
|
||||
func (o *Order) GetTxUrl() string {
|
||||
return GetTxUrl(o.TradeType, o.RefHash)
|
||||
}
|
||||
|
||||
func (o *Order) RedirectUrl() string {
|
||||
var redirect = o.ReturnUrl
|
||||
if o.Status == OrderStatusSuccess && o.ApiType == OrderApiTypeEpay {
|
||||
redirect = fmt.Sprintf("%s?%s", redirect, o.BuildNotifyParams())
|
||||
}
|
||||
|
||||
return redirect
|
||||
}
|
||||
|
||||
func (o *Order) BuildNotifyParams() string {
|
||||
var signStr = utils.Md5String(fmt.Sprintf("money=%s&name=%s&out_trade_no=%s&pid=%s&trade_no=%s&trade_status=TRADE_SUCCESS&type=%s",
|
||||
cast.ToString(o.Money), o.Name, o.OrderId, conf.Pid, o.TradeId, o.TradeType) + AuthToken())
|
||||
var params = fmt.Sprintf("money=%s&name=%s&out_trade_no=%s&pid=%s&trade_no=%s&trade_status=TRADE_SUCCESS&type=%s",
|
||||
cast.ToString(o.Money), url.QueryEscape(o.Name), url.QueryEscape(o.OrderId), conf.Pid, o.TradeId, o.TradeType)
|
||||
|
||||
return fmt.Sprintf("%s&sign=%s", params, signStr)
|
||||
}
|
||||
|
||||
func (o *Order) GetMethods(crypto Crypto) []MethodItem {
|
||||
var items = make([]MethodItem, 0)
|
||||
if o.Status != OrderStatusWaiting {
|
||||
return items
|
||||
}
|
||||
if o.TradeType != "" && !o.CanReselectPayment() {
|
||||
return items
|
||||
}
|
||||
|
||||
allTrades := GetAllTradeConfig()
|
||||
|
||||
// 解析限定币种
|
||||
var whitelist = make(map[string]bool)
|
||||
var blacklist = make(map[string]bool)
|
||||
if o.CurrencyLimit != "" {
|
||||
for _, c := range strings.Split(o.CurrencyLimit, ",") {
|
||||
c = strings.TrimSpace(c)
|
||||
if strings.HasPrefix(c, "-") {
|
||||
blacklist[strings.ToUpper(strings.TrimPrefix(c, "-"))] = true
|
||||
} else {
|
||||
whitelist[strings.ToUpper(c)] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for tradeTypeStr, typeConf := range allTrades {
|
||||
// 如果指定了货币,则进行过滤
|
||||
if crypto != "" && typeConf.Crypto != crypto {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check blacklist
|
||||
if len(blacklist) > 0 && blacklist[string(typeConf.Crypto)] {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check whitelist
|
||||
if len(whitelist) > 0 && !whitelist[string(typeConf.Crypto)] {
|
||||
continue
|
||||
}
|
||||
|
||||
// 检查是否有可用钱包
|
||||
count := len(GetAvailableWallets(TradeType(tradeTypeStr)))
|
||||
if count == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// 获取汇率配置的浮动语法
|
||||
syntax := GetK(ConfKey(fmt.Sprintf("rate_float_%s_%s", typeConf.Crypto, o.Fiat)))
|
||||
|
||||
// 获取汇率
|
||||
rate, err := GetOrderRate(typeConf.Crypto, o.Fiat, syntax)
|
||||
if err != nil {
|
||||
log.Error(fmt.Sprintf("GetPaymentMethods: get order rate error: %s", err.Error()))
|
||||
continue
|
||||
}
|
||||
|
||||
// 计算实际支付金额 (加密货币)
|
||||
// Money 是法币金额
|
||||
moneyDecimal, _ := decimal.NewFromString(o.Money)
|
||||
|
||||
// 计算精度
|
||||
atom, precision := GetAtomicity(TradeType(tradeTypeStr))
|
||||
actualAmount := moneyDecimal.DivRound(rate, precision)
|
||||
if actualAmount.LessThan(atom) {
|
||||
actualAmount = atom
|
||||
}
|
||||
|
||||
items = append(items, MethodItem{
|
||||
Amount: o.Money,
|
||||
ActualAmount: actualAmount.String(),
|
||||
Fiat: string(o.Fiat),
|
||||
ExchangeRate: rate.String(),
|
||||
Currency: string(typeConf.Crypto),
|
||||
Network: string(typeConf.Network),
|
||||
TokenNetName: typeConf.NetworkName,
|
||||
TokenCustomName: "", // 暂为空
|
||||
IsPopular: false, // 暂为 false
|
||||
})
|
||||
}
|
||||
|
||||
// Sort by Currency A-Z
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
if items[i].Currency != items[j].Currency {
|
||||
return items[i].Currency < items[j].Currency
|
||||
}
|
||||
return items[i].Network < items[j].Network
|
||||
})
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
func (o *Order) Network() any {
|
||||
type network struct {
|
||||
Alias string `json:"alias"`
|
||||
Name string `json:"name"`
|
||||
Crypto Crypto `json:"crypto"`
|
||||
Network Network `json:"network"`
|
||||
}
|
||||
|
||||
var net = network{}
|
||||
info, ok := registry[o.TradeType]
|
||||
if !ok {
|
||||
return net
|
||||
}
|
||||
|
||||
net.Name = info.NetworkName
|
||||
net.Alias = info.Alias
|
||||
net.Crypto = info.Crypto
|
||||
net.Network = info.Network
|
||||
|
||||
return net
|
||||
}
|
||||
|
||||
func (o *Order) TableName() string {
|
||||
return "vupay_order"
|
||||
}
|
||||
|
||||
func GetTradeOrder(tradeId string) (Order, bool) {
|
||||
var order Order
|
||||
res := Db.Where("trade_id = ?", tradeId).Limit(1).Find(&order)
|
||||
|
||||
return order, res.RowsAffected > 0
|
||||
}
|
||||
|
||||
func GetOrderByStatus(Status int) []Order {
|
||||
orders := make([]Order, 0)
|
||||
|
||||
Db.Where("status = ?", Status).Find(&orders)
|
||||
|
||||
return orders
|
||||
}
|
||||
|
||||
func GetNotifyFailedTradeOrders() ([]Order, error) {
|
||||
var orders []Order
|
||||
maxRetry := cast.ToInt(GetC(NotifyMaxRetry))
|
||||
if maxRetry <= 0 {
|
||||
maxRetry = cast.ToInt(defaultConf[NotifyMaxRetry])
|
||||
}
|
||||
|
||||
res := Db.Where("status = ?", OrderStatusSuccess).
|
||||
Where("notify_state = ?", OrderNotifyStateFail).
|
||||
Where("notify_num <= ?", maxRetry).Find(&orders)
|
||||
|
||||
return orders, res.Error
|
||||
}
|
||||
|
||||
// CalcTradeAmount 计算当前实际可用的交易金额
|
||||
func CalcTradeAmount(wallets []Wallet, rate decimal.Decimal, p OrderParams) (Wallet, string, error) {
|
||||
if p.AddressLocked {
|
||||
return LockTradeAddress(wallets, p.TradeType)
|
||||
}
|
||||
|
||||
var orders []Order
|
||||
lock := make(map[string]bool)
|
||||
status := []int{OrderStatusConfirming, OrderStatusWaiting}
|
||||
Db.Where("status in (?) and trade_type = ?", status, p.TradeType).Find(&orders)
|
||||
for _, order := range orders {
|
||||
lock[order.Address+order.Amount] = true
|
||||
}
|
||||
|
||||
atom, precision := GetAtomicity(p.TradeType)
|
||||
if rate.LessThanOrEqual(decimal.Zero) || precision <= 0 {
|
||||
return Wallet{}, "", errors.New(fmt.Sprintf("[%v - %v]原子颗粒度计算异常,联系管理员处理!", atom, precision))
|
||||
}
|
||||
|
||||
amount := p.Money.DivRound(rate, precision)
|
||||
if amount.LessThan(atom) { // 低于最小原子精度,从最小原子精度开始计算
|
||||
amount = atom
|
||||
}
|
||||
|
||||
var i = 0
|
||||
var m = 100
|
||||
for {
|
||||
for _, w := range wallets {
|
||||
k := w.GetMatchAddr() + amount.String()
|
||||
if _, ok := lock[k]; ok {
|
||||
continue
|
||||
}
|
||||
|
||||
return w, amount.String(), nil
|
||||
}
|
||||
|
||||
// 已经被占用,每次递增一个原子精度
|
||||
amount = amount.Add(atom)
|
||||
if i++; i > m {
|
||||
return Wallet{}, "", errors.New("计算交易金额异常,联系管理员处理!")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LockTradeAddress 检测交易地址,独占使用
|
||||
func LockTradeAddress(wallets []Wallet, t TradeType) (Wallet, string, error) {
|
||||
zero := decimal.Zero.String()
|
||||
status := []int{OrderStatusConfirming, OrderStatusWaiting}
|
||||
for _, w := range wallets {
|
||||
var o Order
|
||||
Db.Where("match_address = ? and status in (?) and trade_type = ? and address_locked = ?", w.GetMatchAddr(), status, t, true).Order("id desc").Limit(1).Find(&o)
|
||||
if o.ID == 0 {
|
||||
return w, zero, nil
|
||||
}
|
||||
}
|
||||
|
||||
return Wallet{}, zero, errors.New("暂无可用钱包地址")
|
||||
}
|
||||
|
||||
// CalcTradeExpiredAt 计算订单过期时间 最小180,最大3600,默认1200
|
||||
func CalcTradeExpiredAt(sec int64) time.Time {
|
||||
if sec >= 180 && sec <= 3600 {
|
||||
return time.Now().Add(time.Duration(sec) * time.Second)
|
||||
}
|
||||
|
||||
return time.Now().Add(time.Duration(cast.ToUint64(GetK(PaymentTimeout))) * time.Second)
|
||||
}
|
||||
|
||||
func GetAtomicity(t TradeType) (decimal.Decimal, int32) {
|
||||
confKey, ok := GetTradeAtomKey(t)
|
||||
if !ok {
|
||||
confKey = "atom_usdt"
|
||||
}
|
||||
|
||||
atom, _ := decimal.NewFromString(GetK(confKey))
|
||||
|
||||
return atom, cast.ToInt32(math.Abs(float64(atom.Exponent())))
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"github.com/shopspring/decimal"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const OrderStatusExpired = 3
|
||||
const OrderStatusSuccess = 2
|
||||
const OrderStatusWaiting = 1
|
||||
|
||||
const OrderNotifyStateSucc = 1
|
||||
const OrderNotifyStateFail = 0
|
||||
const Atomicity = 0.01 // 原子精度
|
||||
|
||||
var _calcMutex sync.Mutex
|
||||
|
||||
type TradeOrders struct {
|
||||
Id int64 `gorm:"primary_key;AUTO_INCREMENT"`
|
||||
OrderId string `gorm:"type:varchar(255);not null;unique"`
|
||||
TradeId string `gorm:"type:varchar(255);not null;unique"`
|
||||
TradeHash string `gorm:"type:varchar(64);default:'';unique"`
|
||||
UsdtRate string `gorm:"type:varchar(10);not null"`
|
||||
Amount string `gorm:"type:decimal(10,2);not null;default:0"`
|
||||
Money float64 `gorm:"type:decimal(10,2);not null;default:0"`
|
||||
Address string `gorm:"type:varchar(34);not null"`
|
||||
FromAddress string `gorm:"type:varchar(34);not null;default:''"`
|
||||
Status int `gorm:"type:tinyint(1);not null;default:0"`
|
||||
ReturnUrl string `gorm:"type:varchar(255);not null;default:''"`
|
||||
NotifyUrl string `gorm:"type:varchar(255);not null;default:''"`
|
||||
NotifyNum int `gorm:"type:int(11);not null;default:0"`
|
||||
NotifyState int `gorm:"type:tinyint(1);not null;default:0"`
|
||||
ExpiredAt time.Time `gorm:"type:timestamp;not null"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime;type:timestamp;not null"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime;type:timestamp;not null"`
|
||||
ConfirmedAt time.Time `gorm:"type:timestamp;null"`
|
||||
}
|
||||
|
||||
func (o *TradeOrders) OrderSetExpired() error {
|
||||
o.Status = OrderStatusExpired
|
||||
|
||||
return DB.Save(o).Error
|
||||
}
|
||||
|
||||
func (o *TradeOrders) OrderSetSucc(fromAddress, tradeHash string, confirmedAt time.Time) error {
|
||||
// 订单标记交易成功
|
||||
o.Status = OrderStatusSuccess
|
||||
o.FromAddress = fromAddress
|
||||
o.ConfirmedAt = confirmedAt
|
||||
o.TradeHash = tradeHash
|
||||
r := DB.Save(o)
|
||||
|
||||
return r.Error
|
||||
}
|
||||
|
||||
func (o *TradeOrders) OrderSetNotifyState(state int) error {
|
||||
o.NotifyNum += 1
|
||||
o.NotifyState = state
|
||||
|
||||
return DB.Save(o).Error
|
||||
}
|
||||
|
||||
func (o *TradeOrders) GetStatusLabel() string {
|
||||
var _label = "🟢 收款成功"
|
||||
if o.Status == OrderStatusExpired {
|
||||
|
||||
_label = "🔴 交易过期"
|
||||
}
|
||||
if o.Status == OrderStatusWaiting {
|
||||
|
||||
_label = "🟡 等待支付"
|
||||
}
|
||||
|
||||
return _label
|
||||
}
|
||||
|
||||
func GetTradeOrder(tradeId string) (TradeOrders, bool) {
|
||||
var order TradeOrders
|
||||
var res = DB.Where("trade_id = ?", tradeId).First(&order)
|
||||
|
||||
return order, res.Error == nil
|
||||
}
|
||||
|
||||
func GetTradeOrderByStatus(Status int) ([]TradeOrders, error) {
|
||||
var orders []TradeOrders
|
||||
var res = DB.Where("status = ?", Status).Find(&orders)
|
||||
|
||||
return orders, res.Error
|
||||
}
|
||||
|
||||
func GetNotifyFailedTradeOrders() ([]TradeOrders, error) {
|
||||
var orders []TradeOrders
|
||||
var res = DB.Where("status = ?", OrderStatusSuccess).Where("notify_num > ?", 0).
|
||||
Where("notify_state = ?", OrderNotifyStateFail).Find(&orders)
|
||||
|
||||
return orders, res.Error
|
||||
}
|
||||
|
||||
// CalcTradeAmount 计算当前实际可用的交易金额
|
||||
func CalcTradeAmount(wa []WalletAddress, rate, money float64) (WalletAddress, string) {
|
||||
_calcMutex.Lock()
|
||||
defer _calcMutex.Unlock()
|
||||
|
||||
var _orders []TradeOrders
|
||||
var _lock = make(map[string]bool)
|
||||
DB.Where("status = ?", OrderStatusWaiting).Find(&_orders)
|
||||
for _, _order := range _orders {
|
||||
|
||||
_lock[_order.Address+_order.Amount] = true
|
||||
}
|
||||
|
||||
var _atom = decimal.NewFromFloat(Atomicity)
|
||||
var payAmount = strconv.FormatFloat(money/rate, 'f', 2, 64)
|
||||
var _payAmount, _ = decimal.NewFromString(payAmount)
|
||||
for {
|
||||
for _, address := range wa {
|
||||
_key := address.Address + _payAmount.String()
|
||||
if _, ok := _lock[_key]; ok {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
return address, _payAmount.String()
|
||||
}
|
||||
|
||||
// 已经被占用,每次递增一个原子精度
|
||||
_payAmount = _payAmount.Add(_atom)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app"
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/tidwall/gjson"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Rate struct {
|
||||
Id
|
||||
Rate string `gorm:"column:rate;type:varchar(32);not null;comment:订单汇率" json:"rate"`
|
||||
Fiat string `gorm:"column:fiat;type:varchar(16);not null;comment:法币" json:"fiat"`
|
||||
Crypto string `gorm:"column:crypto;type:varchar(16);not null;comment:加密货币" json:"crypto"`
|
||||
RawRate float64 `gorm:"column:raw_rate;type:decimal(10,4);not null;comment:基准汇率" json:"raw_rate"`
|
||||
Syntax string `gorm:"column:syntax;type:varchar(32);not null;default:'';comment:浮动语法" json:"syntax"`
|
||||
AutoTimeAt
|
||||
}
|
||||
|
||||
func (r *Rate) TableName() string {
|
||||
return "vupay_rate"
|
||||
}
|
||||
|
||||
func (r *Rate) BeforeCreate(*gorm.DB) error {
|
||||
var syntax = GetK(ConfKey(fmt.Sprintf("rate_float_%s_%s", r.Crypto, r.Fiat)))
|
||||
if syntax == "" {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
r.Syntax = syntax
|
||||
r.Rate = cast.ToString(ParseFloatRate(syntax, cast.ToFloat64(r.RawRate)))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func CoingeckoRate() error {
|
||||
var fiats = make([]string, 0)
|
||||
for k := range supportFiat {
|
||||
fiats = append(fiats, string(k))
|
||||
}
|
||||
|
||||
var ids = make([]string, 0)
|
||||
var tokens = make(map[CoinId]Crypto)
|
||||
for token, id := range supportCrypto {
|
||||
ids = append(ids, string(id))
|
||||
tokens[id] = token
|
||||
}
|
||||
|
||||
var url = fmt.Sprintf("%s/api/v3/simple/price?ids=%s&vs_currencies=%s", GetC(RateSyncCoingeckoApiUrl), strings.Join(ids, ","), strings.Join(fiats, ","))
|
||||
var client = &http.Client{Timeout: 15 * time.Second}
|
||||
|
||||
req, err := http.NewRequest("GET", url, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req.Header.Set("x-cg-demo-api-key", GetC(RateSyncCoingeckoApiKey))
|
||||
req.Header.Set("User-Agent", fmt.Sprintf("VUPAY/%s", app.Version))
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
|
||||
return errors.New("CoingeckoRate: " + http.StatusText(resp.StatusCode))
|
||||
}
|
||||
|
||||
var data = gjson.ParseBytes(body)
|
||||
if data.Get("status.error_code").Exists() {
|
||||
|
||||
return errors.New("CoingeckoRate: " + data.Get("status.error_message").String())
|
||||
}
|
||||
|
||||
var rows = make([]Rate, 0)
|
||||
for id, v := range data.Map() {
|
||||
var token, ok = tokens[CoinId(id)]
|
||||
if !ok {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
for fiat, val := range v.Map() {
|
||||
rows = append(rows, Rate{
|
||||
Rate: val.String(),
|
||||
Fiat: strings.ToUpper(fiat),
|
||||
Crypto: string(token),
|
||||
RawRate: val.Float(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if len(rows) == 0 {
|
||||
|
||||
return errors.New("CoingeckoRate: no data")
|
||||
}
|
||||
|
||||
Db.Create(&rows)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ParseFloatRate(syntax string, rawVal float64) float64 {
|
||||
if syntax == "" {
|
||||
|
||||
return rawVal
|
||||
}
|
||||
|
||||
if utils.IsNumber(syntax) {
|
||||
|
||||
return cast.ToFloat64(syntax)
|
||||
}
|
||||
|
||||
match, err := regexp.MatchString(`^[~+-]\d+(\.\d+)?$`, syntax)
|
||||
if !match || err != nil {
|
||||
log.Error("浮动语法解析错误", err)
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
var act = syntax[0:1]
|
||||
var raw = decimal.NewFromFloat(rawVal)
|
||||
var base = decimal.NewFromFloat(cast.ToFloat64(syntax[1:]))
|
||||
var result float64 = 0
|
||||
|
||||
switch act {
|
||||
case "~":
|
||||
result = raw.Mul(base).InexactFloat64()
|
||||
case "+":
|
||||
result = raw.Add(base).InexactFloat64()
|
||||
case "-":
|
||||
result = raw.Sub(base).InexactFloat64()
|
||||
}
|
||||
|
||||
return round(result, 4) // 保留4位小数
|
||||
}
|
||||
|
||||
func round(val float64, precision int) float64 {
|
||||
// Round 四舍五入,ROUND_HALF_UP 模式实现
|
||||
// 返回将 val 根据指定精度 precision(十进制小数点后数字的数目)进行四舍五入的结果。precision 也可以是负数或零。
|
||||
|
||||
if precision == 0 {
|
||||
return math.Round(val)
|
||||
}
|
||||
|
||||
p := math.Pow10(precision)
|
||||
if precision < 0 {
|
||||
return math.Floor(val*p+0.5) * math.Pow10(-precision)
|
||||
}
|
||||
|
||||
return math.Floor(val*p+0.5) / p
|
||||
}
|
||||
|
||||
func GetOrderRate(token Crypto, fiat Fiat, syntax string) (decimal.Decimal, error) {
|
||||
var r Rate
|
||||
Db.Where("crypto = ? and fiat = ?", token, fiat).Order("created_at desc").Limit(1).Find(&r)
|
||||
if r.ID == 0 {
|
||||
|
||||
return decimal.Decimal{}, fmt.Errorf("创建失败,请检查汇率同步是否正常:%s %s", token, fiat)
|
||||
}
|
||||
|
||||
if syntax == "" {
|
||||
|
||||
return decimal.NewFromString(r.Rate)
|
||||
}
|
||||
|
||||
return decimal.NewFromFloat(ParseFloatRate(syntax, r.RawRate)), nil
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type NotifyRecord struct {
|
||||
Txid string `gorm:"primary_key;type:varchar(64);not null"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime;type:timestamp;not null"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime;type:timestamp;not null"`
|
||||
}
|
||||
|
||||
func (nr *NotifyRecord) TableName() string {
|
||||
|
||||
return "notify_record"
|
||||
}
|
||||
|
||||
func IsNeedNotifyByTxid(txid string) bool {
|
||||
var row NotifyRecord
|
||||
var res = DB.Where("txid = ?", txid).Limit(1).Find(&row)
|
||||
if res.RowsAffected > 0 {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
var row2 TradeOrders
|
||||
var res2 = DB.Where("trade_hash = ?", txid).Limit(1).Find(&row2)
|
||||
if res2.RowsAffected > 0 {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
"github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
// supportFiat 支持的法定货币
|
||||
var supportFiat = map[Fiat]struct{}{
|
||||
CNY: {},
|
||||
USD: {},
|
||||
JPY: {},
|
||||
EUR: {},
|
||||
GBP: {},
|
||||
}
|
||||
|
||||
// supportCrypto 支持的加密货币;Coin Id 参考来源:https://docs.coingecko.com/v3.0.1/reference/coins-list
|
||||
var supportCrypto = map[Crypto]CoinId{
|
||||
USDT: "tether",
|
||||
USDC: "usd-coin",
|
||||
TRX: "tron",
|
||||
BNB: "binancecoin",
|
||||
ETH: "ethereum",
|
||||
GRAM: "the-open-network",
|
||||
}
|
||||
|
||||
// TradeType 交易类型,当下类型开始增多,现在这里统一管理、尽量收缩配置项
|
||||
var registry = map[TradeType]TradeTypeConf{
|
||||
UsdtTon: {
|
||||
Alias: "USDT・Ton",
|
||||
NetworkName: "Ton",
|
||||
Network: conf.Ton,
|
||||
Crypto: USDT,
|
||||
Contract: conf.UsdtTon,
|
||||
Decimal: conf.UsdtTonDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://tonscan.org/tx/%s#overview",
|
||||
EndpointKey: RpcGlobalConfigUrlTon,
|
||||
AddrCaseSens: true,
|
||||
},
|
||||
UsdtPlasma: {
|
||||
Alias: "USDT・Plasma",
|
||||
NetworkName: "Plasma",
|
||||
Network: conf.Plasma,
|
||||
Crypto: USDT,
|
||||
Contract: conf.UsdtPlasma,
|
||||
Decimal: conf.UsdtPlasmaDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://plasmascan.to/tx/%s",
|
||||
EndpointKey: RpcEndpointPlasma,
|
||||
},
|
||||
UsdtTrc20: {
|
||||
Alias: "USDT・TRC20",
|
||||
NetworkName: "Tron",
|
||||
Network: conf.Tron,
|
||||
Crypto: USDT,
|
||||
Contract: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", // 占位,目前实际没使用
|
||||
Decimal: conf.UsdtTronDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://tronscan.org/#/transaction/%s",
|
||||
EndpointKey: RpcEndpointTron,
|
||||
AddrCaseSens: true,
|
||||
},
|
||||
UsdtErc20: {
|
||||
Alias: "USDT・ERC20",
|
||||
NetworkName: "Ethereum",
|
||||
Network: conf.Ethereum,
|
||||
Crypto: USDT,
|
||||
Contract: conf.UsdtErc20,
|
||||
Decimal: conf.UsdtEthDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://etherscan.io/tx/%s",
|
||||
EndpointKey: RpcEndpointEthereum,
|
||||
},
|
||||
UsdtBep20: {
|
||||
Alias: "USDT・BEP20",
|
||||
NetworkName: "Bsc",
|
||||
Network: conf.Bsc,
|
||||
Crypto: USDT,
|
||||
Contract: conf.UsdtBep20,
|
||||
Decimal: conf.UsdtBscDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://bscscan.com/tx/%s",
|
||||
EndpointKey: RpcEndpointBsc,
|
||||
},
|
||||
UsdtAptos: {
|
||||
Alias: "USDT・Aptos",
|
||||
NetworkName: "Aptos",
|
||||
Network: conf.Aptos,
|
||||
Crypto: USDT,
|
||||
Contract: conf.UsdtAptos,
|
||||
Decimal: conf.UsdtAptosDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://explorer.aptoslabs.com/txn/%s",
|
||||
EndpointKey: RpcEndpointAptos,
|
||||
},
|
||||
UsdtXlayer: {
|
||||
Alias: "USDT・X Layer",
|
||||
NetworkName: "X Layer",
|
||||
Network: conf.Xlayer,
|
||||
Crypto: USDT,
|
||||
Contract: conf.UsdtXlayer,
|
||||
Decimal: conf.UsdtXlayerDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://web3.okx.com/zh-hans/explorer/x-layer/tx/%s",
|
||||
EndpointKey: RpcEndpointXlayer,
|
||||
},
|
||||
UsdtSolana: {
|
||||
Alias: "USDT・Solana",
|
||||
NetworkName: "Solana",
|
||||
Network: conf.Solana,
|
||||
Crypto: USDT,
|
||||
Contract: conf.UsdtSolana,
|
||||
Decimal: conf.UsdtSolanaDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://solscan.io/tx/%s",
|
||||
EndpointKey: RpcEndpointSolana,
|
||||
AddrCaseSens: true,
|
||||
},
|
||||
UsdtPolygon: {
|
||||
Alias: "USDT・Polygon",
|
||||
NetworkName: "Polygon",
|
||||
Network: conf.Polygon,
|
||||
Crypto: USDT,
|
||||
Contract: conf.UsdtPolygon,
|
||||
Decimal: conf.UsdtPolygonDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://polygonscan.com/tx/%s",
|
||||
EndpointKey: RpcEndpointPolygon,
|
||||
},
|
||||
UsdtArbitrum: {
|
||||
Alias: "USDT・Arbitrum",
|
||||
NetworkName: "Arbitrum",
|
||||
Network: conf.Arbitrum,
|
||||
Crypto: USDT,
|
||||
Contract: conf.UsdtArbitrum,
|
||||
Decimal: conf.UsdtArbitrumDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://arbiscan.io/tx/%s",
|
||||
EndpointKey: RpcEndpointArbitrum,
|
||||
},
|
||||
UsdcErc20: {
|
||||
Alias: "USDC・ERC20",
|
||||
NetworkName: "Ethereum",
|
||||
Network: conf.Ethereum,
|
||||
Crypto: USDC,
|
||||
Contract: conf.UsdcErc20,
|
||||
Decimal: conf.UsdcEthDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://etherscan.io/tx/%s",
|
||||
EndpointKey: RpcEndpointEthereum,
|
||||
},
|
||||
UsdcBep20: {
|
||||
Alias: "USDC・BEP20",
|
||||
NetworkName: "Bsc",
|
||||
Network: conf.Bsc,
|
||||
Crypto: USDC,
|
||||
Contract: conf.UsdcBep20,
|
||||
Decimal: conf.UsdcBscDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://bscscan.com/tx/%s",
|
||||
EndpointKey: RpcEndpointBsc,
|
||||
},
|
||||
UsdcXlayer: {
|
||||
Alias: "USDC・X Layer",
|
||||
NetworkName: "X Layer",
|
||||
Network: conf.Xlayer,
|
||||
Crypto: USDC,
|
||||
Contract: conf.UsdcXlayer,
|
||||
Decimal: conf.UsdcXlayerDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://web3.okx.com/zh-hans/explorer/x-layer/tx/%s",
|
||||
EndpointKey: RpcEndpointXlayer,
|
||||
},
|
||||
UsdcPolygon: {
|
||||
Alias: "USDC・Polygon",
|
||||
NetworkName: "Polygon",
|
||||
Network: conf.Polygon,
|
||||
Crypto: USDC,
|
||||
Contract: conf.UsdcPolygon,
|
||||
Decimal: conf.UsdcPolygonDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://polygonscan.com/tx/%s",
|
||||
EndpointKey: RpcEndpointPolygon,
|
||||
},
|
||||
UsdcArbitrum: {
|
||||
Alias: "USDC・Arbitrum",
|
||||
NetworkName: "Arbitrum",
|
||||
Network: conf.Arbitrum,
|
||||
Crypto: USDC,
|
||||
Contract: conf.UsdcArbitrum,
|
||||
Decimal: conf.UsdcArbitrumDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://arbiscan.io/tx/%s",
|
||||
EndpointKey: RpcEndpointArbitrum,
|
||||
},
|
||||
UsdcBase: {
|
||||
Alias: "USDC・Base",
|
||||
NetworkName: "Base",
|
||||
Network: conf.Base,
|
||||
Crypto: USDC,
|
||||
Contract: conf.UsdcBase,
|
||||
Decimal: conf.UsdcBaseDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://basescan.org/tx/%s",
|
||||
EndpointKey: RpcEndpointBase,
|
||||
},
|
||||
UsdcTrc20: {
|
||||
Alias: "USDC・TRC20",
|
||||
NetworkName: "Tron",
|
||||
Network: conf.Tron,
|
||||
Crypto: USDC,
|
||||
Contract: "TEkxiTehnzSmSe2XqrBj4w32RUN966rdz8", // 占位,目前实际没使用
|
||||
Decimal: conf.UsdcTronDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://tronscan.org/#/transaction/%s",
|
||||
EndpointKey: RpcEndpointTron,
|
||||
AddrCaseSens: true,
|
||||
},
|
||||
UsdcSolana: {
|
||||
Alias: "USDC・Solana",
|
||||
NetworkName: "Solana",
|
||||
Network: conf.Solana,
|
||||
Crypto: USDC,
|
||||
Contract: conf.UsdcSolana,
|
||||
Decimal: conf.UsdcSolanaDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://solscan.io/tx/%s",
|
||||
EndpointKey: RpcEndpointSolana,
|
||||
AddrCaseSens: true,
|
||||
},
|
||||
UsdcAptos: {
|
||||
Alias: "USDC・Aptos",
|
||||
NetworkName: "Aptos",
|
||||
Network: conf.Aptos,
|
||||
Crypto: USDC,
|
||||
Contract: conf.UsdcAptos,
|
||||
Decimal: conf.UsdcAptosDecimals,
|
||||
AmountRange: usdGeneralRange,
|
||||
ExplorerFmt: "https://explorer.aptoslabs.com/txn/%s",
|
||||
EndpointKey: RpcEndpointAptos,
|
||||
},
|
||||
TronTrx: {
|
||||
Alias: "Tron・Trx",
|
||||
NetworkName: "Tron",
|
||||
Network: conf.Tron,
|
||||
Crypto: TRX,
|
||||
Native: true,
|
||||
Decimal: -6,
|
||||
AmountRange: Range{
|
||||
MinAmount: decimal.NewFromFloat(0.1),
|
||||
MaxAmount: decimal.NewFromFloat(1000000),
|
||||
},
|
||||
ExplorerFmt: "https://tronscan.org/#/transaction/%s",
|
||||
EndpointKey: RpcEndpointTron,
|
||||
AddrCaseSens: true,
|
||||
},
|
||||
EthereumEth: {
|
||||
Alias: "Ethereum・Eth",
|
||||
NetworkName: "Ethereum",
|
||||
Network: conf.Ethereum,
|
||||
Crypto: ETH,
|
||||
Native: true,
|
||||
Decimal: conf.EthereumEthDecimals,
|
||||
AmountRange: Range{
|
||||
MinAmount: decimal.NewFromFloat(0.000001),
|
||||
MaxAmount: decimal.NewFromFloat(1000000),
|
||||
},
|
||||
ExplorerFmt: "https://etherscan.io/tx/%s",
|
||||
EndpointKey: RpcEndpointEthereum,
|
||||
},
|
||||
BscBnb: {
|
||||
Alias: "Bsc・Bnb",
|
||||
NetworkName: "Bsc",
|
||||
Network: conf.Bsc,
|
||||
Crypto: BNB,
|
||||
Native: true,
|
||||
Decimal: conf.BscBnbDecimals,
|
||||
AmountRange: Range{
|
||||
MinAmount: decimal.NewFromFloat(0.00001),
|
||||
MaxAmount: decimal.NewFromFloat(1000000),
|
||||
},
|
||||
ExplorerFmt: "https://bscscan.com/tx/%s",
|
||||
EndpointKey: RpcEndpointBsc,
|
||||
},
|
||||
TonGram: {
|
||||
Alias: "Ton・Gram",
|
||||
NetworkName: "Ton",
|
||||
Network: conf.Ton,
|
||||
Crypto: GRAM,
|
||||
Native: true,
|
||||
Decimal: conf.TonTonDecimals,
|
||||
AmountRange: Range{
|
||||
MinAmount: decimal.NewFromFloat(0.00001),
|
||||
MaxAmount: decimal.NewFromFloat(1000000),
|
||||
},
|
||||
ExplorerFmt: "https://tonscan.org/tx/%s#overview",
|
||||
EndpointKey: RpcGlobalConfigUrlTon,
|
||||
AddrCaseSens: true,
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
for t, c := range registry {
|
||||
cryptoAtomKeys[c.Crypto] = ConfKey(fmt.Sprintf("atom_%s", strings.ToLower(string(c.Crypto))))
|
||||
explorerUrlMap[t] = c.ExplorerFmt
|
||||
networkTradesMap[c.Network] = append(networkTradesMap[c.Network], t)
|
||||
networkEndpointMap[c.Network] = c.EndpointKey
|
||||
if c.Contract != "" {
|
||||
contractDecimalMap[c.Contract] = c.Decimal
|
||||
contractTradeMap[c.Contract] = t
|
||||
}
|
||||
if c.AmountRange != (Range{}) {
|
||||
tradeAmountRangeMap[t] = c.AmountRange
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func IsSupportedTradeType(t TradeType) bool {
|
||||
_, ok := registry[t]
|
||||
|
||||
return ok
|
||||
}
|
||||
|
||||
func GetCrypto(t TradeType) (Crypto, error) {
|
||||
if c, ok := registry[t]; ok {
|
||||
return c.Crypto, nil
|
||||
}
|
||||
return "", fmt.Errorf("unsupported trade type: %s", t)
|
||||
}
|
||||
|
||||
func GetAllAlias() map[string]string {
|
||||
var alias = make(map[string]string)
|
||||
|
||||
for t, c := range registry {
|
||||
alias[string(t)] = c.Alias
|
||||
}
|
||||
|
||||
return alias
|
||||
}
|
||||
|
||||
func GetAllNetwork() map[string]string {
|
||||
var networks = make(map[string]string)
|
||||
for _, c := range registry {
|
||||
networks[string(c.Network)] = c.NetworkName
|
||||
}
|
||||
|
||||
return networks
|
||||
}
|
||||
|
||||
func GetAllTradeConfig() map[string]TradeTypeConf {
|
||||
var config = make(map[string]TradeTypeConf)
|
||||
|
||||
for t, c := range registry {
|
||||
config[string(t)] = c
|
||||
}
|
||||
|
||||
return config
|
||||
}
|
||||
|
||||
func GetNetworkTrades(n Network) []TradeType {
|
||||
list, ok := networkTradesMap[n]
|
||||
if !ok {
|
||||
return []TradeType{}
|
||||
}
|
||||
|
||||
return list
|
||||
}
|
||||
|
||||
func GetContractTrade(addr string) (TradeType, bool) {
|
||||
t, ok := contractTradeMap[addr]
|
||||
|
||||
return t, ok
|
||||
}
|
||||
|
||||
func GetContractDecimal(addr string) int32 {
|
||||
if d, ok := contractDecimalMap[addr]; ok {
|
||||
|
||||
return d
|
||||
}
|
||||
|
||||
return -6
|
||||
}
|
||||
|
||||
func GetTxUrl(t TradeType, hash string) string {
|
||||
if url, ok := explorerUrlMap[t]; ok {
|
||||
if url == "" {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf(url, hash)
|
||||
}
|
||||
|
||||
return "https://tronscan.org/#/transaction/" + hash
|
||||
}
|
||||
|
||||
func GetTradeContract(t TradeType) string {
|
||||
c, ok := registry[t]
|
||||
if !ok {
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
return c.Contract
|
||||
}
|
||||
|
||||
func GetTradeDecimal(t TradeType) int32 {
|
||||
c, ok := registry[t]
|
||||
if !ok {
|
||||
|
||||
return -6
|
||||
}
|
||||
|
||||
return c.Decimal
|
||||
}
|
||||
|
||||
func IsAmountValid(t TradeType, d decimal.Decimal) bool {
|
||||
r, ok := tradeAmountRangeMap[t]
|
||||
if !ok {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
if r.MaxAmount.Cmp(d) < 0 {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
if r.MinAmount.Cmp(d) > 0 {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func Endpoint(net Network) string {
|
||||
if endpointKey, ok := networkEndpointMap[net]; ok {
|
||||
return GetC(endpointKey)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetTradeAtomKey(t TradeType) (ConfKey, bool) {
|
||||
if c, ok := registry[t]; ok {
|
||||
atomKey, ok := cryptoAtomKeys[c.Crypto]
|
||||
|
||||
return atomKey, ok
|
||||
}
|
||||
|
||||
return "", false
|
||||
}
|
||||
|
||||
func GetSupportFiat() map[Fiat]struct{} {
|
||||
|
||||
return supportFiat
|
||||
}
|
||||
|
||||
func GetSupportCrypto() map[Crypto]CoinId {
|
||||
|
||||
return supportCrypto
|
||||
}
|
||||
|
||||
func AddrCaseSens(t TradeType) bool {
|
||||
if c, ok := registry[t]; ok {
|
||||
|
||||
return c.AddrCaseSens
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func GetTradeTypeByCurrencyAndNetwork(currency, network string) (TradeType, error) {
|
||||
for t, c := range registry {
|
||||
if string(c.Crypto) == currency && (string(c.Network) == network || c.NetworkName == network) {
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("no matching trade type found for currency %s on network %s", currency, network)
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
type OrderParams struct {
|
||||
Money decimal.Decimal `json:"money"` // 交易金额 (单位:法币)s
|
||||
ApiType string `json:"api_type"` // 支付 API 类型
|
||||
Address string `json:"address"` // 收款地址
|
||||
OrderId string `json:"order_id"` // 商户订单 ID
|
||||
TradeType TradeType `json:"trade_type"` // 交易类型
|
||||
RedirectUrl string `json:"redirect_url"` // 成功跳转地址
|
||||
NotifyUrl string `json:"notify_url"` // 异步通知地址
|
||||
Name string `json:"name"` // 商品名称
|
||||
Timeout int64 `json:"timeout"` // 订单超时时间(秒)
|
||||
Rate string `json:"rate"` // 强制指定汇率
|
||||
Fiat Fiat `json:"fiat"` // 法币类型
|
||||
CurrencyLimit string `json:"currency_limit"` // 限定币种
|
||||
AddressLocked bool `json:"address_locked"` // 地址独占锁定
|
||||
ClientFingerprint string `json:"client_fingerprint"` // 客户端指纹
|
||||
}
|
||||
|
||||
type Addr struct {
|
||||
Address string // 对外前端收款地址
|
||||
MatchAddr string // 对内订单校验地址
|
||||
}
|
||||
|
||||
type Trade struct {
|
||||
Wallet Wallet
|
||||
Crypto Crypto
|
||||
Rate decimal.Decimal
|
||||
Amount string
|
||||
}
|
||||
|
||||
var buildMutex sync.Mutex
|
||||
|
||||
func StartBuildOrder(p OrderParams) (Order, error) {
|
||||
var order Order
|
||||
|
||||
if p.Address != "" {
|
||||
if !utils.IsValidTronAddress(p.Address) &&
|
||||
!utils.IsValidEvmAddress(p.Address) &&
|
||||
!utils.IsValidSolanaAddress(p.Address) &&
|
||||
!utils.IsValidAptosAddress(p.Address) &&
|
||||
!utils.IsValidTonAddress(p.Address) {
|
||||
|
||||
return order, fmt.Errorf("钱包地址格式错误:%s", p.Address)
|
||||
}
|
||||
}
|
||||
if _, ok := registry[p.TradeType]; !ok {
|
||||
return order, fmt.Errorf("不支持的交易类型:%s", p.TradeType)
|
||||
}
|
||||
if _, ok := supportFiat[p.Fiat]; !ok {
|
||||
return order, fmt.Errorf("不支持的法币类型:%s", p.Fiat)
|
||||
}
|
||||
maxAmount := decimal.NewFromFloat(cast.ToFloat64(GetC(PaymentMaxAmount)))
|
||||
minAmount := decimal.NewFromFloat(cast.ToFloat64(GetC(PaymentMinAmount)))
|
||||
if !p.AddressLocked && (p.Money.GreaterThan(maxAmount) || p.Money.LessThan(minAmount)) {
|
||||
return order, fmt.Errorf("交易金额必须在 %s - %s 之间", minAmount.String(), maxAmount.String())
|
||||
}
|
||||
|
||||
Db.Where("order_id = ?", p.OrderId).Order("id desc").Limit(1).Find(&order)
|
||||
if order.Status == OrderStatusSuccess || order.Status == OrderStatusConfirming {
|
||||
return order, nil
|
||||
}
|
||||
|
||||
buildMutex.Lock()
|
||||
defer buildMutex.Unlock()
|
||||
|
||||
Db.Where("order_id = ?", p.OrderId).Order("id desc").Limit(1).Find(&order)
|
||||
if order.Status == OrderStatusSuccess || order.Status == OrderStatusConfirming {
|
||||
return order, nil
|
||||
}
|
||||
if order.Status == OrderStatusWaiting {
|
||||
return RebuildOrder(order, p)
|
||||
}
|
||||
|
||||
data, err := BuildTrade(p)
|
||||
if err != nil {
|
||||
return order, err
|
||||
}
|
||||
|
||||
return BuildOrder(p, data)
|
||||
}
|
||||
|
||||
func BuildOrder(p OrderParams, trade Trade) (Order, error) {
|
||||
tradeId, err := utils.GenerateTradeId()
|
||||
if err != nil {
|
||||
return Order{}, err
|
||||
}
|
||||
|
||||
zero := time.Unix(0, 0)
|
||||
tradeOrder := Order{
|
||||
OrderId: p.OrderId,
|
||||
TradeId: tradeId,
|
||||
RefHash: tradeId,
|
||||
TradeType: p.TradeType,
|
||||
Rate: fmt.Sprintf("%v", trade.Rate),
|
||||
Amount: trade.Amount,
|
||||
Money: p.Money.String(),
|
||||
Address: trade.Wallet.GetPaymentAddr(),
|
||||
MatchAddress: trade.Wallet.GetMatchAddr(),
|
||||
AddressLocked: p.Money.IsZero(), // 零值订单,地址锁定 独占
|
||||
Status: OrderStatusWaiting,
|
||||
Name: p.Name,
|
||||
ApiType: p.ApiType,
|
||||
ReturnUrl: p.RedirectUrl,
|
||||
NotifyUrl: p.NotifyUrl,
|
||||
NotifyNum: 0,
|
||||
NotifyState: OrderNotifyStateFail,
|
||||
ExpiredAt: CalcTradeExpiredAt(p.Timeout),
|
||||
Fiat: p.Fiat,
|
||||
Crypto: trade.Crypto,
|
||||
CurrencyLimit: p.CurrencyLimit,
|
||||
ConfirmedAt: &zero, // 默认填充一个0值时间,尽量避免数据库出现允许 NULL 值存在
|
||||
}
|
||||
|
||||
if tradeOrder.Name == "" {
|
||||
tradeOrder.Name = tradeOrder.OrderId
|
||||
}
|
||||
if err = Db.Create(&tradeOrder).Error; err != nil {
|
||||
log.Error("订单创建失败:", err.Error())
|
||||
return Order{}, err
|
||||
}
|
||||
|
||||
return tradeOrder, nil
|
||||
}
|
||||
|
||||
func BuildTrade(p OrderParams) (Trade, error) {
|
||||
// 获取代币类型
|
||||
crypto, err := GetCrypto(p.TradeType)
|
||||
if err != nil {
|
||||
return Trade{}, fmt.Errorf("代币类型(%s)不支持:%v", p.TradeType, err)
|
||||
}
|
||||
|
||||
// 获取订单汇率
|
||||
rate, err := GetOrderRate(crypto, p.Fiat, p.Rate)
|
||||
if err != nil {
|
||||
return Trade{}, err
|
||||
}
|
||||
if rate.LessThanOrEqual(decimal.Zero) {
|
||||
return Trade{}, fmt.Errorf("%s %s 汇率异常", crypto, p.Fiat)
|
||||
}
|
||||
|
||||
var wallets = GetAvailableWallets(p.TradeType)
|
||||
if p.Address != "" { // 指定地址
|
||||
w, err := NewWallet(p.Address, p.TradeType)
|
||||
if err != nil {
|
||||
return Trade{}, err
|
||||
}
|
||||
|
||||
wallets = []Wallet{w}
|
||||
}
|
||||
|
||||
if len(wallets) == 0 {
|
||||
return Trade{}, fmt.Errorf("%s 未检测到可用钱包地址", p.TradeType)
|
||||
}
|
||||
|
||||
// 计算交易金额
|
||||
wallet, amount, err := CalcTradeAmount(wallets, rate, p)
|
||||
if err != nil {
|
||||
|
||||
return Trade{}, err
|
||||
}
|
||||
|
||||
return Trade{
|
||||
Crypto: crypto,
|
||||
Rate: rate,
|
||||
Wallet: wallet,
|
||||
Amount: amount,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func RebuildOrder(t Order, p OrderParams) (Order, error) {
|
||||
if p.OrderId == t.OrderId && p.TradeType == t.TradeType && p.Money.String() == t.Money && p.Fiat == t.Fiat {
|
||||
return t, nil
|
||||
}
|
||||
|
||||
data, err := BuildTrade(p)
|
||||
if err != nil {
|
||||
return t, err
|
||||
}
|
||||
|
||||
if t.TradeType == "" && p.ClientFingerprint != "" {
|
||||
t.ClientFingerprint = p.ClientFingerprint
|
||||
}
|
||||
|
||||
t.Fiat = p.Fiat
|
||||
t.Address = data.Wallet.GetPaymentAddr()
|
||||
t.MatchAddress = data.Wallet.GetMatchAddr()
|
||||
t.Crypto = data.Crypto
|
||||
t.Amount = data.Amount
|
||||
t.Money = p.Money.String()
|
||||
t.TradeType = p.TradeType
|
||||
t.Rate = fmt.Sprintf("%v", data.Rate)
|
||||
t.ExpiredAt = CalcTradeExpiredAt(p.Timeout)
|
||||
|
||||
query := Db.Model(&Order{}).Where("id = ?", t.ID)
|
||||
if p.ClientFingerprint != "" {
|
||||
query = query.Where("(client_fingerprint = '' OR client_fingerprint = ?)", p.ClientFingerprint)
|
||||
}
|
||||
|
||||
res := query.Updates(map[string]any{
|
||||
"fiat": t.Fiat,
|
||||
"address": t.Address,
|
||||
"match_address": t.MatchAddress,
|
||||
"crypto": t.Crypto,
|
||||
"amount": t.Amount,
|
||||
"money": t.Money,
|
||||
"trade_type": t.TradeType,
|
||||
"rate": t.Rate,
|
||||
"expired_at": t.ExpiredAt,
|
||||
"client_fingerprint": t.ClientFingerprint,
|
||||
})
|
||||
if res.Error != nil {
|
||||
return t, res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return t, fmt.Errorf("client fingerprint mismatch")
|
||||
}
|
||||
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// BuildPendingOrder 创建待支付订单(不锁定地址和汇率)
|
||||
func BuildPendingOrder(p OrderParams) (Order, error) {
|
||||
var order Order
|
||||
|
||||
maxAmount := decimal.NewFromFloat(cast.ToFloat64(GetC(PaymentMaxAmount)))
|
||||
minAmount := decimal.NewFromFloat(cast.ToFloat64(GetC(PaymentMinAmount)))
|
||||
if !p.Money.IsZero() && (p.Money.GreaterThan(maxAmount) || p.Money.LessThan(minAmount)) {
|
||||
return order, fmt.Errorf("交易金额必须在 %s - %s 之间", minAmount.String(), maxAmount.String())
|
||||
}
|
||||
|
||||
Db.Where("order_id = ?", p.OrderId).Order("id desc").Limit(1).Find(&order)
|
||||
if order.Status == OrderStatusSuccess || order.Status == OrderStatusConfirming || order.Status == OrderStatusWaiting {
|
||||
return order, nil
|
||||
}
|
||||
|
||||
// 默认使用 USDT
|
||||
crypto := USDT
|
||||
if p.TradeType != "" {
|
||||
c, err := GetCrypto(p.TradeType)
|
||||
if err == nil {
|
||||
crypto = c
|
||||
}
|
||||
} else if p.CurrencyLimit != "" { // 如果指定了唯一的币种限制,且不是黑名单模式,则使用该币种
|
||||
cur := strings.ToUpper(p.CurrencyLimit)
|
||||
if !strings.Contains(cur, ",") && !strings.HasPrefix(cur, "-") {
|
||||
crypto = Crypto(cur)
|
||||
}
|
||||
}
|
||||
|
||||
return BuildOrder(p, Trade{
|
||||
Crypto: crypto,
|
||||
Rate: decimal.Zero,
|
||||
Amount: "0",
|
||||
Wallet: Wallet{},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/v03413/tronprotocol/core"
|
||||
)
|
||||
|
||||
type TronTransfer struct {
|
||||
Network string
|
||||
TxHash string
|
||||
Amount decimal.Decimal
|
||||
FromAddress string
|
||||
RecvAddress string
|
||||
Timestamp time.Time
|
||||
TradeType TradeType
|
||||
BlockNum int
|
||||
}
|
||||
|
||||
type TronResource struct {
|
||||
ID string
|
||||
Type core.Transaction_Contract_ContractType
|
||||
Balance int64
|
||||
FromAddress string
|
||||
RecvAddress string
|
||||
Timestamp time.Time
|
||||
ResourceCode core.ResourceCode
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/xssnick/tonutils-go/address"
|
||||
)
|
||||
|
||||
const (
|
||||
WaStatusEnable uint8 = 1
|
||||
WaStatusDisable uint8 = 0
|
||||
WaOtherEnable uint8 = 1
|
||||
WaOtherDisable uint8 = 0
|
||||
)
|
||||
|
||||
type Wallet struct {
|
||||
Id
|
||||
Name string `gorm:"column:name;type:varchar(32);not null;default:-';comment:名称" json:"name"`
|
||||
Status uint8 `gorm:"column:status;not null;default:1;comment:地址状态" json:"status"`
|
||||
Address string `gorm:"column:address;type:varchar(128);not null;index;comment:钱包地址" json:"address"`
|
||||
MatchAddr string `gorm:"column:match_addr;type:varchar(128);not null;uniqueIndex:idx_address;comment:匹配地址" json:"match_addr"`
|
||||
TradeType string `gorm:"column:trade_type;type:varchar(20);not null;uniqueIndex:idx_address;comment:交易类型" json:"trade_type"`
|
||||
OtherNotify uint8 `gorm:"column:other_notify;not null;default:0;comment:其它通知" json:"other_notify"`
|
||||
Remark string `gorm:"column:remark;type:varchar(255);not null;default:'';comment:备注" json:"remark"`
|
||||
AutoTimeAt
|
||||
}
|
||||
|
||||
func (wa *Wallet) TableName() string {
|
||||
|
||||
return "vupay_wallet"
|
||||
}
|
||||
|
||||
func (wa *Wallet) SetStatus(status uint8) {
|
||||
wa.Status = status
|
||||
Db.Save(wa)
|
||||
}
|
||||
|
||||
func (wa *Wallet) Validate() error {
|
||||
tradeType := TradeType(wa.TradeType)
|
||||
wa.MatchAddr = wa.Address
|
||||
|
||||
switch tradeType {
|
||||
case TronTrx, UsdtTrc20, UsdcTrc20:
|
||||
if !utils.IsValidTronAddress(wa.Address) {
|
||||
return errors.New("钱包地址格式不合法,请检查")
|
||||
}
|
||||
case UsdtSolana, UsdcSolana:
|
||||
if !utils.IsValidSolanaAddress(wa.Address) {
|
||||
return errors.New("钱包地址格式不合法,请检查")
|
||||
}
|
||||
case UsdtAptos, UsdcAptos:
|
||||
if !utils.IsValidAptosAddress(wa.Address) {
|
||||
return errors.New("钱包地址格式不合法,请检查")
|
||||
}
|
||||
case UsdtTon:
|
||||
if !utils.IsValidTonAddress(wa.Address) {
|
||||
return errors.New("TON 地址必须以 UQ 开头")
|
||||
}
|
||||
owner, err := address.ParseAddr(wa.Address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
addr, err := utils.GetJettonWalletAddr(utils.NewTonClient(GetC(RpcGlobalConfigUrlTon)), address.MustParseAddr(conf.UsdtTon), owner)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
wa.MatchAddr = addr.Bounce(false).String()
|
||||
return nil
|
||||
case TonGram:
|
||||
if !utils.IsValidTonAddress(wa.Address) {
|
||||
return errors.New("TON 地址必须以 UQ 开头")
|
||||
}
|
||||
owner, err := address.ParseAddr(wa.Address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
wa.MatchAddr = owner.Bounce(false).String()
|
||||
return nil
|
||||
default:
|
||||
if !utils.IsValidEvmAddress(wa.Address) {
|
||||
return errors.New("钱包地址格式不合法,请检查")
|
||||
}
|
||||
}
|
||||
|
||||
if !AddrCaseSens(tradeType) {
|
||||
wa.MatchAddr = strings.ToLower(wa.Address)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (wa *Wallet) SetOtherNotify(notify uint8) {
|
||||
wa.OtherNotify = notify
|
||||
|
||||
Db.Save(wa)
|
||||
}
|
||||
|
||||
func (wa *Wallet) Delete() {
|
||||
Db.Delete(wa)
|
||||
}
|
||||
|
||||
func (wa *Wallet) GetTokenContract() string {
|
||||
if c, ok := registry[TradeType(wa.TradeType)]; ok {
|
||||
|
||||
return c.Contract
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func (wa *Wallet) GetTokenDecimals() int32 {
|
||||
if c, ok := registry[TradeType(wa.TradeType)]; ok {
|
||||
|
||||
return c.Decimal
|
||||
}
|
||||
|
||||
return -18
|
||||
}
|
||||
|
||||
func (wa *Wallet) GetNetwork() Network {
|
||||
if c, ok := registry[TradeType(wa.TradeType)]; ok {
|
||||
|
||||
return c.Network
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func (wa *Wallet) GetPaymentAddr() string {
|
||||
if wa.TradeType == string(UsdtTon) {
|
||||
|
||||
return wa.Address
|
||||
}
|
||||
|
||||
return wa.MatchAddr
|
||||
}
|
||||
|
||||
func (wa *Wallet) GetMatchAddr() string {
|
||||
return wa.MatchAddr
|
||||
}
|
||||
|
||||
func GetAvailableWallets(t TradeType) []Wallet {
|
||||
var wallets = make([]Wallet, 0)
|
||||
|
||||
Db.Where("trade_type = ? and status = ?", t, WaStatusEnable).Find(&wallets)
|
||||
|
||||
return wallets
|
||||
}
|
||||
|
||||
func NewWallet(address string, tradeType TradeType) (Wallet, error) {
|
||||
wa := Wallet{Address: address, TradeType: string(tradeType)}
|
||||
if err := wa.Validate(); err != nil {
|
||||
return Wallet{}, err
|
||||
}
|
||||
|
||||
return wa, nil
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package monitor
|
||||
|
||||
import (
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/notify"
|
||||
"math"
|
||||
"time"
|
||||
)
|
||||
|
||||
func NotifyStart() {
|
||||
log.Info("回调监控启动.")
|
||||
for range time.Tick(time.Second * 5) {
|
||||
tradeOrders, err := model.GetNotifyFailedTradeOrders()
|
||||
if err != nil {
|
||||
log.Error("待回调订单获取失败", err)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
for _, order := range tradeOrders {
|
||||
// 判断是否到达下次回调时间
|
||||
// 下次回调时间等于 3的失败次数次方 * 1分钟 + 交易确认时间
|
||||
var _nextNotifyTime = order.ConfirmedAt.Add(time.Minute * time.Duration(math.Pow(3, float64(order.NotifyNum))))
|
||||
if time.Now().Unix() >= _nextNotifyTime.Unix() {
|
||||
// 到达下次回调时间
|
||||
|
||||
go notify.OrderNotify(order)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package monitor
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/usdt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// OkxUsdtRateStart Okx USDT 汇率监控,避免频繁请求
|
||||
func OkxUsdtRateStart() {
|
||||
var _act, _value, _defaultRate = config.GetUsdtRate()
|
||||
for {
|
||||
if _act == "" {
|
||||
usdt.SetLatestRate(_defaultRate)
|
||||
|
||||
log.Info("固定汇率", usdt.GetLatestRate())
|
||||
} else {
|
||||
_okxRate, _okxErr := getOkxUsdtCnySellPrice()
|
||||
if _okxErr == nil { // 获取成功
|
||||
usdt.SetOkxLatestRate(_okxRate.InexactFloat64())
|
||||
|
||||
switch _act {
|
||||
case "~":
|
||||
usdt.SetLatestRate(_okxRate.Mul(_value).InexactFloat64())
|
||||
case "+":
|
||||
usdt.SetLatestRate(_okxRate.Add(_value).InexactFloat64())
|
||||
case "-":
|
||||
usdt.SetLatestRate(_okxRate.Sub(_value).InexactFloat64())
|
||||
default:
|
||||
usdt.SetLatestRate(_okxRate.InexactFloat64())
|
||||
}
|
||||
|
||||
log.Info(fmt.Sprintf("okx rate: %v act(%v) value(%v) 最终实际汇率:%v", _okxRate, _act, _value, usdt.GetLatestRate()))
|
||||
}
|
||||
}
|
||||
|
||||
time.Sleep(time.Minute)
|
||||
}
|
||||
}
|
||||
|
||||
// getOkxUsdtCnySellPrice Okx C2C快捷交易 USDT出售 实时汇率
|
||||
func getOkxUsdtCnySellPrice() (decimal.Decimal, error) {
|
||||
var _zero = decimal.NewFromInt(0)
|
||||
var t = strconv.Itoa(int(time.Now().Unix()))
|
||||
var okxApi = "https://www.okx.com/v4/c2c/express/price?crypto=USDT&fiat=CNY&side=sell&t=" + t
|
||||
client := http.Client{Timeout: time.Second * 5}
|
||||
req, _ := http.NewRequest("GET", okxApi, nil)
|
||||
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
|
||||
return _zero, errors.New("okx resp error:" + err.Error())
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
|
||||
return _zero, errors.New("okx resp status code:" + strconv.Itoa(resp.StatusCode))
|
||||
}
|
||||
|
||||
all, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
|
||||
return _zero, errors.New("okx resp read error:" + err.Error())
|
||||
}
|
||||
|
||||
result := gjson.ParseBytes(all)
|
||||
if result.Get("error_code").Int() != 0 {
|
||||
|
||||
return _zero, errors.New("json parse error:" + result.Get("error_message").String())
|
||||
}
|
||||
|
||||
if result.Get("data.price").Exists() {
|
||||
var _ret = result.Get("data.price").Float()
|
||||
if _ret <= 0 {
|
||||
return _zero, errors.New("okx resp json data.price <= 0")
|
||||
}
|
||||
|
||||
return decimal.NewFromFloat(_ret), nil
|
||||
}
|
||||
|
||||
return _zero, errors.New("okx resp json data.price not found")
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package monitor
|
||||
|
||||
import (
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/telegram"
|
||||
)
|
||||
|
||||
var err error
|
||||
|
||||
func BotStart(version string) {
|
||||
var BotApi = telegram.GetBotApi()
|
||||
if BotApi == nil {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
u := tgbotapi.NewUpdate(0)
|
||||
u.Timeout = 60
|
||||
updates := BotApi.GetUpdatesChan(u)
|
||||
if err != nil {
|
||||
log.Error("TG Bot GetUpdatesChan Error:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
telegram.SendWelcome(version)
|
||||
|
||||
// 监听消息
|
||||
for _u := range updates {
|
||||
if _u.Message != nil {
|
||||
if !_u.FromChat().IsPrivate() {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
telegram.HandleMessage(_u.Message)
|
||||
}
|
||||
if _u.CallbackQuery != nil {
|
||||
|
||||
telegram.HandleCallback(_u.CallbackQuery)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,398 +0,0 @@
|
||||
package monitor
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/notify"
|
||||
"github.com/v03413/bepusdt/app/telegram"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
const usdtToken = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
|
||||
|
||||
func TradeStart() {
|
||||
log.Info("交易监控启动.")
|
||||
|
||||
for range time.Tick(time.Second * 5) {
|
||||
var recentTransferTotal float64
|
||||
var _lock, err = getAllPendingOrders()
|
||||
if err != nil {
|
||||
log.Error(err.Error())
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
for _, _row := range model.GetAvailableAddress() {
|
||||
var result gjson.Result
|
||||
var err error
|
||||
|
||||
if config.IsTronScanApi() {
|
||||
result, err = getUsdtTrc20TransByTronScan(_row.Address)
|
||||
} else {
|
||||
result, err = getUsdtTrc20TransByTronGrid(_row.Address)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
log.Error(err.Error())
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if config.IsTronScanApi() {
|
||||
recentTransferTotal = result.Get("total").Num
|
||||
} else {
|
||||
recentTransferTotal = result.Get("meta.page_size").Num
|
||||
}
|
||||
|
||||
log.Info(fmt.Sprintf("[%s] recent transfer total: %s(%v)", config.GetTronServerApi(), _row.Address, recentTransferTotal))
|
||||
if recentTransferTotal <= 0 { // 没有交易记录
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if config.IsTronScanApi() {
|
||||
handlePaymentTransactionForTronScan(_lock, _row.Address, result)
|
||||
handleOtherNotifyForTronScan(_row.Address, result)
|
||||
} else {
|
||||
handlePaymentTransactionForTronGrid(_lock, _row.Address, result)
|
||||
handleOtherNotifyForTronGrid(_row.Address, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 列出所有等待支付的交易订单
|
||||
func getAllPendingOrders() (map[string]model.TradeOrders, error) {
|
||||
tradeOrders, err := model.GetTradeOrderByStatus(model.OrderStatusWaiting)
|
||||
if err != nil {
|
||||
|
||||
return nil, fmt.Errorf("待支付订单获取失败: %w", err)
|
||||
}
|
||||
|
||||
var _lock = make(map[string]model.TradeOrders) // 当前所有正在等待支付的订单 Lock Key
|
||||
for _, order := range tradeOrders {
|
||||
if time.Now().Unix() >= order.ExpiredAt.Unix() { // 订单过期
|
||||
err := order.OrderSetExpired()
|
||||
if err != nil {
|
||||
log.Error("订单过期标记失败:", err, order.OrderId)
|
||||
} else {
|
||||
log.Info("订单过期:", order.OrderId)
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
_lock[order.Address+order.Amount] = order
|
||||
}
|
||||
|
||||
return _lock, nil
|
||||
}
|
||||
|
||||
// 处理支付交易 TronScan
|
||||
func handlePaymentTransactionForTronScan(_lock map[string]model.TradeOrders, _toAddress string, _data gjson.Result) {
|
||||
for _, transfer := range _data.Get("token_transfers").Array() {
|
||||
if transfer.Get("to_address").String() != _toAddress {
|
||||
// 不是接收地址
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 计算交易金额
|
||||
var _quant = parseTransAmount(transfer.Get("quant").Float())
|
||||
|
||||
_order, ok := _lock[_toAddress+_quant]
|
||||
if !ok || transfer.Get("contractRet").String() != "SUCCESS" {
|
||||
// 订单不存在或交易失败
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 判断时间是否有效
|
||||
var _createdAt = time.UnixMilli(transfer.Get("block_ts").Int())
|
||||
if _createdAt.Unix() < _order.CreatedAt.Unix() || _createdAt.Unix() > _order.ExpiredAt.Unix() {
|
||||
// 失效交易
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var _transId = transfer.Get("transaction_id").String()
|
||||
var _fromAddress = transfer.Get("from_address").String()
|
||||
if _order.OrderSetSucc(_fromAddress, _transId, _createdAt) == nil {
|
||||
// 通知订单支付成功
|
||||
go notify.OrderNotify(_order)
|
||||
|
||||
// TG发送订单信息
|
||||
go telegram.SendTradeSuccMsg(_order)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 处理支付交易 TronGrid
|
||||
func handlePaymentTransactionForTronGrid(_lock map[string]model.TradeOrders, _toAddress string, result gjson.Result) {
|
||||
for _, transfer := range result.Get("data").Array() {
|
||||
if transfer.Get("to").String() != _toAddress {
|
||||
// 不是接收地址
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 计算交易金额
|
||||
var _quant = parseTransAmount(transfer.Get("value").Float())
|
||||
_order, ok := _lock[_toAddress+_quant]
|
||||
if !ok || transfer.Get("type").String() != "Transfer" {
|
||||
// 订单不存在或交易失败
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 判断时间是否有效
|
||||
var _createdAt = time.UnixMilli(transfer.Get("block_timestamp").Int())
|
||||
if _createdAt.Unix() < _order.CreatedAt.Unix() || _createdAt.Unix() > _order.ExpiredAt.Unix() {
|
||||
// 失效交易
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var _transId = transfer.Get("transaction_id").String()
|
||||
var _fromAddress = transfer.Get("from").String()
|
||||
if _order.OrderSetSucc(_fromAddress, _transId, _createdAt) == nil {
|
||||
// 通知订单支付成功
|
||||
go notify.OrderNotify(_order)
|
||||
|
||||
// TG发送订单信息
|
||||
go telegram.SendTradeSuccMsg(_order)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 非订单交易通知
|
||||
func handleOtherNotifyForTronScan(_toAddress string, result gjson.Result) {
|
||||
for _, transfer := range result.Get("token_transfers").Array() {
|
||||
if !model.GetOtherNotify(_toAddress) {
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
var _amount = parseTransAmount(transfer.Get("quant").Float())
|
||||
var _created = time.UnixMilli(transfer.Get("block_ts").Int())
|
||||
var _txid = transfer.Get("transaction_id").String()
|
||||
var _detailUrl = "https://tronscan.org/#/transaction/" + _txid
|
||||
if !model.IsNeedNotifyByTxid(_txid) {
|
||||
// 不需要额外通知
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var title = "收入"
|
||||
if transfer.Get("to_address").String() != _toAddress {
|
||||
title = "支出"
|
||||
}
|
||||
|
||||
var text = fmt.Sprintf(
|
||||
"#账户%s #非订单交易\n---\n```\n💲交易数额:%v USDT.TRC20\n⏱️交易时间:%v\n✅接收地址:%v\n🅾️发送地址:%v```\n",
|
||||
title,
|
||||
_amount,
|
||||
_created.Format(time.DateTime),
|
||||
help.MaskAddress(transfer.Get("to_address").String()),
|
||||
help.MaskAddress(transfer.Get("from_address").String()),
|
||||
)
|
||||
|
||||
var chatId, err = strconv.ParseInt(config.GetTgBotNotifyTarget(), 10, 64)
|
||||
if err != nil {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var msg = tgbotapi.NewMessage(chatId, text)
|
||||
msg.ParseMode = tgbotapi.ModeMarkdown
|
||||
msg.ReplyMarkup = tgbotapi.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]tgbotapi.InlineKeyboardButton{
|
||||
{
|
||||
tgbotapi.NewInlineKeyboardButtonURL("📝查看交易明细", _detailUrl),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
var _record = model.NotifyRecord{Txid: _txid}
|
||||
model.DB.Create(&_record)
|
||||
|
||||
go telegram.SendMsg(msg)
|
||||
}
|
||||
}
|
||||
|
||||
func handleOtherNotifyForTronGrid(_toAddress string, result gjson.Result) {
|
||||
for _, transfer := range result.Get("data").Array() {
|
||||
if !model.GetOtherNotify(_toAddress) {
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
var _amount = parseTransAmount(transfer.Get("value").Float())
|
||||
var _created = time.UnixMilli(transfer.Get("block_timestamp").Int())
|
||||
var _txid = transfer.Get("transaction_id").String()
|
||||
var _detailUrl = "https://tronscan.org/#/transaction/" + _txid
|
||||
if !model.IsNeedNotifyByTxid(_txid) {
|
||||
// 不需要额外通知
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var title = "收入"
|
||||
if transfer.Get("to").String() != _toAddress {
|
||||
title = "支出"
|
||||
}
|
||||
|
||||
var text = fmt.Sprintf(
|
||||
"#账户%s #非订单交易\n---\n```\n💲交易数额:%v USDT.TRC20\n⏱️交易时间:%v\n✅接收地址:%v\n🅾️发送地址:%v```\n",
|
||||
title,
|
||||
_amount,
|
||||
_created.Format(time.DateTime),
|
||||
help.MaskAddress(transfer.Get("to").String()),
|
||||
help.MaskAddress(transfer.Get("from").String()),
|
||||
)
|
||||
|
||||
var chatId, err = strconv.ParseInt(config.GetTgBotNotifyTarget(), 10, 64)
|
||||
if err != nil {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var msg = tgbotapi.NewMessage(chatId, text)
|
||||
msg.ParseMode = tgbotapi.ModeMarkdown
|
||||
msg.ReplyMarkup = tgbotapi.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]tgbotapi.InlineKeyboardButton{
|
||||
{
|
||||
tgbotapi.NewInlineKeyboardButtonURL("📝查看交易明细", _detailUrl),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
var _record = model.NotifyRecord{Txid: _txid}
|
||||
model.DB.Create(&_record)
|
||||
|
||||
go telegram.SendMsg(msg)
|
||||
}
|
||||
}
|
||||
|
||||
// 搜索交易记录 TronScan
|
||||
func getUsdtTrc20TransByTronScan(_toAddress string) (gjson.Result, error) {
|
||||
var now = time.Now()
|
||||
var client = &http.Client{Timeout: time.Second * 15}
|
||||
req, err := http.NewRequest("GET", "https://apilist.tronscanapi.com/api/new/token_trc20/transfers", nil)
|
||||
if err != nil {
|
||||
|
||||
return gjson.Result{}, fmt.Errorf("处理请求创建错误: %w", err)
|
||||
}
|
||||
|
||||
// 构建请求参数
|
||||
var params = url.Values{}
|
||||
params.Add("start", "0")
|
||||
params.Add("limit", "30")
|
||||
params.Add("contract_address", usdtToken)
|
||||
params.Add("start_timestamp", strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10)) // 当前时间向前推 1 小时
|
||||
params.Add("end_timestamp", strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)) // 当前时间向后推 1 小时
|
||||
params.Add("relatedAddress", _toAddress)
|
||||
if config.GetTradeConfirmed() {
|
||||
params.Add("confirm", "true")
|
||||
} else {
|
||||
params.Add("confirm", "false")
|
||||
}
|
||||
req.URL.RawQuery = params.Encode()
|
||||
|
||||
if config.GetTronScanApiKey() != "" {
|
||||
|
||||
req.Header.Add("TRON-PRO-API-KEY", config.GetTronScanApiKey())
|
||||
}
|
||||
|
||||
// 请求交易记录
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
|
||||
return gjson.Result{}, fmt.Errorf("请求交易记录错误: %w", err)
|
||||
}
|
||||
|
||||
// 获取响应记录
|
||||
all, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
|
||||
return gjson.Result{}, fmt.Errorf("读取交易记录错误: %w", err)
|
||||
}
|
||||
|
||||
// 释放响应请求
|
||||
_ = resp.Body.Close()
|
||||
|
||||
// 解析响应记录
|
||||
return gjson.ParseBytes(all), nil
|
||||
}
|
||||
|
||||
// 搜索交易记录 TronGrid
|
||||
func getUsdtTrc20TransByTronGrid(_toAddress string) (gjson.Result, error) {
|
||||
var now = time.Now()
|
||||
var client = &http.Client{Timeout: time.Second * 15}
|
||||
req, err := http.NewRequest("GET", fmt.Sprintf("https://api.trongrid.io/v1/accounts/%s/transactions/trc20", _toAddress), nil)
|
||||
if err != nil {
|
||||
|
||||
return gjson.Result{}, fmt.Errorf("处理请求创建错误: %w", err)
|
||||
}
|
||||
|
||||
// 构建请求参数
|
||||
var params = url.Values{}
|
||||
params.Add("limit", "30")
|
||||
params.Add("contract_address", usdtToken)
|
||||
params.Add("min_timestamp", strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10)) // 当前时间向前推 3 小时
|
||||
params.Add("max_timestamp", strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)) // 当前时间向后推 1 小时
|
||||
params.Add("order_by", "block_timestamp,desc")
|
||||
if config.GetTradeConfirmed() {
|
||||
params.Add("only_confirmed", "true")
|
||||
} else {
|
||||
params.Add("only_confirmed", "false")
|
||||
}
|
||||
if config.GetTronGridApiKey() != "" {
|
||||
|
||||
req.Header.Add("TRON-PRO-API-KEY", config.GetTronGridApiKey())
|
||||
}
|
||||
|
||||
req.URL.RawQuery = params.Encode()
|
||||
|
||||
// 请求交易记录
|
||||
resp, err := client.Do(req)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
|
||||
return gjson.Result{}, fmt.Errorf("请求交易记录错误: StatusCode != 200")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
|
||||
return gjson.Result{}, fmt.Errorf("请求交易记录错误: %w", err)
|
||||
}
|
||||
|
||||
// 获取响应记录
|
||||
all, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
|
||||
return gjson.Result{}, fmt.Errorf("读取交易记录错误: %w", err)
|
||||
}
|
||||
|
||||
// 释放响应请求
|
||||
_ = resp.Body.Close()
|
||||
|
||||
// 解析响应记录
|
||||
return gjson.ParseBytes(all), nil
|
||||
}
|
||||
|
||||
// 解析交易金额
|
||||
func parseTransAmount(amount float64) string {
|
||||
var _decimalAmount = decimal.NewFromFloat(amount)
|
||||
var _decimalDivisor = decimal.NewFromFloat(1000000)
|
||||
return _decimalAmount.Div(_decimalDivisor).String()
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package mqtt
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
)
|
||||
|
||||
type activeConf struct {
|
||||
host string
|
||||
port string
|
||||
user string
|
||||
pass string
|
||||
}
|
||||
|
||||
var (
|
||||
client mqtt.Client
|
||||
mu sync.RWMutex
|
||||
curConf activeConf
|
||||
)
|
||||
|
||||
// Reload 按最新配置连接MQTT服务器
|
||||
func Reload() error {
|
||||
host := model.GetC(model.MqttHost)
|
||||
port := model.GetC(model.MqttPort)
|
||||
if host == "" || port == "" {
|
||||
return nil // 未配置 MQTT,跳过
|
||||
}
|
||||
|
||||
newConf := activeConf{
|
||||
host: host,
|
||||
port: port,
|
||||
user: model.GetC(model.MqttUser),
|
||||
pass: model.GetC(model.MqttPass),
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if newConf == curConf { // 配置未变更,无需重连
|
||||
return nil
|
||||
}
|
||||
|
||||
// 断开旧连接(给 250ms 优雅退出)
|
||||
if client != nil {
|
||||
client.Disconnect(250)
|
||||
log.Info("🔄 MQTT 配置变动,正在连接...")
|
||||
}
|
||||
|
||||
opts := mqtt.NewClientOptions()
|
||||
// 暂时只支持 tcp 模式
|
||||
opts.AddBroker(fmt.Sprintf("tcp://%s:%s", newConf.host, newConf.port))
|
||||
opts.SetUsername(newConf.user)
|
||||
opts.SetPassword(newConf.pass)
|
||||
opts.SetClientID(fmt.Sprintf("VUPAY %d", os.Getpid()))
|
||||
opts.SetAutoReconnect(true)
|
||||
opts.SetOrderMatters(false)
|
||||
opts.SetOnConnectHandler(onConnectHandler)
|
||||
opts.SetConnectionLostHandler(onConnectionLost)
|
||||
|
||||
newClient := mqtt.NewClient(opts)
|
||||
if token := newClient.Connect(); token.Wait() && token.Error() != nil {
|
||||
return fmt.Errorf("MQTT 连接失败: %s", token.Error())
|
||||
}
|
||||
|
||||
client = newClient
|
||||
curConf = newConf
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func onConnectHandler(c mqtt.Client) {
|
||||
for topic, cb := range subscribeMap {
|
||||
c.Subscribe(topic, cb.Qos, cb.Handler).Wait()
|
||||
}
|
||||
|
||||
log.Info("✅ MQTT 连接成功")
|
||||
}
|
||||
|
||||
func onConnectionLost(_ mqtt.Client, err error) {
|
||||
log.Warn(fmt.Sprintf("❌ MQTT 连接断开: %s", err.Error()))
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package mqtt
|
||||
|
||||
import (
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
)
|
||||
|
||||
// Publish 发布消息。若 MQTT 未连接则静默丢弃,返回 nil。
|
||||
func Publish(topic string, qos byte, retained bool, payload interface{}) mqtt.Token {
|
||||
mu.RLock()
|
||||
c := client
|
||||
mu.RUnlock()
|
||||
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
token := c.Publish(topic, qos, retained, payload)
|
||||
if qos > 0 {
|
||||
go func() {
|
||||
token.Wait()
|
||||
if err := token.Error(); err != nil {
|
||||
log.Warn("MQTT publish error: " + err.Error())
|
||||
return
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
return token
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package mqtt
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
)
|
||||
|
||||
type callback struct {
|
||||
Qos byte
|
||||
Handler mqtt.MessageHandler
|
||||
}
|
||||
|
||||
var subscribeMap = make(map[string]callback)
|
||||
|
||||
// Subscribe 注册订阅。topic 会持久保存在 subscribeMap,
|
||||
// 重连后由 onConnectHandler 自动恢复所有订阅。
|
||||
func Subscribe(topic string, qos byte, handler mqtt.MessageHandler) {
|
||||
subscribeMap[topic] = callback{Qos: qos, Handler: handler}
|
||||
|
||||
mu.RLock()
|
||||
c := client
|
||||
mu.RUnlock()
|
||||
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if token := c.Subscribe(topic, qos, handler); token.Wait() && token.Error() == nil {
|
||||
log.Info(fmt.Sprintf("✅ 订阅主题: %s", topic))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package notifier
|
||||
|
||||
import "git.viaeon.com/admin/vupay/app/model"
|
||||
|
||||
type None struct{}
|
||||
|
||||
func (None) Initialize(params string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (None) Success(order model.Order) {}
|
||||
|
||||
func (None) NotifyFail(order model.Order, reason string) {}
|
||||
|
||||
func (None) NonOrderTransfer(trans model.TronTransfer, wa model.Wallet) {
|
||||
|
||||
}
|
||||
|
||||
func (None) TronResourceChange(res model.TronResource) {
|
||||
|
||||
}
|
||||
|
||||
func (None) Welcome() {
|
||||
|
||||
}
|
||||
|
||||
func (None) Test() error {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package notifier
|
||||
|
||||
import (
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
ChannelNone = "none"
|
||||
ChannelWechat = "wechat"
|
||||
ChannelTelegram = "telegram"
|
||||
)
|
||||
|
||||
type Notifier interface {
|
||||
Initialize(params string) error // 初始化
|
||||
Success(o model.Order) // 交易成功通知
|
||||
NotifyFail(o model.Order, reason string) // 订单回调失败通知
|
||||
NonOrderTransfer(trans model.TronTransfer, wa model.Wallet) // 非订单交易通知
|
||||
TronResourceChange(res model.TronResource) // Tron 资源变动通知
|
||||
Welcome() // 程序启动时的欢迎信息
|
||||
Test() error // 测试通知是否成功
|
||||
}
|
||||
|
||||
var notifierMap = make(map[string]Notifier)
|
||||
var confKeys = []model.ConfKey{
|
||||
model.NotifierChannel,
|
||||
model.NotifierParams,
|
||||
}
|
||||
|
||||
func NewNotifier(channel, params string) (Notifier, error) {
|
||||
var key = utils.Md5String(channel + params)
|
||||
if n, ok := notifierMap[key]; ok {
|
||||
return n, nil
|
||||
}
|
||||
|
||||
var notifier Notifier
|
||||
|
||||
switch channel {
|
||||
case ChannelNone:
|
||||
notifier = &None{}
|
||||
case ChannelWechat:
|
||||
notifier = &Wechat{}
|
||||
case ChannelTelegram:
|
||||
notifier = &Telegram{}
|
||||
default:
|
||||
notifier = &None{}
|
||||
}
|
||||
|
||||
err := notifier.Initialize(params)
|
||||
if err != nil {
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
notifierMap[key] = notifier
|
||||
|
||||
return notifier, nil
|
||||
}
|
||||
|
||||
func getNotifier() (Notifier, error) {
|
||||
data := model.GetVs(confKeys)
|
||||
return NewNotifier(data[model.NotifierChannel], data[model.NotifierParams])
|
||||
}
|
||||
|
||||
func Success(order model.Order) {
|
||||
notifier, err := getNotifier()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go notifier.Success(order)
|
||||
}
|
||||
|
||||
func NotifyFail(order model.Order, reason string) {
|
||||
notifier, err := getNotifier()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go notifier.NotifyFail(order, reason)
|
||||
}
|
||||
|
||||
func NonOrderTransfer(trans model.TronTransfer, wa model.Wallet) {
|
||||
notifier, err := getNotifier()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go notifier.NonOrderTransfer(trans, wa)
|
||||
}
|
||||
|
||||
func TronResourceChange(res model.TronResource) {
|
||||
notifier, err := getNotifier()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go notifier.TronResourceChange(res)
|
||||
}
|
||||
|
||||
func Welcome() {
|
||||
notifier, err := getNotifier()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
go notifier.Welcome()
|
||||
}
|
||||
|
||||
func Test() error {
|
||||
notifier, err := getNotifier()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return notifier.Test()
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package notifier
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app"
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/tronprotocol/core"
|
||||
)
|
||||
|
||||
type Telegram struct {
|
||||
api *bot.Bot
|
||||
token string
|
||||
chatID int64
|
||||
topicID int
|
||||
}
|
||||
|
||||
func (t *Telegram) Initialize(params string) error {
|
||||
info := gjson.Parse(params)
|
||||
|
||||
t.token = info.Get("bot_token").String()
|
||||
t.chatID = info.Get("chat_id").Int()
|
||||
t.topicID = cast.ToInt(info.Get("topic_id").Int())
|
||||
|
||||
b, err := bot.New(t.token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
t.api = b
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Telegram) Success(o model.Order) {
|
||||
if o.Status != model.OrderStatusSuccess {
|
||||
return
|
||||
}
|
||||
|
||||
tradeType := string(o.TradeType)
|
||||
tokenType, err := model.GetCrypto(o.TradeType)
|
||||
if err != nil {
|
||||
t.sendMessage(&bot.SendMessageParams{Text: "❌交易类型不支持:" + tradeType})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
token := string(tokenType)
|
||||
|
||||
text := `
|
||||
\#收款成功 \#订单交易 \#` + token + `
|
||||
\-\-\-
|
||||
` + "```" + `
|
||||
🚦商户订单:%v
|
||||
💰请求金额:%v ` + string(o.Fiat) + `(%v)
|
||||
💲支付数额:%v ` + tradeType + `
|
||||
💎交易哈希:%s
|
||||
✅收款地址:%s
|
||||
⏱️创建时间:%s
|
||||
️🎯️支付时间:%s
|
||||
` + "```" + `
|
||||
`
|
||||
text = fmt.Sprintf(text,
|
||||
o.OrderId,
|
||||
o.Money,
|
||||
o.Rate,
|
||||
o.Amount,
|
||||
utils.MaskHash(o.RefHash),
|
||||
utils.MaskAddress(o.Address),
|
||||
o.CreatedAt.Format(time.DateTime),
|
||||
o.UpdatedAt.Format(time.DateTime),
|
||||
)
|
||||
|
||||
t.sendMessage(&bot.SendMessageParams{
|
||||
Text: text,
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
ReplyMarkup: &models.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]models.InlineKeyboardButton{
|
||||
{
|
||||
models.InlineKeyboardButton{Text: "📝查看交易明细", URL: o.GetTxUrl()},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (t *Telegram) NotifyFail(o model.Order, reason string) {
|
||||
tradeType := string(o.TradeType)
|
||||
tokenT, err := model.GetCrypto(o.TradeType)
|
||||
if err != nil {
|
||||
t.sendMessage(&bot.SendMessageParams{Text: "❌交易类型不支持:" + tradeType})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
token := string(tokenT)
|
||||
|
||||
text := fmt.Sprintf(`
|
||||
\#回调失败 \#订单交易 \#`+token+`
|
||||
\-\-\-
|
||||
`+"```"+`
|
||||
🚦商户订单:%v
|
||||
💲支付数额:%v
|
||||
💰请求金额:%v `+string(o.Fiat)+`(%v)
|
||||
💍交易类别:%s
|
||||
⚖️️确认时间:%s
|
||||
⏰下次回调:%s
|
||||
🗒️失败原因:%s
|
||||
`+"```"+`
|
||||
`,
|
||||
utils.Ec(o.OrderId),
|
||||
o.Amount,
|
||||
o.Money, o.Rate,
|
||||
strings.ToUpper(tradeType),
|
||||
o.ConfirmedAt.Format(time.DateTime),
|
||||
utils.CalcNextNotifyTime(*o.ConfirmedAt, o.NotifyNum+1).Format(time.DateTime),
|
||||
reason,
|
||||
)
|
||||
|
||||
t.sendMessage(&bot.SendMessageParams{
|
||||
Text: text,
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
ReplyMarkup: &models.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]models.InlineKeyboardButton{
|
||||
{
|
||||
models.InlineKeyboardButton{Text: "📝查看收款详情", CallbackData: o.GetTxUrl()},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (t *Telegram) NonOrderTransfer(trans model.TronTransfer, wa model.Wallet) {
|
||||
title := nonOrderTransferTitle(trans, wa)
|
||||
|
||||
text := fmt.Sprintf(
|
||||
"\\#账户%s \\#非订单交易\n\\-\\-\\-\n```\n💲交易数额:%v \n💍交易类别:"+strings.ToUpper(string(trans.TradeType))+"\n⏱️交易时间:%v\n✅接收地址:%v\n🅾️发送地址:%v```\n",
|
||||
title,
|
||||
trans.Amount.String(),
|
||||
trans.Timestamp.Format(time.DateTime),
|
||||
utils.MaskAddress(trans.RecvAddress),
|
||||
utils.MaskAddress(trans.FromAddress),
|
||||
)
|
||||
|
||||
t.sendMessage(&bot.SendMessageParams{
|
||||
Text: text,
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
ReplyMarkup: models.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]models.InlineKeyboardButton{
|
||||
{
|
||||
models.InlineKeyboardButton{Text: "📝查看交易明细", URL: model.GetTxUrl(trans.TradeType, trans.TxHash)},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func nonOrderTransferTitle(trans model.TronTransfer, wa model.Wallet) string {
|
||||
if trans.RecvAddress == wa.MatchAddr {
|
||||
return "收入"
|
||||
}
|
||||
|
||||
return "支出"
|
||||
}
|
||||
|
||||
func (t *Telegram) TronResourceChange(res model.TronResource) {
|
||||
title := "代理"
|
||||
if res.Type == core.Transaction_Contract_UnDelegateResourceContract {
|
||||
title = "回收"
|
||||
}
|
||||
|
||||
text := fmt.Sprintf(
|
||||
"\\#资源动态 \\#能量"+title+"\n\\-\\-\\-\n```\n🔋质押数量:"+cast.ToString(res.Balance/1000000)+"\n⏱️交易时间:%v\n✅操作地址:%v\n🅾️资源来源:%v```\n",
|
||||
res.Timestamp.Format(time.DateTime),
|
||||
utils.MaskAddress(res.RecvAddress),
|
||||
utils.MaskAddress(res.FromAddress),
|
||||
)
|
||||
|
||||
t.sendMessage(&bot.SendMessageParams{
|
||||
Text: text,
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
ReplyMarkup: models.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]models.InlineKeyboardButton{
|
||||
{
|
||||
models.InlineKeyboardButton{Text: "📝查看交易明细", URL: "https://tronscan.org/#/transaction/" + res.ID},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (t *Telegram) Welcome() {
|
||||
text := `
|
||||
👋 欢迎使用 VUPAY,` + conf.Desc + `,如果您看到此消息,说明系统已启动成功!
|
||||
|
||||
📌当前版本:` + app.Version + `
|
||||
🎉开源地址:` + conf.Github + `
|
||||
---
|
||||
`
|
||||
t.sendMessage(&bot.SendMessageParams{
|
||||
Text: text,
|
||||
ReplyMarkup: models.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]models.InlineKeyboardButton{
|
||||
{
|
||||
{Text: "🌐 访问站点", URL: "https://u.viaeon.com"},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (t *Telegram) Test() error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
|
||||
defer cancel()
|
||||
_, err := t.api.SendMessage(ctx, &bot.SendMessageParams{
|
||||
ChatID: t.chatID,
|
||||
MessageThreadID: t.topicID,
|
||||
Text: "✅ 这是一条测试消息,Telegram 通知配置成功!\n当前系统时间:" + time.Now().Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (t *Telegram) sendMessage(p *bot.SendMessageParams) {
|
||||
p.ChatID = t.chatID
|
||||
p.MessageThreadID = t.topicID
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
|
||||
defer cancel()
|
||||
|
||||
_, err := t.api.SendMessage(ctx, p)
|
||||
if err != nil {
|
||||
log.Warn("Bot Send Message Error:", err.Error())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package notifier
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
)
|
||||
|
||||
func TestNonOrderTransferTitleUsesMatchAddress(t *testing.T) {
|
||||
trans := model.TronTransfer{
|
||||
RecvAddress: "0xf9dff4e813644edc7d9b1b535100b7e92333f743",
|
||||
FromAddress: "0x6cba0ff7e76b225ee3b975c3096d828f012c8c72",
|
||||
}
|
||||
wallet := model.Wallet{
|
||||
Address: "0xF9DFF4E813644eDc7D9b1b535100b7e92333f743",
|
||||
MatchAddr: "0xf9dff4e813644edc7d9b1b535100b7e92333f743",
|
||||
}
|
||||
|
||||
if title := nonOrderTransferTitle(trans, wallet); title != "收入" {
|
||||
t.Fatalf("title = %q, want %q", title, "收入")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNonOrderTransferTitleMarksOutgoingTransfer(t *testing.T) {
|
||||
trans := model.TronTransfer{
|
||||
RecvAddress: "0xrecipient",
|
||||
FromAddress: "0xf9dff4e813644edc7d9b1b535100b7e92333f743",
|
||||
}
|
||||
wallet := model.Wallet{
|
||||
Address: "0xF9DFF4E813644eDc7D9b1b535100b7e92333f743",
|
||||
MatchAddr: "0xf9dff4e813644edc7d9b1b535100b7e92333f743",
|
||||
}
|
||||
|
||||
if title := nonOrderTransferTitle(trans, wallet); title != "支出" {
|
||||
t.Fatalf("title = %q, want %q", title, "支出")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package notifier
|
||||
|
||||
import (
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
)
|
||||
|
||||
type Wechat struct{}
|
||||
|
||||
func (Wechat) Initialize(params string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (Wechat) Success(order model.Order) {}
|
||||
|
||||
func (Wechat) NotifyFail(order model.Order, reason string) {}
|
||||
|
||||
func (Wechat) NonOrderTransfer(trans model.TronTransfer, wa model.Wallet) {
|
||||
|
||||
}
|
||||
|
||||
func (Wechat) TronResourceChange(res model.TronResource) {
|
||||
|
||||
}
|
||||
|
||||
func (Wechat) Welcome() {
|
||||
|
||||
}
|
||||
|
||||
func (Wechat) Test() error {
|
||||
return nil
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func OrderNotify(order model.TradeOrders) {
|
||||
var data = make(map[string]interface{})
|
||||
var body = struct {
|
||||
TradeId string `json:"trade_id"` // 本地订单号
|
||||
OrderId string `json:"order_id"` // 客户交易id
|
||||
Amount float64 `json:"amount"` // 订单金额 CNY
|
||||
ActualAmount string `json:"actual_amount"` // USDT 交易数额
|
||||
Token string `json:"token"` // 收款钱包地址
|
||||
BlockTransactionId string `json:"block_transaction_id"` // 区块id
|
||||
Signature string `json:"signature"` // 签名
|
||||
Status int `json:"status"` // 1:等待支付,2:支付成功,3:已过期
|
||||
}{
|
||||
TradeId: order.TradeId,
|
||||
OrderId: order.OrderId,
|
||||
Amount: order.Money,
|
||||
ActualAmount: order.Amount,
|
||||
Token: order.Address,
|
||||
BlockTransactionId: order.TradeHash,
|
||||
Status: order.Status,
|
||||
}
|
||||
var jsonBody, err = json.Marshal(body)
|
||||
if err != nil {
|
||||
log.Error("Notify Json Marshal Error:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(jsonBody, &data); err != nil {
|
||||
log.Error("Notify JSON Unmarshal Error:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 签名
|
||||
body.Signature = help.GenerateSignature(data, config.GetAuthToken())
|
||||
|
||||
// 再次序列化
|
||||
jsonBody, err = json.Marshal(body)
|
||||
var client = http.Client{Timeout: time.Second * 5}
|
||||
var postReq, err2 = http.NewRequest("POST", order.NotifyUrl, strings.NewReader(string(jsonBody)))
|
||||
if err2 != nil {
|
||||
log.Error("Notify NewRequest Error:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
postReq.Header.Set("Content-Type", "application/json")
|
||||
postReq.Header.Set("Powered-By", "https://github.com/v03413/bepusdt")
|
||||
resp, err := client.Do(postReq)
|
||||
if err != nil {
|
||||
log.Error("Notify Do Error:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
log.Warn(fmt.Sprintf("订单回调失败(%v):resp.StatusCode != 200", order.OrderId), order.OrderSetNotifyState(model.OrderNotifyStateFail))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
all, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Warn(fmt.Sprintf("订单回调失败(%v):io.ReadAll(resp.Body) Error:", order.OrderId), err, order.OrderSetNotifyState(model.OrderNotifyStateFail))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if string(all) != "ok" {
|
||||
log.Warn(fmt.Sprintf("订单回调失败(%v):body != ok (%s)", order.OrderId, string(all)), err, order.OrderSetNotifyState(model.OrderNotifyStateFail))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err = order.OrderSetNotifyState(model.OrderNotifyStateSucc)
|
||||
if err != nil {
|
||||
log.Error("订单标记通知成功错误:", err, order.OrderId)
|
||||
} else {
|
||||
log.Info("订单通知成功:", order.OrderId)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"git.viaeon.com/admin/vupay/app/handler/admin"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func adminInit(e *gin.Engine) {
|
||||
var confRtr = e.Group("/api/conf")
|
||||
var confHdr = new(admin.Conf)
|
||||
{
|
||||
GetRegister(confRtr, "/rpc", true, confHdr.Rpc)
|
||||
PostRegister(confRtr, "/set", true, confHdr.Set)
|
||||
PostRegister(confRtr, "/get", true, confHdr.Get)
|
||||
PostRegister(confRtr, "/del", true, confHdr.Del)
|
||||
PostRegister(confRtr, "/gets", true, confHdr.Gets)
|
||||
PostRegister(confRtr, "/sets", true, confHdr.Sets)
|
||||
PostRegister(confRtr, "/notifier", true, confHdr.Notifier)
|
||||
PostRegister(confRtr, "/notifier_test", true, confHdr.NotifierTest)
|
||||
PostRegister(confRtr, "/checkout_list", true, confHdr.CheckoutList)
|
||||
PostRegister(confRtr, "/reset_api_auth_token", true, confHdr.ResetApiAuthToken)
|
||||
}
|
||||
|
||||
var walletRtr = e.Group("/api/wallet")
|
||||
var walletHdr = new(admin.Wallet)
|
||||
{
|
||||
PostRegister(walletRtr, "/add", true, walletHdr.Add)
|
||||
PostRegister(walletRtr, "/list", true, walletHdr.List)
|
||||
PostRegister(walletRtr, "/mod", true, walletHdr.Mod)
|
||||
PostRegister(walletRtr, "/del", true, walletHdr.Del)
|
||||
}
|
||||
|
||||
var orderRtr = e.Group("/api/order")
|
||||
var orderHdr = new(admin.Order)
|
||||
{
|
||||
PostRegister(orderRtr, "/list", true, orderHdr.List)
|
||||
PostRegister(orderRtr, "/create", true, orderHdr.Create)
|
||||
PostRegister(orderRtr, "/detail", true, orderHdr.Detail)
|
||||
PostRegister(orderRtr, "/paid", true, orderHdr.Paid)
|
||||
PostRegister(orderRtr, "/manual_notify", true, orderHdr.ManualNotify)
|
||||
PostRegister(orderRtr, "/cancel", true, orderHdr.Cancel)
|
||||
PostRegister(orderRtr, "/del", true, orderHdr.Del)
|
||||
}
|
||||
|
||||
var rateRtr = e.Group("/api/rate")
|
||||
var rateHdr = new(admin.Rate)
|
||||
{
|
||||
PostRegister(rateRtr, "/list", true, rateHdr.List)
|
||||
PostRegister(rateRtr, "/syntax", true, rateHdr.Syntax)
|
||||
PostRegister(rateRtr, "/set_syntax", true, rateHdr.SetSyntax)
|
||||
PostRegister(rateRtr, "/sync", true, rateHdr.Sync)
|
||||
}
|
||||
|
||||
var dashboardRtr = e.Group("/api/dashboard")
|
||||
var dashboardHdr = new(admin.Dashboard)
|
||||
{
|
||||
PostRegister(dashboardRtr, "/home", true, dashboardHdr.Home)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"git.viaeon.com/admin/vupay/app/handler/auth"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func authInit(e *gin.Engine) {
|
||||
var authRtr = e.Group("/api/auth")
|
||||
var authHdr = new(auth.Auth)
|
||||
{
|
||||
GetRegister(authRtr, "/info", true, authHdr.Info)
|
||||
GetRegister(authRtr, "/menu", true, authHdr.Menu)
|
||||
PostRegister(authRtr, "/login", false, authHdr.Login)
|
||||
PostRegister(authRtr, "/logout", true, authHdr.Logout)
|
||||
PostRegister(authRtr, "/set_password", true, authHdr.SetPassword)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.viaeon.com/admin/vupay/static"
|
||||
)
|
||||
|
||||
func TestLangGeCheckoutTemplateIsEmbedded(t *testing.T) {
|
||||
checkout, err := readCheckoutInfoFromFS(static.Checkout, "checkout/langge")
|
||||
if err != nil {
|
||||
t.Fatalf("read langge checkout info: %v", err)
|
||||
}
|
||||
|
||||
if checkout.Name != "LangGe design" {
|
||||
t.Fatalf("unexpected checkout name: %q", checkout.Name)
|
||||
}
|
||||
if checkout.Author == "" {
|
||||
t.Fatal("checkout author is required")
|
||||
}
|
||||
if checkout.Desc == "" {
|
||||
t.Fatal("checkout desc is required")
|
||||
}
|
||||
|
||||
view, err := fs.ReadFile(static.Checkout, "checkout/langge/views/checkout.html")
|
||||
if err != nil {
|
||||
t.Fatalf("read langge checkout template: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(view), "{{ .trade_id }}") {
|
||||
t.Fatal("langge checkout template must only depend on trade_id server injection")
|
||||
}
|
||||
|
||||
tmpl := template.New("default")
|
||||
if !registerTemplatesFromFS(tmpl, static.Checkout, "checkout/langge", "langge") {
|
||||
t.Fatal("langge checkout template was not registered")
|
||||
}
|
||||
if tmpl.Lookup("langge/checkout.html") == nil {
|
||||
t.Fatal("langge checkout template was not registered under expected name")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"git.viaeon.com/admin/vupay/app/handler/epay"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func epayInit(engine *gin.Engine) {
|
||||
epHdr := new(epay.Epay)
|
||||
{
|
||||
engine.POST("/submit.php", epHdr.Submit)
|
||||
engine.GET("/submit.php", epHdr.Submit)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-contrib/sessions/memstore"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/go-cache"
|
||||
)
|
||||
|
||||
var engine *gin.Engine
|
||||
var authRoute = make(map[string]bool)
|
||||
var secureRoute = make(map[string]struct{})
|
||||
|
||||
func Handler() *gin.Engine {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
|
||||
engine = gin.New()
|
||||
session := memstore.NewStore([]byte(model.GetK(model.AdminSecret)))
|
||||
session.Options(sessions.Options{
|
||||
MaxAge: 86400,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
Path: "/",
|
||||
})
|
||||
|
||||
engine.Use(sessions.Sessions("session", session))
|
||||
engine.Use(gin.LoggerWithWriter(log.GetWriter()), gin.Recovery())
|
||||
engine.Use(sessionAuth(), copyright())
|
||||
engine.NoRoute(noRoute())
|
||||
engine.GET("/", func(ctx *gin.Context) {
|
||||
if !model.IsInstalled() {
|
||||
model.InstallLock()
|
||||
ctx.HTML(200, "installed.html", model.GetInstallInfo())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
sess := sessions.Default(ctx)
|
||||
if secure, ok := sess.Get(conf.AdminSecureK).(bool); ok && secure {
|
||||
ctx.HTML(200, "secure.html", gin.H{})
|
||||
return
|
||||
}
|
||||
|
||||
if url := model.GetC(model.HomeRedirectUrl); url != "" {
|
||||
ctx.Redirect(302, url)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.HTML(200, "index.html", gin.H{"title": conf.Desc, "url": conf.Github})
|
||||
})
|
||||
|
||||
{
|
||||
staticInit(engine)
|
||||
vupayInit(engine)
|
||||
epayInit(engine)
|
||||
adminInit(engine)
|
||||
authInit(engine)
|
||||
}
|
||||
|
||||
return engine
|
||||
}
|
||||
|
||||
func sessionAuth() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
if conf.Debug {
|
||||
ctx.Next()
|
||||
return
|
||||
}
|
||||
|
||||
var route = fmt.Sprintf("%s.%s", ctx.Request.Method, ctx.Request.URL.Path)
|
||||
if _, ok := secureRoute[route]; ok {
|
||||
sess := sessions.Default(ctx)
|
||||
if secure, ok := sess.Get(conf.AdminSecureK).(bool); !ok || !secure {
|
||||
ctx.JSON(403, gin.H{"code": 403, "msg": "unauthorized access"})
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var need, ok = authRoute[route]
|
||||
if !ok || !need {
|
||||
ctx.Next()
|
||||
return
|
||||
}
|
||||
|
||||
token, ok := cache.Get(conf.AdminTokenK)
|
||||
if !ok {
|
||||
ctx.JSON(403, gin.H{"code": 403, "msg": "token expired, please login again"})
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
authHeader := ctx.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
ctx.JSON(403, gin.H{"code": 403, "msg": "missing authorization token"})
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if subtle.ConstantTimeCompare([]byte(cast.ToString(token)), []byte(authHeader)) != 1 {
|
||||
ctx.JSON(403, gin.H{"code": 403, "msg": "invalid authorization token"})
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func noRoute() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
if ctx.Request.URL.Path == model.GetC(model.AdminSecure) {
|
||||
session := sessions.Default(ctx)
|
||||
session.Set(conf.AdminSecureK, true)
|
||||
_ = session.Save()
|
||||
|
||||
ctx.Redirect(302, "/#/login")
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func copyright() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
ctx.Writer.Header().Set("Payment-Gateway", "https://git.viaeon.com/admin/vupay")
|
||||
}
|
||||
}
|
||||
|
||||
func PostRegister(router *gin.RouterGroup, relativePath string, checkAuth bool, handlers ...gin.HandlerFunc) {
|
||||
var route = fmt.Sprintf("POST.%s%s", router.BasePath(), relativePath)
|
||||
|
||||
authRoute[route] = checkAuth
|
||||
secureRoute[route] = struct{}{}
|
||||
|
||||
router.POST(relativePath, handlers...)
|
||||
}
|
||||
|
||||
func GetRegister(router *gin.RouterGroup, relativePath string, checkAuth bool, handlers ...gin.HandlerFunc) {
|
||||
var route = fmt.Sprintf("GET.%s%s", router.BasePath(), relativePath)
|
||||
|
||||
authRoute[route] = checkAuth
|
||||
secureRoute[route] = struct{}{}
|
||||
|
||||
router.GET(relativePath, handlers...)
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"git.viaeon.com/admin/vupay/static"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func staticInit(e *gin.Engine) {
|
||||
tmpl := template.New("default")
|
||||
|
||||
template.Must(tmpl.ParseFS(static.Secure, "secure/secure.html"))
|
||||
template.Must(tmpl.ParseFS(static.Payment, "payment/views/*.html"))
|
||||
|
||||
checkoutFS, checkoutRoot, checkoutSourceDesc := checkoutSource()
|
||||
log.Info("当前使用", checkoutSourceDesc)
|
||||
|
||||
// 注册收银台模板和静态资源
|
||||
entries, err := fs.ReadDir(checkoutFS, checkoutRoot)
|
||||
if err != nil {
|
||||
panic(errors.New(fmt.Sprintf("收银台模板读取异常:%v", err)))
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() {
|
||||
continue
|
||||
}
|
||||
|
||||
name := entry.Name()
|
||||
dir := path.Join(checkoutRoot, name)
|
||||
checkout, err := readCheckoutInfoFromFS(checkoutFS, dir)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if registerTemplatesFromFS(tmpl, checkoutFS, dir, name) {
|
||||
model.RegisterCheckout(name, checkout)
|
||||
log.Info("前台收银模板注册成功:", name)
|
||||
}
|
||||
|
||||
registerAssetsFromFS(e, checkoutFS, dir, "/checkout/"+name+"/assets")
|
||||
}
|
||||
|
||||
e.SetHTMLTemplate(tmpl)
|
||||
e.StaticFS("/payment/assets", http.FS(subFS(static.Payment, "payment/assets")))
|
||||
e.StaticFS("/secure/assets", http.FS(subFS(static.Secure, "secure/assets")))
|
||||
}
|
||||
|
||||
func checkoutSource() (fs.FS, string, string) {
|
||||
const externalStaticDir = "static"
|
||||
const checkoutRoot = "checkout"
|
||||
const externalCheckoutDir = externalStaticDir + "/" + checkoutRoot
|
||||
|
||||
if info, err := os.Stat(externalCheckoutDir); err == nil && info.IsDir() {
|
||||
return os.DirFS(externalStaticDir), checkoutRoot, "外部收银台模板目录:" + externalCheckoutDir
|
||||
} else if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return static.Checkout, checkoutRoot, "内嵌收银台模板(外部目录读取失败:" + err.Error() + ")"
|
||||
}
|
||||
|
||||
return static.Checkout, checkoutRoot, "内嵌收银台模板"
|
||||
}
|
||||
|
||||
func readCheckoutInfoFromFS(src fs.FS, baseDir string) (model.Checkout, error) {
|
||||
infoPath := path.Join(baseDir, "checkout.json")
|
||||
data, err := fs.ReadFile(src, infoPath)
|
||||
if err != nil {
|
||||
return model.Checkout{}, fmt.Errorf("checkout.json 不存在或读取失败: %w", err)
|
||||
}
|
||||
|
||||
var checkout model.Checkout
|
||||
if err := json.Unmarshal(data, &checkout); err != nil {
|
||||
return model.Checkout{}, fmt.Errorf("解析 checkout.json 失败: %w", err)
|
||||
}
|
||||
|
||||
return checkout, nil
|
||||
}
|
||||
|
||||
func registerTemplatesFromFS(tmpl *template.Template, src fs.FS, baseDir, namePrefix string) bool {
|
||||
viewsDir := path.Join(baseDir, "views")
|
||||
files, err := fs.ReadDir(src, viewsDir)
|
||||
if err != nil {
|
||||
log.Error("读取模板目录失败:", err.Error())
|
||||
return false
|
||||
}
|
||||
|
||||
registered := false
|
||||
for _, f := range files {
|
||||
if f.IsDir() || !strings.HasSuffix(f.Name(), ".html") {
|
||||
continue
|
||||
}
|
||||
|
||||
content, rErr := fs.ReadFile(src, path.Join(viewsDir, f.Name()))
|
||||
if rErr != nil {
|
||||
log.Error("读取模板文件失败:", rErr.Error())
|
||||
continue
|
||||
}
|
||||
|
||||
name := f.Name()
|
||||
if namePrefix != "" {
|
||||
name = namePrefix + "/" + name
|
||||
}
|
||||
|
||||
if _, pErr := tmpl.New(name).Parse(string(content)); pErr != nil {
|
||||
log.Error("解析模板失败:", pErr.Error())
|
||||
continue
|
||||
}
|
||||
|
||||
registered = true
|
||||
}
|
||||
|
||||
return registered
|
||||
}
|
||||
|
||||
func registerAssetsFromFS(e *gin.Engine, src fs.FS, baseDir, routePath string) {
|
||||
assetsDir := path.Join(baseDir, "assets")
|
||||
if _, err := fs.Stat(src, assetsDir); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
e.StaticFS(routePath, http.FS(subFS(src, assetsDir)))
|
||||
}
|
||||
|
||||
func subFS(src fs.FS, dir string) fs.FS {
|
||||
sub, _ := fs.Sub(src, dir)
|
||||
|
||||
return sub
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"git.viaeon.com/admin/vupay/app/handler/vupay"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func vupayInit(engine *gin.Engine) {
|
||||
epGrp := engine.Group("/pay")
|
||||
epHdr := new(vupay.Vupay)
|
||||
{
|
||||
epGrp.GET("/checkout/:trade_id", epHdr.Checkout)
|
||||
}
|
||||
|
||||
orderGrp := engine.Group("/api/v1/order")
|
||||
{
|
||||
orderGrp.Use(epHdr.SignVerify)
|
||||
orderGrp.POST("/create-transaction", epHdr.CreateTransaction)
|
||||
orderGrp.POST("/cancel-transaction", epHdr.CancelTransaction)
|
||||
orderGrp.POST("/create-order", epHdr.CreateOrder)
|
||||
}
|
||||
|
||||
payGrp := engine.Group("/api/v1/pay")
|
||||
{
|
||||
payGrp.POST("/info", epHdr.Info)
|
||||
payGrp.POST("/notify", epHdr.Notify)
|
||||
payGrp.POST("/methods", epHdr.GetMethods)
|
||||
payGrp.POST("/update-order", epHdr.UpdateOrder)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
func TestAmountMatchHasPrefix(t *testing.T) {
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.PaymentMatchMode: string(model.HasPrefix)})
|
||||
|
||||
cases := []struct {
|
||||
paid, order string
|
||||
want bool
|
||||
}{
|
||||
{"1.5", "1.5", true},
|
||||
{"1.50123", "1.5", true},
|
||||
{"1.509", "1.5", true},
|
||||
{"1.51", "1.5", false},
|
||||
{"1.4999", "1.5", false},
|
||||
{"2", "2", true},
|
||||
{"2.009", "2", true},
|
||||
{"2.01", "2", false},
|
||||
{"2.5", "2", false},
|
||||
{"10.379", "10.37", true},
|
||||
{"10.38", "10.37", false},
|
||||
{"20", "2", false},
|
||||
{"100.5", "100", false},
|
||||
{"123.456789", "123.45", true},
|
||||
// 订单金额小数位多于原子精度时按订单金额的小数位截断
|
||||
{"1.5059", "1.505", true},
|
||||
{"1.506", "1.505", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got := amountMatch(decimal.RequireFromString(c.paid), c.order, string(model.UsdtTrc20))
|
||||
if got != c.want {
|
||||
t.Errorf("paid %s order %s: got %v, want %v", c.paid, c.order, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 同一地址并发订单按原子精度递增金额,截断后每笔付款最多对应其中一笔
|
||||
func TestAmountMatchHasPrefixConcurrentOrders(t *testing.T) {
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.PaymentMatchMode: string(model.HasPrefix)})
|
||||
|
||||
orders := []string{"1.5", "1.51", "1.52"}
|
||||
payments := map[string]string{"1.5": "1.5", "1.50123": "1.5", "1.51": "1.51", "1.519": "1.51", "1.52": "1.52"}
|
||||
for paid, want := range payments {
|
||||
var matched []string
|
||||
for _, o := range orders {
|
||||
if amountMatch(decimal.RequireFromString(paid), o, string(model.UsdtTrc20)) {
|
||||
matched = append(matched, o)
|
||||
}
|
||||
}
|
||||
if len(matched) != 1 || matched[0] != want {
|
||||
t.Errorf("paid %s matched %v, want only %s", paid, matched, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
blockapi "git.viaeon.com/admin/vupay/app/core"
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/panjf2000/ants/v2"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/smallnest/chanx"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
type aptos struct {
|
||||
versionChunkSize int
|
||||
versionConfirmedOffset int
|
||||
lastVersion int
|
||||
versionQueue *chanx.UnboundedChan[version]
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
type version struct {
|
||||
Start int
|
||||
Limit int
|
||||
}
|
||||
|
||||
var apt aptos
|
||||
|
||||
type aptEvent struct {
|
||||
Type string
|
||||
Action string
|
||||
Amount decimal.Decimal
|
||||
Address string
|
||||
}
|
||||
|
||||
type aptAmount struct {
|
||||
Amount string
|
||||
Type model.TradeType
|
||||
}
|
||||
|
||||
func init() {
|
||||
apt = newAptos()
|
||||
Register(Task{Callback: apt.versionDispatch})
|
||||
Register(Task{Callback: apt.syncVersionForward, Duration: time.Second * 3})
|
||||
Register(Task{Callback: apt.tradeConfirmHandle, Duration: time.Second * 5})
|
||||
Register(Task{Callback: apt.lookbackVersion, Duration: time.Second * 15})
|
||||
}
|
||||
|
||||
func newAptos() aptos {
|
||||
return aptos{
|
||||
versionChunkSize: 100,
|
||||
versionConfirmedOffset: 1000,
|
||||
lastVersion: 0,
|
||||
versionQueue: chanx.NewUnboundedChan[version](context.Background(), 30),
|
||||
client: utils.NewHttpClient(),
|
||||
}
|
||||
}
|
||||
|
||||
func (a *aptos) syncVersionForward(ctx context.Context) {
|
||||
if syncBreak(conf.Aptos, a.versionQueue.Len()) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
req, _ := http.NewRequestWithContext(ctx, "GET", model.Endpoint(conf.Aptos)+"/v1", nil)
|
||||
resp, err := a.client.Do(req)
|
||||
if err != nil {
|
||||
log.Task.Warn("aptos syncVersionForward Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
log.Task.Warn("aptos syncVersionForward Error response status code:", resp.StatusCode)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Task.Warn("aptos syncVersionForward Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
now := int(gjson.GetBytes(body, "ledger_version").Int())
|
||||
if now <= 0 {
|
||||
log.Task.Warn("syncVersionForward Error: invalid ledger_version:", now)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if now-a.lastVersion > 10000 {
|
||||
a.lastVersion = now - a.versionChunkSize
|
||||
}
|
||||
|
||||
var sub = now - a.lastVersion
|
||||
if sub <= a.versionChunkSize {
|
||||
a.versionQueue.In <- version{Start: a.lastVersion, Limit: sub}
|
||||
} else {
|
||||
chunks := (sub + a.versionChunkSize - 1) / a.versionChunkSize
|
||||
for i := 0; i < chunks; i++ {
|
||||
limit := a.versionChunkSize
|
||||
start := a.lastVersion + a.versionChunkSize*i
|
||||
if i == chunks-1 {
|
||||
limit = sub % a.versionChunkSize
|
||||
if limit == 0 {
|
||||
limit = a.versionChunkSize
|
||||
}
|
||||
}
|
||||
|
||||
a.versionQueue.In <- version{Start: start, Limit: limit}
|
||||
}
|
||||
}
|
||||
|
||||
a.lastVersion = now
|
||||
}
|
||||
|
||||
func (a *aptos) lookbackVersion(ctx context.Context) {
|
||||
if syncBreak(conf.Aptos, a.versionQueue.Len()) {
|
||||
return
|
||||
}
|
||||
|
||||
startAt, endAt, ok := getLookbackUnix(conf.Aptos)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
start, end := blockapi.New().GetBoundaryHeights(startAt, endAt, conf.Aptos)
|
||||
for i := int(start); i <= int(end); i += a.versionChunkSize {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
if syncBreak(conf.Aptos, a.versionQueue.Len()) {
|
||||
return
|
||||
}
|
||||
limit := a.versionChunkSize
|
||||
if i+limit > int(end) {
|
||||
limit = int(end) - i + 1
|
||||
}
|
||||
a.versionQueue.In <- version{Start: i, Limit: limit}
|
||||
time.Sleep(time.Millisecond * 200) // 速率控制
|
||||
}
|
||||
}
|
||||
|
||||
func (a *aptos) versionDispatch(ctx context.Context) {
|
||||
p, err := ants.NewPoolWithFunc(3, a.versionParse)
|
||||
if err != nil {
|
||||
log.Task.Warn("aptos versionDispatch Error:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer p.Release()
|
||||
|
||||
for {
|
||||
select {
|
||||
case n := <-a.versionQueue.Out:
|
||||
if err := p.Invoke(n); err != nil {
|
||||
a.versionQueue.In <- n
|
||||
log.Task.Warn("versionDispatch Error invoking process slot:", err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
if err := ctx.Err(); err != nil {
|
||||
log.Task.Warn("versionDispatch context done:", err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 由于 aptos 网络特性,交易数据中不会显示存在交易转账 from => to 的对应关系,
|
||||
// 所以目前此解析函数存在大量循环嵌套解析,逻辑较为复杂,希望未来有更好的方式进行解析 慢慢优化
|
||||
func (a *aptos) versionParse(n any) {
|
||||
p := n.(version)
|
||||
|
||||
var net = conf.Aptos
|
||||
var url = fmt.Sprintf("%sv1/transactions?start=%d&limit=%d", model.Endpoint(conf.Aptos), p.Start, p.Limit)
|
||||
|
||||
conf.RecordSuccess(net, cast.ToString(p.Start+p.Limit))
|
||||
resp, err := a.client.Get(url)
|
||||
if err != nil {
|
||||
conf.RecordFailure(net)
|
||||
log.Task.Warn("versionParse Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
conf.RecordFailure(net)
|
||||
log.Task.Warn("versionParse Error response status code:", resp.StatusCode)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
conf.RecordFailure(net)
|
||||
a.versionQueue.In <- p
|
||||
log.Task.Warn("versionParse Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if !gjson.ValidBytes(body) {
|
||||
conf.RecordFailure(net)
|
||||
a.versionQueue.In <- p
|
||||
log.Task.Warn("versionParse Error: invalid JSON response body")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
transfers := make([]transfer, 0)
|
||||
for _, trans := range gjson.ParseBytes(body).Array() {
|
||||
tsNano := trans.Get("timestamp").Int() * 1000
|
||||
timestamp := time.Unix(tsNano/1e9, tsNano%1e9)
|
||||
|
||||
ver := int(trans.Get("version").Int())
|
||||
hash := trans.Get("hash").String()
|
||||
addrOwner := make(map[string]string) // [address] => owner address
|
||||
addrType := make(map[string]model.TradeType) // [address] => tradeType
|
||||
amtAddrMap := map[string]map[aptAmount]string{"deposit": {}, "withdraw": {}} // [amount] => address
|
||||
aptEvents := make([]aptEvent, 0)
|
||||
trans.Get("changes").ForEach(func(_, v gjson.Result) bool {
|
||||
if v.Get("type").String() != "write_resource" {
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
data := v.Get("data")
|
||||
if data.Get("type").String() == "0x1::fungible_asset::FungibleStore" {
|
||||
addr := v.Get("address").String()
|
||||
switch data.Get("data.metadata.inner").String() {
|
||||
case conf.UsdtAptos:
|
||||
addrType[addr] = model.UsdtAptos
|
||||
case conf.UsdcAptos:
|
||||
addrType[addr] = model.UsdcAptos
|
||||
}
|
||||
}
|
||||
if data.Get("type").String() == "0x1::object::ObjectCore" {
|
||||
addrOwner[v.Get("address").String()] = data.Get("data.owner").String()
|
||||
}
|
||||
|
||||
return true
|
||||
})
|
||||
trans.Get("events").ForEach(func(_, v gjson.Result) bool {
|
||||
amount := v.Get("data.amount").String()
|
||||
amt, err := decimal.NewFromString(amount)
|
||||
if err != nil {
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
address := v.Get("data.store").String()
|
||||
switch v.Get("type").String() {
|
||||
case "0x1::fungible_asset::Deposit":
|
||||
aptEvents = append(aptEvents, aptEvent{Amount: amt, Address: address, Action: "deposit"})
|
||||
amtAddrMap["deposit"][aptAmount{Amount: amount, Type: addrType[address]}] = address
|
||||
case "0x1::fungible_asset::Withdraw":
|
||||
amtAddrMap["withdraw"][aptAmount{Amount: amount, Type: addrType[address]}] = address
|
||||
aptEvents = append(aptEvents, aptEvent{Amount: amt, Address: address, Action: "withdraw"})
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
// 针对 一个withdraw 对应 一个deposit 且数额相同的情况
|
||||
for amt, to := range amtAddrMap["deposit"] {
|
||||
from, ok := amtAddrMap["withdraw"][amt]
|
||||
if !ok {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
amount, ok := new(big.Int).SetString(amt.Amount, 10)
|
||||
if !ok {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
tradeType, ok := addrType[to]
|
||||
if !ok {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transfers = append(transfers, transfer{
|
||||
Network: net,
|
||||
TxHash: hash,
|
||||
Amount: decimal.NewFromBigInt(amount, model.GetTradeDecimal(tradeType)),
|
||||
FromAddress: a.padAddressLeadingZeros(addrOwner[from]),
|
||||
RecvAddress: a.padAddressLeadingZeros(addrOwner[to]),
|
||||
Timestamp: timestamp,
|
||||
TradeType: tradeType,
|
||||
BlockNum: ver,
|
||||
})
|
||||
}
|
||||
|
||||
// 针对 一个withdraw 对应 多个deposit(数额累计等于 withdraw) 的情况
|
||||
processEvents := func(tradeType model.TradeType, events []aptEvent) ([]aptEvent, map[string]string) {
|
||||
deposits := make([]aptEvent, 0)
|
||||
withdraws := make(map[decimal.Decimal]aptEvent)
|
||||
fromMap := make(map[string]string)
|
||||
|
||||
// 分类事件
|
||||
for _, e := range events {
|
||||
if addrType[e.Address] == tradeType {
|
||||
if e.Action == "deposit" {
|
||||
deposits = append(deposits, e)
|
||||
}
|
||||
if e.Action == "withdraw" {
|
||||
withdraws[e.Amount] = e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 穷举计算匹配关系,只穷举 A + B = C 的情况,实际上还存在 A + B + C + ... = D
|
||||
// 大部分这种情况都是合约 swap 等交易,非普通人1对1转账,所以选择忽视
|
||||
for k1, e1 := range deposits {
|
||||
for k2, e2 := range deposits {
|
||||
if k1 == k2 {
|
||||
continue
|
||||
}
|
||||
for sum, e3 := range withdraws {
|
||||
if e1.Amount.Add(e2.Amount).Equal(sum) {
|
||||
fromMap[e1.Address] = e3.Address
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return deposits, fromMap
|
||||
}
|
||||
generateTransfers := func(deposits []aptEvent, fromMap map[string]string, t model.TradeType, decimals int32) {
|
||||
for _, to := range deposits {
|
||||
if from, ok := fromMap[to.Address]; ok {
|
||||
transfers = append(transfers, transfer{
|
||||
Network: net,
|
||||
TxHash: hash,
|
||||
Amount: decimal.NewFromBigInt(to.Amount.BigInt(), decimals),
|
||||
FromAddress: a.padAddressLeadingZeros(addrOwner[from]),
|
||||
RecvAddress: a.padAddressLeadingZeros(addrOwner[to.Address]),
|
||||
Timestamp: timestamp,
|
||||
TradeType: t,
|
||||
BlockNum: ver,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 处理 USDT
|
||||
usdtDeposits, usdtFrom := processEvents(model.UsdtAptos, aptEvents)
|
||||
generateTransfers(usdtDeposits, usdtFrom, model.UsdtAptos, model.GetTradeDecimal(model.UsdtAptos))
|
||||
|
||||
// 处理 USDC
|
||||
usdcDeposits, usdcFrom := processEvents(model.UsdcAptos, aptEvents)
|
||||
generateTransfers(usdcDeposits, usdcFrom, model.UsdcAptos, model.GetTradeDecimal(model.UsdcAptos))
|
||||
}
|
||||
|
||||
if len(transfers) > 0 {
|
||||
|
||||
transferQueue.In <- transfers
|
||||
}
|
||||
|
||||
log.Task.Info(fmt.Sprintf("区块扫描完成(Aptos) %d.%d 成功率:%s", p.Start, p.Limit, conf.GetSuccessRate(net)))
|
||||
}
|
||||
|
||||
func (a *aptos) padAddressLeadingZeros(addr string) string {
|
||||
addr = strings.TrimPrefix(addr, "0x")
|
||||
addr = strings.Repeat("0", 64-len(addr)) + addr
|
||||
|
||||
return "0x" + addr
|
||||
}
|
||||
|
||||
func (a *aptos) tradeConfirmHandle(ctx context.Context) {
|
||||
var orders = getConfirmingOrders(model.GetNetworkTrades(conf.Aptos))
|
||||
var wg sync.WaitGroup
|
||||
|
||||
var handle = func(o model.Order) {
|
||||
if model.GetC(model.BlockOffsetConfirm) == "1" {
|
||||
if a.lastVersion == 0 {
|
||||
return
|
||||
}
|
||||
if a.lastVersion-o.RefBlockNum < a.versionConfirmedOffset {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
req, _ := http.NewRequestWithContext(ctx, "GET", model.Endpoint(conf.Aptos)+"v1/transactions/by_hash/"+o.RefHash, nil)
|
||||
resp, err := a.client.Do(req)
|
||||
if err != nil {
|
||||
log.Task.Warn("aptos tradeConfirmHandle Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
log.Task.Warn("aptos tradeConfirmHandle Error response status code:", resp.StatusCode)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Task.Warn("aptos tradeConfirmHandle Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
data := gjson.ParseBytes(body)
|
||||
if data.Get("error_code").Exists() {
|
||||
log.Task.Warn("aptos tradeConfirmHandle Error:", data.Get("message").String())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if data.Get("version").String() != "" &&
|
||||
data.Get("success").Bool() &&
|
||||
data.Get("vm_status").String() == "Executed successfully" {
|
||||
|
||||
markFinalConfirmed(o)
|
||||
}
|
||||
}
|
||||
|
||||
for _, order := range orders {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
handle(order)
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/smallnest/chanx"
|
||||
)
|
||||
|
||||
func arbitrumInit() {
|
||||
ctx := context.Background()
|
||||
arb := evm{
|
||||
Network: conf.Arbitrum,
|
||||
Block: block{
|
||||
ConfirmedOffset: 40,
|
||||
},
|
||||
Client: utils.NewHttpClient(),
|
||||
blockScanQueue: chanx.NewUnboundedChan[evmBlock](ctx, 30),
|
||||
}
|
||||
|
||||
Register(Task{Callback: arb.blockDispatch})
|
||||
Register(Task{Callback: arb.syncBlocksForward, Duration: time.Second * 5})
|
||||
Register(Task{Callback: arb.tradeConfirmHandle, Duration: time.Second * 5})
|
||||
Register(Task{Callback: arb.lookbackBlocks, Duration: time.Second * 15})
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/smallnest/chanx"
|
||||
)
|
||||
|
||||
func baseInit() {
|
||||
ctx := context.Background()
|
||||
base := evm{
|
||||
Network: conf.Base,
|
||||
Block: block{
|
||||
ConfirmedOffset: 40,
|
||||
},
|
||||
Client: utils.NewHttpClient(),
|
||||
blockScanQueue: chanx.NewUnboundedChan[evmBlock](ctx, 30),
|
||||
}
|
||||
|
||||
Register(Task{Callback: base.blockDispatch})
|
||||
Register(Task{Callback: base.syncBlocksForward, Duration: time.Second * 5})
|
||||
Register(Task{Callback: base.tradeConfirmHandle, Duration: time.Second * 5})
|
||||
Register(Task{Callback: base.lookbackBlocks, Duration: time.Second * 15})
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/smallnest/chanx"
|
||||
)
|
||||
|
||||
func bscInit() {
|
||||
ctx := context.Background()
|
||||
bsc := evm{
|
||||
Network: conf.Bsc,
|
||||
Block: block{
|
||||
ConfirmedOffset: 15,
|
||||
},
|
||||
Native: evmNative{
|
||||
Parse: true,
|
||||
Decimal: conf.BscBnbDecimals,
|
||||
TradeType: model.BscBnb,
|
||||
},
|
||||
Client: utils.NewHttpClient(),
|
||||
blockScanQueue: chanx.NewUnboundedChan[evmBlock](ctx, 30),
|
||||
}
|
||||
|
||||
Register(Task{Callback: bsc.blockDispatch})
|
||||
Register(Task{Callback: bsc.syncBlocksForward, Duration: time.Second * 5})
|
||||
Register(Task{Callback: bsc.tradeConfirmHandle, Duration: time.Second * 5})
|
||||
Register(Task{Callback: bsc.lookbackBlocks, Duration: time.Second * 15})
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
)
|
||||
|
||||
type rConf struct {
|
||||
}
|
||||
|
||||
// init 配置刷新到内存,高频读取
|
||||
func init() {
|
||||
var c = rConf{}
|
||||
|
||||
Register(Task{Duration: time.Second * 3, Callback: c.Refresh})
|
||||
}
|
||||
|
||||
func (rConf) Refresh(ctx context.Context) {
|
||||
model.RefreshC()
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/smallnest/chanx"
|
||||
)
|
||||
|
||||
func ethInit() {
|
||||
ctx := context.Background()
|
||||
eth := evm{
|
||||
Network: conf.Ethereum,
|
||||
LookbackInterval: time.Second * 2,
|
||||
Block: block{
|
||||
ConfirmedOffset: 12,
|
||||
},
|
||||
Native: evmNative{
|
||||
Parse: true,
|
||||
TradeType: model.EthereumEth,
|
||||
Decimal: conf.EthereumEthDecimals,
|
||||
},
|
||||
Client: utils.NewHttpClient(),
|
||||
blockScanQueue: chanx.NewUnboundedChan[evmBlock](ctx, 30),
|
||||
}
|
||||
|
||||
Register(Task{Callback: eth.blockDispatch})
|
||||
Register(Task{Callback: eth.syncBlocksForward, Duration: time.Second * 12})
|
||||
Register(Task{Callback: eth.tradeConfirmHandle, Duration: time.Second * 5})
|
||||
Register(Task{Callback: eth.lookbackBlocks, Duration: time.Second * 20})
|
||||
}
|
||||
+478
@@ -0,0 +1,478 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
blockapi "git.viaeon.com/admin/vupay/app/core"
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/panjf2000/ants/v2"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/smallnest/chanx"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
const (
|
||||
blockParseMaxNum = 10 // 每次解析区块的最大数量
|
||||
evmTransferEvent = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
|
||||
)
|
||||
|
||||
var chainBlockNum sync.Map
|
||||
|
||||
type block struct {
|
||||
RollDelayOffset int64 // 延迟偏移量,某些RPC节点如果不延迟,会报错 block is out of range,目前发现 https://rpc.xlayer.tech/ 存在此问题
|
||||
ConfirmedOffset int // 确认偏移量,开启交易确认后,区块高度需要减去此值认为交易已确认
|
||||
}
|
||||
|
||||
type evmNative struct {
|
||||
Parse bool
|
||||
Decimal int32
|
||||
TradeType model.TradeType
|
||||
}
|
||||
|
||||
type evm struct {
|
||||
Network string
|
||||
Block block
|
||||
Native evmNative
|
||||
Client *http.Client
|
||||
blockScanQueue *chanx.UnboundedChan[evmBlock]
|
||||
LookbackInterval time.Duration // 回溯时每批入队的间隔,控制 RPC 调用速率;默认 500ms
|
||||
}
|
||||
|
||||
type evmBlock struct {
|
||||
From int64
|
||||
To int64
|
||||
}
|
||||
|
||||
func (e *evm) syncBlocksForward(ctx context.Context) {
|
||||
if syncBreak(e.Network, e.blockScanQueue.Len()) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
post := []byte(`{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}`)
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", e.rpcEndpoint(), bytes.NewBuffer(post))
|
||||
if err != nil {
|
||||
log.Task.Warn("Error creating request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := e.Client.Do(req)
|
||||
if err != nil {
|
||||
log.Task.Warn("Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Task.Warn("Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var res = gjson.ParseBytes(body)
|
||||
if !res.IsObject() {
|
||||
log.Task.Warn(fmt.Sprintf("EVM 数据解析错误(%s): %s", e.Network, string(body)))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var now = utils.HexStr2Int(res.Get("result").String()).Int64() - e.Block.RollDelayOffset
|
||||
if now <= 0 {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var lastBlockNumber int64
|
||||
if v, ok := chainBlockNum.Load(e.Network); ok {
|
||||
lastBlockNumber = v.(int64)
|
||||
}
|
||||
|
||||
if now-lastBlockNumber > cast.ToInt64(model.GetC(model.BlockHeightMaxDiff)) {
|
||||
|
||||
lastBlockNumber = now - 1
|
||||
}
|
||||
|
||||
chainBlockNum.Store(e.Network, now)
|
||||
if now <= lastBlockNumber {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
for from := lastBlockNumber + 1; from <= now; from += blockParseMaxNum {
|
||||
to := from + blockParseMaxNum - 1
|
||||
if to > now {
|
||||
to = now
|
||||
}
|
||||
|
||||
e.blockScanQueue.In <- evmBlock{From: from, To: to}
|
||||
}
|
||||
}
|
||||
|
||||
func (e *evm) lookbackBlocks(ctx context.Context) {
|
||||
if syncBreak(e.Network, e.blockScanQueue.Len()) {
|
||||
return
|
||||
}
|
||||
|
||||
startAt, endAt, ok := getLookbackUnix(model.Network(e.Network))
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
interval := e.LookbackInterval
|
||||
if interval <= 0 {
|
||||
interval = time.Millisecond * 300
|
||||
}
|
||||
|
||||
start, end := blockapi.New().GetBoundaryHeights(startAt, endAt, e.Network)
|
||||
for i := start; i <= end; i += blockParseMaxNum {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
if syncBreak(e.Network, e.blockScanQueue.Len()) {
|
||||
return
|
||||
}
|
||||
to := i + blockParseMaxNum - 1
|
||||
if to > end {
|
||||
to = end
|
||||
}
|
||||
e.blockScanQueue.In <- evmBlock{From: i, To: to}
|
||||
time.Sleep(interval)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *evm) blockDispatch(ctx context.Context) {
|
||||
p, err := ants.NewPoolWithFunc(3, e.getBlockByNumber)
|
||||
if err != nil {
|
||||
log.Task.Warn("Error creating pool:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer p.Release()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case n := <-e.blockScanQueue.Out:
|
||||
if err := p.Invoke(n); err != nil {
|
||||
e.blockScanQueue.In <- n
|
||||
|
||||
log.Task.Warn("Evm Block Dispatch Error invoking process block:", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (e *evm) getBlockByNumber(a any) {
|
||||
b, ok := a.(evmBlock)
|
||||
if !ok {
|
||||
log.Task.Warn("Evm Block Parse Error: expected []int64, got", a)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]string, 0)
|
||||
for i := b.From; i <= b.To; i++ {
|
||||
items = append(items, fmt.Sprintf(`{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["0x%x",%t],"id":%d}`, i, e.Native.Parse, i))
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
|
||||
defer cancel()
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", e.rpcEndpoint(), bytes.NewBuffer([]byte(fmt.Sprintf(`[%s]`, strings.Join(items, ",")))))
|
||||
if err != nil {
|
||||
log.Task.Warn("Error creating request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := e.Client.Do(req)
|
||||
if err != nil {
|
||||
conf.RecordFailure(e.Network)
|
||||
e.blockScanQueue.In <- b
|
||||
log.Task.Warn("eth_getBlockByNumber Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
conf.RecordFailure(e.Network)
|
||||
e.blockScanQueue.In <- b
|
||||
log.Task.Warn("eth_getBlockByNumber Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
conf.RecordSuccess(e.Network, cast.ToString(b.To))
|
||||
|
||||
nativeTransfers := make([]transfer, 0)
|
||||
blockTimestamp := make(map[string]time.Time)
|
||||
for _, itm := range gjson.ParseBytes(body).Array() {
|
||||
if itm.Get("error").Exists() {
|
||||
conf.RecordFailure(e.Network)
|
||||
e.blockScanQueue.In <- b
|
||||
log.Task.Warn(fmt.Sprintf("%s eth_getBlockByNumber response error %s", e.Network, itm.Get("error").String()))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
timestamp := utils.HexStr2Int(itm.Get("result.timestamp").String()).Int64()
|
||||
blockTime := time.Unix(timestamp, 0)
|
||||
blockNumHex := itm.Get("result.number").String()
|
||||
blockTimestamp[blockNumHex] = blockTime
|
||||
|
||||
var array = itm.Get("result.transactions").Array()
|
||||
if e.Native.Parse && len(array) != 0 {
|
||||
|
||||
nativeTransfers = append(nativeTransfers, e.parseNativeTransfer(array, int(utils.HexStr2Int(blockNumHex).Int64()), blockTime)...)
|
||||
}
|
||||
}
|
||||
|
||||
transfers, err := e.parseEventTransfer(b, blockTimestamp)
|
||||
if err != nil {
|
||||
conf.RecordFailure(e.Network)
|
||||
e.blockScanQueue.In <- b
|
||||
log.Task.Warn("Evm Block Parse Error parsing block transfer:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if len(nativeTransfers) > 0 {
|
||||
transferQueue.In <- nativeTransfers
|
||||
}
|
||||
if len(transfers) > 0 {
|
||||
transferQueue.In <- transfers
|
||||
}
|
||||
|
||||
log.Task.Info(fmt.Sprintf("区块扫描完成(%s): %d → %d 成功率:%s", e.Network, b.From, b.To, conf.GetSuccessRate(e.Network)))
|
||||
}
|
||||
|
||||
func (e *evm) parseNativeTransfer(array []gjson.Result, num int, timestamp time.Time) []transfer {
|
||||
nativeTransfers := make([]transfer, 0)
|
||||
for _, tx := range array {
|
||||
if tx.Get("input").String() != "0x" {
|
||||
// 非原生币交易
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
valStr := tx.Get("value").String()
|
||||
if valStr == "0x0" || len(valStr) < 3 {
|
||||
// 过滤 0 值交易
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
amount, ok := big.NewInt(0).SetString(valStr[2:], 16)
|
||||
if !ok || amount.Sign() <= 0 {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
toAddress := tx.Get("to").String()
|
||||
if toAddress == "" { // 合约创建交易 to 为空
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
nativeTransfers = append(nativeTransfers, transfer{
|
||||
Network: e.Network,
|
||||
FromAddress: tx.Get("from").String(),
|
||||
RecvAddress: toAddress,
|
||||
Amount: decimal.NewFromBigInt(amount, e.Native.Decimal),
|
||||
TxHash: tx.Get("hash").String(),
|
||||
BlockNum: num,
|
||||
Timestamp: timestamp,
|
||||
TradeType: e.Native.TradeType,
|
||||
})
|
||||
}
|
||||
|
||||
return nativeTransfers
|
||||
}
|
||||
|
||||
func (e *evm) parseEventTransfer(b evmBlock, timestamp map[string]time.Time) ([]transfer, error) {
|
||||
transfers := make([]transfer, 0)
|
||||
post := []byte(fmt.Sprintf(`{"jsonrpc":"2.0","method":"eth_getLogs","params":[{"fromBlock":"0x%x","toBlock":"0x%x","topics":["%s"]}],"id":1}`, b.From, b.To, evmTransferEvent))
|
||||
resp, err := e.Client.Post(e.rpcEndpoint(), "application/json", bytes.NewBuffer(post))
|
||||
if err != nil {
|
||||
|
||||
return transfers, errors.Join(errors.New("eth_getLogs Post Error"), err)
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
|
||||
return transfers, errors.Join(errors.New("eth_getLogs ReadAll Error"), err)
|
||||
}
|
||||
|
||||
data := gjson.ParseBytes(body)
|
||||
if data.Get("error").Exists() {
|
||||
|
||||
return transfers, errors.New(fmt.Sprintf("%s eth_getLogs response error %s", e.Network, data.Get("error").String()))
|
||||
}
|
||||
|
||||
for _, itm := range data.Get("result").Array() {
|
||||
to := itm.Get("address").String()
|
||||
tradeType, ok := model.GetContractTrade(to)
|
||||
if !ok {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
topics := itm.Get("topics").Array()
|
||||
if len(topics) < 3 {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if topics[0].String() != evmTransferEvent { // transfer event signature
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
from := fmt.Sprintf("0x%s", topics[1].String()[26:])
|
||||
recv := fmt.Sprintf("0x%s", topics[2].String()[26:])
|
||||
amount, ok := big.NewInt(0).SetString(itm.Get("data").String()[2:], 16)
|
||||
if !ok || amount.Sign() <= 0 {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transfers = append(transfers, transfer{
|
||||
Network: e.Network,
|
||||
FromAddress: from,
|
||||
RecvAddress: recv,
|
||||
Amount: decimal.NewFromBigInt(amount, model.GetContractDecimal(to)),
|
||||
TxHash: itm.Get("transactionHash").String(),
|
||||
BlockNum: cast.ToInt(itm.Get("blockNumber").String()),
|
||||
Timestamp: timestamp[itm.Get("blockNumber").String()],
|
||||
TradeType: tradeType,
|
||||
})
|
||||
}
|
||||
|
||||
return transfers, nil
|
||||
}
|
||||
|
||||
func (e *evm) tradeConfirmHandle(ctx context.Context) {
|
||||
var orders = getConfirmingOrders(model.GetNetworkTrades(model.Network(e.Network)))
|
||||
var wg sync.WaitGroup
|
||||
|
||||
var handle = func(o model.Order) {
|
||||
if model.GetC(model.BlockOffsetConfirm) == "1" {
|
||||
last, ok := chainBlockNum.Load(e.Network)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if cast.ToInt(last)-o.RefBlockNum < e.Block.ConfirmedOffset {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
post := []byte(fmt.Sprintf(`{"jsonrpc":"2.0","method":"eth_getTransactionReceipt","params":["%s"],"id":1}`, o.RefHash))
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", e.rpcEndpoint(), bytes.NewBuffer(post))
|
||||
if err != nil {
|
||||
log.Task.Warn("evm tradeConfirmHandle Error creating request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := e.Client.Do(req)
|
||||
if err != nil {
|
||||
log.Task.Warn("evm tradeConfirmHandle Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Task.Warn("evm tradeConfirmHandle Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
data := gjson.ParseBytes(body)
|
||||
if data.Get("error").Exists() {
|
||||
log.Task.Warn(fmt.Sprintf("%s eth_getTransactionReceipt response error %s", e.Network, data.Get("error").String()))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if data.Get("result.status").String() == "0x1" {
|
||||
markFinalConfirmed(o)
|
||||
}
|
||||
}
|
||||
|
||||
for _, order := range orders {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
handle(order)
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func (e *evm) rpcEndpoint() string {
|
||||
|
||||
return model.Endpoint(model.Network(e.Network))
|
||||
}
|
||||
|
||||
func syncBreak(network string, num int) bool {
|
||||
if num >= blockQueueLimit {
|
||||
log.Task.Warn(fmt.Sprintf("%s 同步阻塞,当前区块消费堆积数量:%d", network, num))
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if mqttSubscribed(network) {
|
||||
return false
|
||||
}
|
||||
|
||||
trades := model.GetNetworkTrades(model.Network(network))
|
||||
if len(trades) == 0 {
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
var count int64
|
||||
model.Db.Model(&model.Wallet{}).
|
||||
Where("other_notify = ? and trade_type in (?)", model.WaOtherEnable, trades).
|
||||
Count(&count)
|
||||
if count > 0 {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return !hasLookbackOrders(trades)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
appMqtt "git.viaeon.com/admin/vupay/app/mqtt"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/go-cache"
|
||||
)
|
||||
|
||||
type mqttTransfer struct {
|
||||
Network string `json:"network"`
|
||||
TxHash string `json:"tx_hash"`
|
||||
Amount decimal.Decimal `json:"amount"`
|
||||
FromAddress string `json:"from_address"`
|
||||
RecvAddress string `json:"recv_address"`
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
TradeType model.TradeType `json:"trade_type"`
|
||||
BlockNum int `json:"block_num"`
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(Task{Duration: time.Second * 5, Callback: mqttWatcher})
|
||||
}
|
||||
|
||||
func mqttWatcher(_ context.Context) {
|
||||
if err := appMqtt.Reload(); err != nil {
|
||||
log.Printf("❌ MQTT 连接失败: %s\n", err.Error())
|
||||
}
|
||||
|
||||
networks := strings.Split(model.GetC(model.MqttNetworks), ",")
|
||||
for _, n := range networks {
|
||||
cache.Set("mqtt_subscribed_"+n, true, time.Second*8)
|
||||
}
|
||||
}
|
||||
|
||||
func mqttPublish(t transfer) {
|
||||
if !mqttSubscribed(t.Network) {
|
||||
return
|
||||
}
|
||||
|
||||
var qos = cast.ToUint8(model.GetC(model.MqttPublishQos))
|
||||
var topic = model.GetC(model.MqttTopicPrefix) + "/transfer/" + t.Network
|
||||
var data = mqttTransfer{
|
||||
Network: t.Network,
|
||||
TxHash: t.TxHash,
|
||||
Amount: t.Amount,
|
||||
FromAddress: t.FromAddress,
|
||||
RecvAddress: t.RecvAddress,
|
||||
Timestamp: t.Timestamp.Unix(),
|
||||
TradeType: t.TradeType,
|
||||
BlockNum: t.BlockNum,
|
||||
}
|
||||
go func() {
|
||||
payload, _ := json.Marshal(data)
|
||||
|
||||
appMqtt.Publish(topic, qos, false, payload)
|
||||
}()
|
||||
}
|
||||
|
||||
func mqttSubscribed(n string) bool {
|
||||
_, found := cache.Get("mqtt_subscribed_" + n)
|
||||
return found
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"git.viaeon.com/admin/vupay/app/notifier"
|
||||
"git.viaeon.com/admin/vupay/app/task/notify"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Register(Task{Duration: time.Second * 3, Callback: notifyRetry})
|
||||
Register(Task{Duration: time.Second * 30, Callback: notifyRoll})
|
||||
}
|
||||
|
||||
// notifyRetry 回调失败重试
|
||||
func notifyRetry(context.Context) {
|
||||
tradeOrders, err := model.GetNotifyFailedTradeOrders()
|
||||
if err != nil {
|
||||
log.Task.Error("待回调订单获取失败", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
for _, order := range tradeOrders {
|
||||
next := utils.CalcNextNotifyTime(*order.ConfirmedAt, order.NotifyNum)
|
||||
if time.Now().Unix() >= next.Unix() {
|
||||
go notify.Handle(order)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func notifyRoll(context.Context) {
|
||||
for _, o := range model.GetOrderByStatus(model.OrderStatusWaiting) {
|
||||
notify.Vupay(o)
|
||||
}
|
||||
}
|
||||
|
||||
// notifyOrderSuccess 统一触发订单成功后的回调与订单通知。
|
||||
func notifyOrderSuccess(order model.Order) {
|
||||
go notify.Handle(order)
|
||||
go notifier.Success(order)
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app"
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"git.viaeon.com/admin/vupay/app/notifier"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/spf13/cast"
|
||||
|
||||
"github.com/v03413/go-cache"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type EpNotify struct {
|
||||
TradeId string `json:"trade_id"` // 本地订单号
|
||||
OrderId string `json:"order_id"` // 客户交易id
|
||||
Amount float64 `json:"amount"` // 订单金额 CNY
|
||||
ActualAmount string `json:"actual_amount"` // USDT 交易数额
|
||||
Token string `json:"token"` // 收款钱包地址
|
||||
BlockTransactionId string `json:"block_transaction_id"` // 区块id
|
||||
Signature string `json:"signature"` // 签名
|
||||
Status int `json:"status"` // 1:等待支付,2:支付成功,3:订单超时
|
||||
}
|
||||
|
||||
func Handle(order model.Order) error {
|
||||
if order.Status != model.OrderStatusSuccess {
|
||||
|
||||
return errors.New("订单未支付 无法回调")
|
||||
}
|
||||
|
||||
var ctx, cancel = context.WithTimeout(context.Background(), time.Second*10)
|
||||
defer cancel()
|
||||
|
||||
var err error
|
||||
if order.ApiType == model.OrderApiTypeEpay {
|
||||
err = epay(ctx, order)
|
||||
} else {
|
||||
err = vupay(ctx, order)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log.Info("订单回调成功:", order.TradeId)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func epay(ctx context.Context, order model.Order) error {
|
||||
var client = http.Client{Timeout: time.Second * 5}
|
||||
var notifyUrl = fmt.Sprintf("%s?%s", order.NotifyUrl, order.BuildNotifyParams())
|
||||
|
||||
postReq, err2 := http.NewRequestWithContext(ctx, "GET", notifyUrl, nil)
|
||||
if err2 != nil {
|
||||
return err2
|
||||
}
|
||||
|
||||
postReq.Header.Set("Powered-By", "https://git.viaeon.com/admin/vupay")
|
||||
resp, err := client.Do(postReq)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
markNotifyFail(order, fmt.Sprintf("resp.StatusCode != 200"))
|
||||
|
||||
return fmt.Errorf("商户系统返回状态码错误:%d(必须是200)", resp.StatusCode)
|
||||
}
|
||||
|
||||
all, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
markNotifyFail(order, fmt.Sprintf("io.ReadAll(resp.Body) Error: %v", err))
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
var bodyStr = strings.ToLower(strings.TrimSpace(string(all)))
|
||||
|
||||
// 判断是否包含 success 或 ok
|
||||
if !strings.Contains(bodyStr, "success") && !strings.Contains(bodyStr, "ok") {
|
||||
markNotifyFail(order, "商户系统必须响应 success 或 ok 才会认定回调成功")
|
||||
|
||||
return fmt.Errorf("商户系统必须响应 success 或 ok 才会认定回调成功,实际响应:%s", string(all))
|
||||
}
|
||||
|
||||
if err = order.SetNotifyState(model.OrderNotifyStateSucc); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func vupay(ctx context.Context, order model.Order) error {
|
||||
var data = make(map[string]interface{})
|
||||
var body = EpNotify{
|
||||
TradeId: order.TradeId,
|
||||
OrderId: order.OrderId,
|
||||
Amount: cast.ToFloat64(order.Money),
|
||||
ActualAmount: order.Amount,
|
||||
Token: order.Address,
|
||||
BlockTransactionId: order.RefHash,
|
||||
Status: order.Status,
|
||||
}
|
||||
var jsonBody, err = json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(jsonBody, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 签名
|
||||
body.Signature = utils.VupaySign(data, model.AuthToken())
|
||||
|
||||
// 再次序列化
|
||||
jsonBody, err = json.Marshal(body)
|
||||
var client = http.Client{Timeout: time.Second * 5}
|
||||
var postReq, err2 = http.NewRequestWithContext(ctx, "POST", order.NotifyUrl, strings.NewReader(string(jsonBody)))
|
||||
if err2 != nil {
|
||||
markNotifyFail(order, err2.Error())
|
||||
|
||||
return err2
|
||||
}
|
||||
|
||||
postReq.Header.Set("Content-Type", "application/json")
|
||||
postReq.Header.Set("Powered-By", "https://git.viaeon.com/admin/vupay")
|
||||
postReq.Header.Set("User-Agent", "VUPAY/"+app.Version)
|
||||
resp, err := client.Do(postReq)
|
||||
if err != nil {
|
||||
markNotifyFail(order, err.Error())
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
markNotifyFail(order, fmt.Sprintf("商户系统返回状态码错误:%d(必须是200)", resp.StatusCode))
|
||||
|
||||
return fmt.Errorf("商户系统返回状态码错误:%d(必须是200)", resp.StatusCode)
|
||||
}
|
||||
|
||||
if err = order.SetNotifyState(model.OrderNotifyStateSucc); err != nil {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func Vupay(o model.Order) {
|
||||
if o.ApiType != model.OrderApiTypeVupay && o.ApiType != model.OrderApiTypeVupayOrder {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var authToken = model.AuthToken()
|
||||
var client = &http.Client{Timeout: time.Second * 5}
|
||||
go func() {
|
||||
if err := deliverVupayStatusUpdate(model.Db, client, authToken, o); err != nil {
|
||||
log.Warn("notify VUPAY Error:", err.Error())
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func deliverVupayStatusUpdate(db *gorm.DB, client *http.Client, authToken string, o model.Order) error {
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: time.Second * 5}
|
||||
}
|
||||
|
||||
var current model.Order
|
||||
tx := db.Where("trade_id = ? and status = ?", o.TradeId, o.Status).Limit(1).Find(¤t)
|
||||
if tx.Error != nil {
|
||||
return tx.Error
|
||||
}
|
||||
if tx.RowsAffected == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var key = fmt.Sprintf("vupay_notify_%d_%s", current.Status, current.TradeId)
|
||||
if _, ok := cache.Get(key); ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
cache.Set(key, true, time.Minute)
|
||||
|
||||
var data = make(map[string]interface{})
|
||||
var body = EpNotify{
|
||||
TradeId: current.TradeId,
|
||||
OrderId: current.OrderId,
|
||||
Amount: cast.ToFloat64(current.Money),
|
||||
ActualAmount: current.Amount,
|
||||
Token: current.Address,
|
||||
BlockTransactionId: current.RefHash,
|
||||
Status: current.Status,
|
||||
}
|
||||
jsonBody, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(jsonBody, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
body.Signature = utils.VupaySign(data, authToken)
|
||||
|
||||
jsonBody, _ = json.Marshal(body)
|
||||
req, err := http.NewRequest("POST", current.NotifyUrl, strings.NewReader(string(jsonBody)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Powered-By", "https://git.viaeon.com/admin/vupay")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return fmt.Errorf("resp.StatusCode != 200")
|
||||
}
|
||||
|
||||
all, _ := io.ReadAll(resp.Body)
|
||||
log.Info(fmt.Sprintf("订单回调成功[%d]:%s %s", current.Status, current.TradeId, string(all)))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func markNotifyFail(o model.Order, reason string) {
|
||||
log.Warn(fmt.Sprintf("订单回调失败(%v):%s %v", o.TradeId, reason, o.SetNotifyState(model.OrderNotifyStateFail)))
|
||||
|
||||
notifier.NotifyFail(o, reason)
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
applog "git.viaeon.com/admin/vupay/app/log"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"github.com/glebarez/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func newNotifyTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
|
||||
dbPath := filepath.Join(t.TempDir(), "notify-test.db")
|
||||
db, err := gorm.Open(sqlite.Open(dbPath+"?cache=shared&mode=rwc&_pragma=journal_mode(WAL)&_pragma=busy_timeout(1000)"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open test db: %v", err)
|
||||
}
|
||||
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
t.Fatalf("get sql db: %v", err)
|
||||
}
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
sqlDB.SetMaxIdleConns(1)
|
||||
|
||||
if err := db.AutoMigrate(&model.Order{}); err != nil {
|
||||
t.Fatalf("auto migrate order: %v", err)
|
||||
}
|
||||
|
||||
return db
|
||||
}
|
||||
|
||||
func initNotifyTestLog(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
if err := applog.Init(filepath.Join(t.TempDir(), "logs")); err != nil {
|
||||
t.Fatalf("init log: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
applog.Close()
|
||||
})
|
||||
}
|
||||
|
||||
func newWaitingOrder(notifyURL string) model.Order {
|
||||
now := time.Now()
|
||||
confirmedAt := now
|
||||
|
||||
return model.Order{
|
||||
OrderId: "merchant-order-1",
|
||||
TradeId: "trade-order-1",
|
||||
TradeType: model.UsdtTrc20,
|
||||
Fiat: "CNY",
|
||||
Crypto: "USDT",
|
||||
Rate: "7.00",
|
||||
Amount: "1.00",
|
||||
Money: "7.00",
|
||||
Address: "TTestAddress1234567890",
|
||||
Status: model.OrderStatusWaiting,
|
||||
ApiType: model.OrderApiTypeVupay,
|
||||
NotifyUrl: notifyURL,
|
||||
ExpiredAt: now.Add(10 * time.Minute),
|
||||
ConfirmedAt: &confirmedAt,
|
||||
AutoTimeAt: model.AutoTimeAt{CreatedAt: (*model.Datetime)(&now), UpdatedAt: (*model.Datetime)(&now)},
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliverVupayStatusUpdateDoesNotHoldDBWhileHTTPIsPending(t *testing.T) {
|
||||
db := newNotifyTestDB(t)
|
||||
initNotifyTestLog(t)
|
||||
|
||||
requestStarted := make(chan struct{}, 1)
|
||||
releaseResponse := make(chan struct{})
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestStarted <- struct{}{}
|
||||
<-releaseResponse
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
order := newWaitingOrder(server.URL)
|
||||
if err := db.Create(&order).Error; err != nil {
|
||||
t.Fatalf("seed order: %v", err)
|
||||
}
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- deliverVupayStatusUpdate(db, &http.Client{Timeout: 2 * time.Second}, "test-auth-token", order)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-requestStarted:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("notification request never reached test server")
|
||||
}
|
||||
|
||||
queryDone := make(chan error, 1)
|
||||
go func() {
|
||||
var count int64
|
||||
queryDone <- db.Model(&model.Order{}).Where("status = ?", model.OrderStatusWaiting).Count(&count).Error
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-queryDone:
|
||||
if err != nil {
|
||||
t.Fatalf("concurrent query failed: %v", err)
|
||||
}
|
||||
case <-time.After(300 * time.Millisecond):
|
||||
close(releaseResponse)
|
||||
<-errCh
|
||||
t.Fatal("database query was blocked while notification HTTP request was in flight")
|
||||
}
|
||||
|
||||
close(releaseResponse)
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatalf("deliver notification: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/smallnest/chanx"
|
||||
)
|
||||
|
||||
func plasmaInit() {
|
||||
ctx := context.Background()
|
||||
xpl := evm{
|
||||
Network: conf.Plasma,
|
||||
Block: block{
|
||||
ConfirmedOffset: 40,
|
||||
},
|
||||
Client: utils.NewHttpClient(),
|
||||
blockScanQueue: chanx.NewUnboundedChan[evmBlock](ctx, 30),
|
||||
}
|
||||
|
||||
Register(Task{Callback: xpl.blockDispatch})
|
||||
Register(Task{Callback: xpl.syncBlocksForward, Duration: time.Second * 5})
|
||||
Register(Task{Callback: xpl.tradeConfirmHandle, Duration: time.Second * 5})
|
||||
Register(Task{Callback: xpl.lookbackBlocks, Duration: time.Second * 15})
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/smallnest/chanx"
|
||||
)
|
||||
|
||||
func polygonInit() {
|
||||
ctx := context.Background()
|
||||
pol := evm{
|
||||
Network: conf.Polygon,
|
||||
Block: block{
|
||||
ConfirmedOffset: 40,
|
||||
},
|
||||
Client: utils.NewHttpClient(),
|
||||
blockScanQueue: chanx.NewUnboundedChan[evmBlock](ctx, 30),
|
||||
}
|
||||
|
||||
Register(Task{Callback: pol.blockDispatch})
|
||||
Register(Task{Callback: pol.syncBlocksForward, Duration: time.Second * 5})
|
||||
Register(Task{Callback: pol.tradeConfirmHandle, Duration: time.Second * 5})
|
||||
Register(Task{Callback: pol.lookbackBlocks, Duration: time.Second * 15})
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var rate = Rate{}
|
||||
|
||||
Register(Task{Duration: time.Hour, Callback: rate.Clear})
|
||||
Register(Task{Duration: time.Second * 5, Callback: rate.Sync})
|
||||
}
|
||||
|
||||
type Rate struct {
|
||||
}
|
||||
|
||||
func (Rate) Sync(ctx context.Context) {
|
||||
var lastAt model.Rate
|
||||
model.Db.Model(&lastAt).Order("id desc").Limit(1).Find(&lastAt)
|
||||
var interval = cast.ToInt64(model.GetC(model.RateSyncInterval))
|
||||
if lastAt.ID != 0 && time.Now().Unix()-lastAt.CreatedAt.Time().Unix() < interval {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err := model.CoingeckoRate()
|
||||
if err != nil {
|
||||
|
||||
log.Warn(fmt.Sprintf("同步汇率失败: %s", err.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
func (Rate) Clear(ctx context.Context) {
|
||||
days := cast.ToInt(model.GetC(model.RateSyncHistoryDays))
|
||||
if days <= 0 {
|
||||
days = 1
|
||||
}
|
||||
|
||||
createdAt := time.Now().AddDate(0, 0, -days)
|
||||
model.Db.Where("created_at < ?", createdAt).Delete(&model.Rate{})
|
||||
}
|
||||
@@ -0,0 +1,654 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
blockapi "git.viaeon.com/admin/vupay/app/core"
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"git.viaeon.com/admin/vupay/app/utils"
|
||||
"github.com/btcsuite/btcd/btcutil/base58"
|
||||
"github.com/panjf2000/ants/v2"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/smallnest/chanx"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// 参考文档
|
||||
// - https://solana.com/zh/docs/rpc
|
||||
// - https://github.com/solana-program/token/blob/6d18ff73b1dd30703a30b1ca941cb0f1d18c2b2a/program/src/instruction.rs
|
||||
|
||||
type solana struct {
|
||||
slotConfirmedOffset int
|
||||
lastSlotNum int
|
||||
forwardIdle bool // 因没有待支付订单而暂停了向前扫描
|
||||
slotQueue *chanx.UnboundedChan[int]
|
||||
client *http.Client
|
||||
retryMu sync.Mutex
|
||||
retryAttempts map[int]int
|
||||
retryScheduled map[int]*time.Timer
|
||||
retryStopped map[int]struct{}
|
||||
lookbackMu sync.Mutex
|
||||
lookbackNext int
|
||||
lookbackEnd int
|
||||
lookbackOrderIDs []int64
|
||||
}
|
||||
|
||||
type solanaTokenOwner struct {
|
||||
TradeType model.TradeType
|
||||
Address string
|
||||
}
|
||||
|
||||
var sol solana
|
||||
|
||||
func init() {
|
||||
sol = newSolana()
|
||||
Register(Task{Callback: sol.slotDispatch})
|
||||
Register(Task{Callback: sol.syncSlotForward, Duration: time.Second * 5})
|
||||
Register(Task{Callback: sol.tradeConfirmHandle, Duration: time.Second * 5})
|
||||
Register(Task{Callback: sol.lookbackSlots, Duration: time.Second * 15})
|
||||
Register(Task{Callback: sol.reconcileExpiredOrders, Duration: time.Minute})
|
||||
}
|
||||
|
||||
func newSolana() solana {
|
||||
return solana{
|
||||
slotConfirmedOffset: 60,
|
||||
lastSlotNum: 0,
|
||||
slotQueue: chanx.NewUnboundedChan[int](context.Background(), 30),
|
||||
client: utils.NewHttpClient(),
|
||||
retryAttempts: make(map[int]int),
|
||||
retryScheduled: make(map[int]*time.Timer),
|
||||
retryStopped: make(map[int]struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func solanaGetBlockPayload(slot int) []byte {
|
||||
return []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"getBlock","params":[%d,{"encoding":"json","maxSupportedTransactionVersion":1,"transactionDetails":"full","rewards":false}]}`, slot))
|
||||
}
|
||||
|
||||
func (s *solana) syncSlotForward(ctx context.Context) {
|
||||
if queued := s.slotQueue.Len(); syncBreak(conf.Solana, queued) {
|
||||
if queued < blockQueueLimit {
|
||||
s.forwardIdle = true
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
if s.pendingSlotRetryCount() >= solanaForwardPauseRetries {
|
||||
return
|
||||
}
|
||||
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", model.Endpoint(conf.Solana), bytes.NewBuffer([]byte(`{"jsonrpc":"2.0","id":1,"method":"getSlot"}`)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
log.Task.Warn("syncSlotForward Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
log.Task.Warn("syncSlotForward Error response status code:", resp.StatusCode)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Task.Warn("syncSlotForward Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
now := int(gjson.GetBytes(body, "result").Int())
|
||||
if now <= 0 {
|
||||
log.Task.Warn("syncSlotForward Error: invalid slot number:", now)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if lag := now - s.lastSlotNum; lag > cast.ToInt(model.GetC(model.BlockHeightMaxDiff)) {
|
||||
if s.lastSlotNum == 0 || s.forwardIdle { // 启动或空闲后恢复扫描:直接从最新高度开始
|
||||
s.lastSlotNum = now
|
||||
} else { // 扫描期间落后:继续追赶,不能跳过,其中可能有付款
|
||||
log.Task.Warn(fmt.Sprintf("Solana 扫描落后 %d 个 slot,继续追赶", lag))
|
||||
}
|
||||
}
|
||||
s.forwardIdle = false
|
||||
|
||||
if now <= s.lastSlotNum { // 区块高度没有变化或节点返回旧高度
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 只填充队列的可用容量;消费后由下一轮继续追赶,避免长时间故障恢复时瞬间过度扫描。
|
||||
for n := s.lastSlotNum + 1; n <= now && s.slotQueue.Len() < blockQueueLimit; n++ {
|
||||
s.slotQueue.In <- n
|
||||
s.lastSlotNum = n
|
||||
}
|
||||
}
|
||||
|
||||
func (s *solana) slotDispatch(ctx context.Context) {
|
||||
p, err := ants.NewPoolWithFunc(3, s.slotParse)
|
||||
if err != nil {
|
||||
log.Task.Warn("Error creating pool:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer p.Release()
|
||||
|
||||
for {
|
||||
select {
|
||||
case slot := <-s.slotQueue.Out:
|
||||
if err := p.Invoke(slot); err != nil {
|
||||
s.slotQueue.In <- slot
|
||||
log.Task.Warn("slotDispatch Error invoking process slot:", err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
if err := ctx.Err(); err != nil {
|
||||
log.Task.Warn("slotDispatch context done:", err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *solana) slotParse(n any) {
|
||||
slot := n.(int)
|
||||
post := solanaGetBlockPayload(slot)
|
||||
network := conf.Solana
|
||||
|
||||
resp, err := s.client.Post(model.Endpoint(conf.Solana), "application/json", bytes.NewBuffer(post))
|
||||
if err != nil {
|
||||
conf.RecordFailure(network)
|
||||
s.scheduleSlotRetry(slot)
|
||||
log.Task.Warn("slotParse Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
conf.RecordFailure(network)
|
||||
s.scheduleSlotRetry(slot)
|
||||
log.Task.Warn("slotParse Error response status code:", resp.StatusCode)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
conf.RecordFailure(network)
|
||||
s.scheduleSlotRetry(slot)
|
||||
log.Task.Warn("slotParse Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
result, err := validateSolanaBlockResponse(body)
|
||||
if errors.Is(err, errSolanaBlockCleanedUp) { // 节点已清理该 slot,重试也拿不到;放弃,不暂停向前扫描
|
||||
conf.RecordFailure(network)
|
||||
s.stopSlotRetry(slot)
|
||||
log.Task.Error(fmt.Sprintf("Solana slot %d 已被节点清理,无法扫描,该 slot 内的付款需要人工核对:%s", slot, err))
|
||||
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
conf.RecordFailure(network)
|
||||
s.scheduleSlotRetry(slot)
|
||||
log.Task.Warn("slotParse Error JSON-RPC response:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
conf.RecordSuccess(network, cast.ToString(slot))
|
||||
s.resetSlotRetry(slot)
|
||||
if result.Type == gjson.Null {
|
||||
log.Task.Info(fmt.Sprintf("区块已跳过(Solana) %d 成功率:%s", slot, conf.GetSuccessRate(network)))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
timestamp := time.Unix(result.Get("blockTime").Int(), 0)
|
||||
|
||||
for _, trans := range result.Get("transactions").Array() {
|
||||
if transfers := s.parseTransaction(trans, slot, timestamp); len(transfers) > 0 {
|
||||
transferQueue.In <- transfers
|
||||
}
|
||||
}
|
||||
|
||||
log.Task.Info(fmt.Sprintf("区块扫描完成(Solana) %d 成功率:%s", slot, conf.GetSuccessRate(network)))
|
||||
}
|
||||
|
||||
// parseTransaction 解析单笔交易中的 USDT/USDC 转账;getBlock 返回的交易项与 getTransaction 的结果结构相同,都可以传入
|
||||
func (s *solana) parseTransaction(trans gjson.Result, slot int, timestamp time.Time) []transfer {
|
||||
if !solanaTxSucceeded(trans.Get("meta.err")) {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
hash := trans.Get("transaction.signatures.0").String()
|
||||
|
||||
// 解析账号索引
|
||||
accountKeys := make([]string, 0)
|
||||
for _, key := range trans.Get("transaction.message.accountKeys").Array() {
|
||||
accountKeys = append(accountKeys, key.String())
|
||||
}
|
||||
for _, v := range []string{"readonly", "writable"} {
|
||||
for _, key := range trans.Get("meta.loadedAddresses." + v).Array() {
|
||||
accountKeys = append(accountKeys, key.String())
|
||||
}
|
||||
}
|
||||
|
||||
// 查找SPL Token索引
|
||||
splTokenIndex := int64(-1)
|
||||
for i, v := range accountKeys {
|
||||
if v == conf.SolSplToken {
|
||||
splTokenIndex = int64(i)
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// SPL Token的Mint地址,即不包含 Token 交易信息
|
||||
if splTokenIndex == -1 {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// 解析 Token 账户 【Token Wallet => Owner Wallet】
|
||||
tokenAccountMap := make(map[string]solanaTokenOwner)
|
||||
for _, v := range []string{"postTokenBalances", "preTokenBalances"} {
|
||||
for _, itm := range trans.Get("meta." + v).Array() {
|
||||
tradeType, ok := model.GetContractTrade(itm.Get("mint").String())
|
||||
if !ok || itm.Get("programId").String() != conf.SolSplToken {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
tokenAccountMap[accountKeys[itm.Get("accountIndex").Int()]] = solanaTokenOwner{
|
||||
TradeType: tradeType,
|
||||
Address: itm.Get("owner").String(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
transArr := make([]transfer, 0)
|
||||
|
||||
// 解析外部指令
|
||||
for _, instr := range trans.Get("transaction.message.instructions").Array() {
|
||||
if instr.Get("programIdIndex").Int() != splTokenIndex {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transArr = append(transArr, s.parseTransfer(instr, accountKeys, tokenAccountMap))
|
||||
}
|
||||
|
||||
// 解析内部指令
|
||||
for _, itm := range trans.Get("meta.innerInstructions").Array() {
|
||||
for _, instr := range itm.Get("instructions").Array() {
|
||||
if instr.Get("programIdIndex").Int() != splTokenIndex {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transArr = append(transArr, s.parseTransfer(instr, accountKeys, tokenAccountMap))
|
||||
}
|
||||
}
|
||||
|
||||
// 过滤无关交易
|
||||
result := make([]transfer, 0)
|
||||
for _, t := range transArr {
|
||||
if t.FromAddress == "" || t.RecvAddress == "" || t.Amount.IsZero() {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
t.TxHash = hash
|
||||
t.Network = conf.Solana
|
||||
t.BlockNum = slot
|
||||
t.Timestamp = timestamp
|
||||
|
||||
result = append(result, t)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// 执行失败的交易同样会被打包进区块,指令和代币余额也照常保留,但转账已经回滚;只有 err 为 null 才算执行成功
|
||||
func solanaTxSucceeded(err gjson.Result) bool {
|
||||
return err.Exists() && err.Type == gjson.Null
|
||||
}
|
||||
|
||||
// getSignatureStatuses 对执行失败的交易同样返回 finalized,必须同时检查 err
|
||||
func solanaSignatureFinalized(status gjson.Result) bool {
|
||||
return status.Get("confirmationStatus").String() == "finalized" && solanaTxSucceeded(status.Get("err"))
|
||||
}
|
||||
|
||||
// Solana JSON-RPC 错误码,参考 https://github.com/anza-xyz/agave/blob/master/rpc-client-api/src/custom_error.rs
|
||||
const (
|
||||
solanaErrBlockCleanedUp = -32001
|
||||
solanaErrSlotSkipped = -32007
|
||||
solanaErrLongTermStorageSlotSkipped = -32009
|
||||
)
|
||||
|
||||
// 节点只保留最近一段时间的区块,更早的 slot 返回 -32001,换一个时间重试也不会有
|
||||
var errSolanaBlockCleanedUp = errors.New("block cleaned up")
|
||||
|
||||
func validateSolanaBlockResponse(body []byte) (gjson.Result, error) {
|
||||
if !gjson.ValidBytes(body) {
|
||||
return gjson.Result{}, fmt.Errorf("invalid JSON response")
|
||||
}
|
||||
|
||||
data := gjson.ParseBytes(body)
|
||||
if rpcErr := data.Get("error"); rpcErr.Exists() {
|
||||
switch rpcErr.Get("code").Int() {
|
||||
case solanaErrSlotSkipped, solanaErrLongTermStorageSlotSkipped: // 被跳过的 slot 没有区块,按空 slot 处理
|
||||
return gjson.Result{Type: gjson.Null}, nil
|
||||
case solanaErrBlockCleanedUp:
|
||||
return gjson.Result{}, fmt.Errorf("%w: %s", errSolanaBlockCleanedUp, rpcErr.Raw)
|
||||
}
|
||||
|
||||
return gjson.Result{}, fmt.Errorf("RPC error: %s", rpcErr.Raw)
|
||||
}
|
||||
|
||||
result := data.Get("result")
|
||||
if !result.Exists() {
|
||||
return gjson.Result{}, fmt.Errorf("missing result")
|
||||
}
|
||||
if result.Type != gjson.Null && !result.Get("transactions").Exists() {
|
||||
return gjson.Result{}, fmt.Errorf("missing result.transactions")
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *solana) scheduleSlotRetry(slot int) {
|
||||
s.retryMu.Lock()
|
||||
if _, stopped := s.retryStopped[slot]; stopped {
|
||||
s.retryMu.Unlock()
|
||||
|
||||
return
|
||||
}
|
||||
if _, ok := s.retryScheduled[slot]; ok {
|
||||
s.retryMu.Unlock()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
attempt := s.retryAttempts[slot] + 1
|
||||
if attempt > solanaSlotMaxRetries { // 放弃该 slot,否则向前扫描会一直暂停
|
||||
delete(s.retryAttempts, slot)
|
||||
s.retryMu.Unlock()
|
||||
log.Task.Error(fmt.Sprintf("Solana slot %d 连续 %d 次扫描失败,已放弃,该 slot 内的付款需要人工核对", slot, solanaSlotMaxRetries))
|
||||
|
||||
return
|
||||
}
|
||||
s.retryAttempts[slot] = attempt
|
||||
|
||||
// 待重试的 slot 数量有限,到期直接入队;不再因队列堆积而延后,否则堆积会被计为失败次数
|
||||
var timer *time.Timer
|
||||
timer = time.AfterFunc(solanaRetryDelay(attempt), func() {
|
||||
s.retryMu.Lock()
|
||||
if s.retryScheduled[slot] != timer {
|
||||
s.retryMu.Unlock()
|
||||
|
||||
return
|
||||
}
|
||||
delete(s.retryScheduled, slot)
|
||||
s.retryMu.Unlock()
|
||||
|
||||
s.slotQueue.In <- slot
|
||||
})
|
||||
s.retryScheduled[slot] = timer
|
||||
s.retryMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *solana) stopSlotRetry(slot int) {
|
||||
s.retryMu.Lock()
|
||||
delete(s.retryAttempts, slot)
|
||||
if timer, ok := s.retryScheduled[slot]; ok {
|
||||
timer.Stop()
|
||||
delete(s.retryScheduled, slot)
|
||||
}
|
||||
s.retryStopped[slot] = struct{}{}
|
||||
s.retryMu.Unlock()
|
||||
|
||||
// 防止同一 slot 的并发请求在终态响应之后重新建立重试;并发请求结束后无需长期保留。
|
||||
time.AfterFunc(time.Minute, func() {
|
||||
s.retryMu.Lock()
|
||||
delete(s.retryStopped, slot)
|
||||
s.retryMu.Unlock()
|
||||
})
|
||||
}
|
||||
|
||||
func (s *solana) resetSlotRetry(slot int) {
|
||||
s.retryMu.Lock()
|
||||
defer s.retryMu.Unlock()
|
||||
|
||||
delete(s.retryAttempts, slot)
|
||||
if timer, ok := s.retryScheduled[slot]; ok {
|
||||
timer.Stop()
|
||||
delete(s.retryScheduled, slot)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *solana) pendingSlotRetryCount() int {
|
||||
s.retryMu.Lock()
|
||||
defer s.retryMu.Unlock()
|
||||
|
||||
return len(s.retryAttempts)
|
||||
}
|
||||
|
||||
// 单个 slot 最多重试 10 次,按 solanaRetryDelay 约 7 分钟
|
||||
const solanaSlotMaxRetries = 10
|
||||
|
||||
// 待重试的 slot 达到这个数量,说明节点整体故障,暂停向前扫描,避免新 slot 不断进入重试;
|
||||
// 个别 slot 失败时继续向前扫描,否则一个 slot 的重试会让之后的付款最多等约 7 分钟
|
||||
const solanaForwardPauseRetries = 10
|
||||
|
||||
func solanaRetryDelay(attempt int) time.Duration {
|
||||
delays := [...]time.Duration{2 * time.Second, 5 * time.Second, 15 * time.Second, 30 * time.Second, time.Minute}
|
||||
if attempt < 1 {
|
||||
attempt = 1
|
||||
}
|
||||
if attempt > len(delays) {
|
||||
attempt = len(delays)
|
||||
}
|
||||
|
||||
return delays[attempt-1]
|
||||
}
|
||||
|
||||
func (s *solana) parseTransfer(instr gjson.Result, accountKeys []string, tokenAccountMap map[string]solanaTokenOwner) transfer {
|
||||
accounts := instr.Get("accounts").Array()
|
||||
trans := transfer{}
|
||||
if len(accounts) < 3 { // from to singer,至少存在3个账户索引,如果是多签则 > 3
|
||||
|
||||
return trans
|
||||
}
|
||||
|
||||
data := base58.Decode(instr.Get("data").String())
|
||||
dLen := len(data)
|
||||
if dLen < 9 {
|
||||
|
||||
return trans
|
||||
}
|
||||
|
||||
isTransfer := data[0] == 3 && dLen == 9
|
||||
isTransferChecked := data[0] == 12 && dLen == 10
|
||||
if !isTransfer && !isTransferChecked {
|
||||
|
||||
return trans
|
||||
}
|
||||
|
||||
var exp int32 = -6
|
||||
if isTransferChecked {
|
||||
exp = int32(data[9]) * -1
|
||||
}
|
||||
|
||||
from, ok := tokenAccountMap[accountKeys[accounts[0].Int()]]
|
||||
if !ok {
|
||||
|
||||
return trans
|
||||
}
|
||||
|
||||
trans.FromAddress = from.Address
|
||||
trans.RecvAddress = tokenAccountMap[accountKeys[accounts[1].Int()]].Address
|
||||
if isTransferChecked {
|
||||
trans.RecvAddress = tokenAccountMap[accountKeys[accounts[2].Int()]].Address
|
||||
}
|
||||
|
||||
buf := make([]byte, 8)
|
||||
copy(buf[:], data[1:9])
|
||||
number := binary.LittleEndian.Uint64(buf)
|
||||
b := new(big.Int)
|
||||
b.SetUint64(number)
|
||||
trans.TradeType = from.TradeType
|
||||
trans.Amount = decimal.NewFromBigInt(b, exp)
|
||||
|
||||
return trans
|
||||
}
|
||||
|
||||
func (s *solana) tradeConfirmHandle(ctx context.Context) {
|
||||
var orders = getConfirmingOrders(model.GetNetworkTrades(conf.Solana))
|
||||
var wg sync.WaitGroup
|
||||
|
||||
var handle = func(o model.Order) {
|
||||
post := []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"getSignatureStatuses","params":[["%s"],{"searchTransactionHistory":true}]}`, o.RefHash))
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", model.Endpoint(conf.Solana), bytes.NewBuffer(post))
|
||||
resp, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
log.Task.Warn("solana tradeConfirmHandle Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
log.Task.Warn("solana tradeConfirmHandle Error response status code:", resp.StatusCode)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Task.Warn("solana tradeConfirmHandle Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
data := gjson.ParseBytes(body)
|
||||
if data.Get("error").Exists() {
|
||||
log.Task.Warn("solana tradeConfirmHandle Error:", data.Get("error").String())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 用同一响应里节点当前的 slot 计算确认数,不依赖向前扫描进度:扫描在没有待支付订单时会暂停,重启后为 0
|
||||
if model.GetC(model.BlockOffsetConfirm) == "1" && data.Get("result.context.slot").Int()-int64(o.RefBlockNum) < int64(s.slotConfirmedOffset) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if solanaSignatureFinalized(data.Get("result.value.0")) {
|
||||
|
||||
markFinalConfirmed(o)
|
||||
}
|
||||
}
|
||||
|
||||
for _, order := range orders {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
handle(order)
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func (s *solana) lookbackSlots(ctx context.Context) {
|
||||
s.lookbackMu.Lock()
|
||||
defer s.lookbackMu.Unlock()
|
||||
|
||||
// 回溯到一半时订单已支付、取消,或已超出回溯时间,剩余区间不再需要。扫描空闲时这里不会执行到下面,
|
||||
// 不清空的话进度会一直保留,下一笔订单到来时接着扫这段旧 slot,节点可能早已清理
|
||||
if s.lookbackNext != 0 {
|
||||
pending, err := lookbackOrdersPending(s.lookbackOrderIDs)
|
||||
if err != nil { // 查询失败不等于订单已结束,保留进度,下一轮再判断
|
||||
log.Task.Warn("Solana 回溯订单查询失败,稍后重试:", err)
|
||||
|
||||
return
|
||||
}
|
||||
if !pending {
|
||||
log.Task.Info(fmt.Sprintf("Solana 回溯的订单已不需要回溯,丢弃剩余回溯区间 %d-%d", s.lookbackNext, s.lookbackEnd))
|
||||
s.resetLookback()
|
||||
}
|
||||
}
|
||||
|
||||
if syncBreak(conf.Solana, s.slotQueue.Len()) {
|
||||
return
|
||||
}
|
||||
|
||||
if s.lookbackNext == 0 {
|
||||
startAt, endAt, orderIDs, ok := pendingLookbackUnix(conf.Solana)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
start, end := blockapi.New().GetBoundaryHeights(startAt, endAt, conf.Solana)
|
||||
if !validSolanaLookbackRange(start, end) {
|
||||
log.Task.Warn("Solana 回溯区块范围无效,稍后重试:", start, "-", end)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
s.lookbackNext = int(start)
|
||||
s.lookbackEnd = int(end)
|
||||
s.lookbackOrderIDs = orderIDs
|
||||
}
|
||||
|
||||
for s.lookbackNext <= s.lookbackEnd && s.slotQueue.Len() < blockQueueLimit {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
s.slotQueue.In <- s.lookbackNext
|
||||
s.lookbackNext++
|
||||
}
|
||||
|
||||
if s.lookbackNext > s.lookbackEnd {
|
||||
markLookbackDone(s.lookbackOrderIDs)
|
||||
s.resetLookback()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *solana) resetLookback() {
|
||||
s.lookbackNext = 0
|
||||
s.lookbackEnd = 0
|
||||
s.lookbackOrderIDs = nil
|
||||
}
|
||||
|
||||
func validSolanaLookbackRange(start, end int64) bool {
|
||||
return start > 0 && end >= start
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
)
|
||||
|
||||
func TestSolanaConfirmOffsetUsesRPCSlot(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
confirmations int
|
||||
want int
|
||||
}{
|
||||
{name: "enough confirmations", confirmations: 100, want: model.OrderStatusSuccess},
|
||||
{name: "waiting for confirmations", confirmations: 25, want: model.OrderStatusConfirming},
|
||||
}
|
||||
|
||||
const slot = 451914288
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/notify" {
|
||||
_, _ = w.Write([]byte("ok"))
|
||||
|
||||
return
|
||||
}
|
||||
// 主网 getSignatureStatuses 对该交易的真实返回,只改 context.slot
|
||||
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":{"context":{"slot":%d},"value":[{"confirmationStatus":"finalized","confirmations":null,"err":null,"slot":%d,"status":{"Ok":null}}]},"id":1}`, slot+tt.confirmations, slot)
|
||||
}))
|
||||
defer srv.Close()
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL, model.BlockOffsetConfirm: "1"})
|
||||
|
||||
order := createTestOrder(t, model.Order{
|
||||
OrderId: "merchant-order-1",
|
||||
TradeId: "trade-order-1",
|
||||
TradeType: model.UsdcSolana,
|
||||
Rate: "7.00",
|
||||
Amount: "390.990618",
|
||||
Money: "2736.93",
|
||||
Address: "F7p3dFrjRTbtRp8FRF6qHLomXbKRBzpvBLjtQcfcgmNe",
|
||||
Status: model.OrderStatusConfirming,
|
||||
ApiType: model.OrderApiTypeVupay,
|
||||
NotifyUrl: srv.URL + "/notify",
|
||||
RefHash: "DohbsAfxAerDTAX9XS1b9jXY5XYMXQsCnyY3qu42eEEcTeJ6UzMbFs3JTdY14QgNKQPdy6yezdgbqLbnRVj6YB6",
|
||||
RefBlockNum: slot,
|
||||
ExpiredAt: time.Now().Add(10 * time.Minute),
|
||||
}, time.Now().Add(-time.Minute))
|
||||
|
||||
s := newSolana() // lastSlotNum 为 0,相当于重启后或扫描已暂停
|
||||
s.tradeConfirmHandle(t.Context())
|
||||
|
||||
if got := getTestOrder(t, order.TradeId).Status; got != tt.want {
|
||||
t.Fatalf("order status = %d, want %d", got, tt.want)
|
||||
}
|
||||
if tt.want == model.OrderStatusSuccess {
|
||||
waitOrderNotified(t, order.TradeId)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func scanSolanaTestBlock(t *testing.T, block []byte) []transfer {
|
||||
t.Helper()
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write(block)
|
||||
}))
|
||||
defer srv.Close()
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
|
||||
|
||||
s := newSolana()
|
||||
s.slotParse(solanaFixtureSlot(block))
|
||||
|
||||
return drainTransferQueue()
|
||||
}
|
||||
|
||||
func TestSolanaTxSucceeded(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
tx string
|
||||
want bool
|
||||
}{
|
||||
{name: "succeeded", tx: `{"meta":{"err":null}}`, want: true},
|
||||
{name: "instruction error", tx: `{"meta":{"err":{"InstructionError":[1,{"Custom":6001}]}}}`},
|
||||
{name: "missing err", tx: `{"meta":{}}`},
|
||||
{name: "missing meta", tx: `{"meta":null}`},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := solanaTxSucceeded(gjson.Get(tt.tx, "meta.err")); got != tt.want {
|
||||
t.Fatalf("solanaTxSucceeded = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaSlotParseSkipsFailedTransactions(t *testing.T) {
|
||||
tests := []struct {
|
||||
fixture string
|
||||
// 把 meta.err 改为 null 后应解析出的转账数,证明没有转账只是因为交易失败
|
||||
transfersIfSucceeded int
|
||||
}{
|
||||
{fixture: "failed_v1_transfer.json", transfersIfSucceeded: 3},
|
||||
{fixture: "failed_v0_inner_transfer.json", transfersIfSucceeded: 1},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.fixture, func(t *testing.T) {
|
||||
block := readSolanaFixture(t, tt.fixture)
|
||||
if got := scanSolanaTestBlock(t, block); len(got) != 0 {
|
||||
t.Fatalf("failed transaction produced %d transfers: %+v", len(got), got)
|
||||
}
|
||||
|
||||
errRaw := gjson.GetBytes(block, "result.transactions.0.meta.err").Raw
|
||||
succeeded := bytes.Replace(block, []byte(`"err":`+errRaw), []byte(`"err":null`), 1)
|
||||
if bytes.Equal(succeeded, block) {
|
||||
t.Fatalf("fixture has no meta.err to clear")
|
||||
}
|
||||
if got := scanSolanaTestBlock(t, succeeded); len(got) != tt.transfersIfSucceeded {
|
||||
t.Fatalf("transfers = %d, want %d", len(got), tt.transfersIfSucceeded)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaSlotParseKeepsSucceededTransactions(t *testing.T) {
|
||||
got := scanSolanaTestBlock(t, readSolanaFixture(t, "success_v0_inner_transfer.json"))
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("transfers = %d, want 1", len(got))
|
||||
}
|
||||
|
||||
tr := got[0]
|
||||
if tr.TxHash != "DohbsAfxAerDTAX9XS1b9jXY5XYMXQsCnyY3qu42eEEcTeJ6UzMbFs3JTdY14QgNKQPdy6yezdgbqLbnRVj6YB6" ||
|
||||
tr.TradeType != model.UsdcSolana ||
|
||||
tr.RecvAddress != "F7p3dFrjRTbtRp8FRF6qHLomXbKRBzpvBLjtQcfcgmNe" ||
|
||||
tr.Amount.String() != "390.990618" {
|
||||
t.Fatalf("unexpected transfer: %+v", tr)
|
||||
}
|
||||
}
|
||||
|
||||
// 主网 getSignatureStatuses 的真实返回
|
||||
const (
|
||||
solanaFailedSignatureStatus = `{"confirmationStatus":"finalized","confirmations":null,"err":{"InstructionError":[1,{"Custom":6001}]},"slot":458281527,"status":{"Err":{"InstructionError":[1,{"Custom":6001}]}}}`
|
||||
solanaSucceededSignatureStatus = `{"confirmationStatus":"finalized","confirmations":null,"err":null,"slot":451914288,"status":{"Ok":null}}`
|
||||
)
|
||||
|
||||
func TestSolanaSignatureFinalized(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status string
|
||||
want bool
|
||||
}{
|
||||
{name: "finalized", status: solanaSucceededSignatureStatus, want: true},
|
||||
{name: "finalized but failed", status: solanaFailedSignatureStatus},
|
||||
{name: "confirmed", status: `{"confirmationStatus":"confirmed","confirmations":12,"err":null,"slot":451914288,"status":{"Ok":null}}`},
|
||||
{name: "not found", status: `null`},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := solanaSignatureFinalized(gjson.Parse(tt.status)); got != tt.want {
|
||||
t.Fatalf("solanaSignatureFinalized = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaTradeConfirmIgnoresFailedTransaction(t *testing.T) {
|
||||
var notified atomic.Bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/notify" {
|
||||
notified.Store(true)
|
||||
_, _ = w.Write([]byte("ok"))
|
||||
|
||||
return
|
||||
}
|
||||
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":{"context":{"slot":458281967},"value":[%s]},"id":1}`, solanaFailedSignatureStatus)
|
||||
}))
|
||||
defer srv.Close()
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
|
||||
|
||||
order := createTestOrder(t, model.Order{
|
||||
OrderId: "merchant-order-1",
|
||||
TradeId: "trade-order-1",
|
||||
TradeType: model.UsdcSolana,
|
||||
Rate: "7.00",
|
||||
Amount: "225.966818",
|
||||
Money: "1581.77",
|
||||
Address: "GpsvqTPP7triXkqH8mVtXEM6at9DJ41UHy5dYPTFe16H",
|
||||
Status: model.OrderStatusConfirming,
|
||||
ApiType: model.OrderApiTypeVupay,
|
||||
NotifyUrl: srv.URL + "/notify",
|
||||
RefHash: "53bZ2UeqMGryYjbjKgB2nAo8umAMsPTP4dzBhR94SdV7f4YaxDvWqEdL5WQ46JSHsmLph3hBmEdHzTMdnYKMsbRz",
|
||||
RefBlockNum: 458281527,
|
||||
ExpiredAt: time.Now().Add(10 * time.Minute),
|
||||
}, time.Now().Add(-time.Minute))
|
||||
|
||||
s := newSolana()
|
||||
s.tradeConfirmHandle(t.Context())
|
||||
|
||||
if got := getTestOrder(t, order.TradeId); got.Status != model.OrderStatusConfirming {
|
||||
t.Fatalf("order status = %d after failed transaction, want confirming", got.Status)
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
if notified.Load() {
|
||||
t.Fatalf("callback sent for failed transaction")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
)
|
||||
|
||||
// 模拟 n 个 slot 正在等待重试
|
||||
func (s *solana) setPendingSlotRetries(first, n int) {
|
||||
s.retryMu.Lock()
|
||||
defer s.retryMu.Unlock()
|
||||
|
||||
for slot := first; slot < first+n; slot++ {
|
||||
s.retryAttempts[slot] = 1
|
||||
}
|
||||
}
|
||||
|
||||
// 一个 slot 在等待重试时,向前扫描照常推进,之后的付款不用等它重试完
|
||||
func TestSolanaForwardContinuesWhileFewSlotsRetry(t *testing.T) {
|
||||
var head atomic.Int64
|
||||
srv := newSolanaSlotTestServer(t, &head)
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL, model.BlockHeightMaxDiff: fmt.Sprint(solanaTestMaxDiff)})
|
||||
createSolanaWaitingOrder(t)
|
||||
|
||||
const last = 458000000
|
||||
s := newSolana()
|
||||
s.lastSlotNum = last
|
||||
s.setPendingSlotRetries(last-9, solanaForwardPauseRetries-1)
|
||||
head.Store(last + 5)
|
||||
s.syncSlotForward(t.Context())
|
||||
|
||||
if s.lastSlotNum != last+5 {
|
||||
t.Fatalf("lastSlotNum = %d, want %d: forward sync paused by one slot retry", s.lastSlotNum, last+5)
|
||||
}
|
||||
select {
|
||||
case got := <-s.slotQueue.Out:
|
||||
if got != last+1 {
|
||||
t.Fatalf("first queued slot = %d, want %d", got, last+1)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatalf("no slot queued while one slot retries")
|
||||
}
|
||||
}
|
||||
|
||||
// 很多 slot 同时等待重试,说明节点整体故障,暂停向前扫描
|
||||
func TestSolanaForwardPausesWhileManySlotsRetry(t *testing.T) {
|
||||
var head atomic.Int64
|
||||
srv := newSolanaSlotTestServer(t, &head)
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL, model.BlockHeightMaxDiff: fmt.Sprint(solanaTestMaxDiff)})
|
||||
createSolanaWaitingOrder(t)
|
||||
|
||||
const last = 458000000
|
||||
s := newSolana()
|
||||
s.lastSlotNum = last
|
||||
s.setPendingSlotRetries(last-solanaForwardPauseRetries, solanaForwardPauseRetries)
|
||||
head.Store(last + 5)
|
||||
s.syncSlotForward(t.Context())
|
||||
|
||||
if s.lastSlotNum != last || s.slotQueue.Len() != 0 {
|
||||
t.Fatalf("lastSlotNum = %d, queued = %d; want forward sync paused at %d", s.lastSlotNum, s.slotQueue.Len(), last)
|
||||
}
|
||||
|
||||
s.resetSlotRetry(last - solanaForwardPauseRetries)
|
||||
s.syncSlotForward(t.Context())
|
||||
if s.lastSlotNum != last+5 {
|
||||
t.Fatalf("lastSlotNum = %d after retries dropped below threshold, want %d", s.lastSlotNum, last+5)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
)
|
||||
|
||||
func newSolanaSlotTestServer(t *testing.T, head *atomic.Int64) *httptest.Server {
|
||||
t.Helper()
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":%d,"id":1}`, head.Load())
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
return srv
|
||||
}
|
||||
|
||||
func createSolanaWaitingOrder(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
createTestOrder(t, model.Order{
|
||||
OrderId: "merchant-order-1",
|
||||
TradeId: "trade-order-1",
|
||||
TradeType: model.UsdcSolana,
|
||||
Rate: "7.00",
|
||||
Amount: "1.23",
|
||||
Money: "8.61",
|
||||
Address: "GpsvqTPP7triXkqH8mVtXEM6at9DJ41UHy5dYPTFe16H",
|
||||
Status: model.OrderStatusWaiting,
|
||||
ApiType: model.OrderApiTypeVupay,
|
||||
ExpiredAt: time.Now().Add(10 * time.Minute),
|
||||
}, time.Now().Add(-time.Minute))
|
||||
}
|
||||
|
||||
// 落后阈值设为 10,用 20 个 slot 的落后量验证,队列不会超过 chanx 的初始容量
|
||||
const solanaTestMaxDiff = 10
|
||||
|
||||
func TestSolanaForwardCatchesUpWhileOrdersActive(t *testing.T) {
|
||||
var head atomic.Int64
|
||||
srv := newSolanaSlotTestServer(t, &head)
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL, model.BlockHeightMaxDiff: fmt.Sprint(solanaTestMaxDiff)})
|
||||
createSolanaWaitingOrder(t)
|
||||
|
||||
const last = 458000000
|
||||
s := newSolana()
|
||||
s.lastSlotNum = last
|
||||
head.Store(last + 2*solanaTestMaxDiff)
|
||||
s.syncSlotForward(t.Context())
|
||||
|
||||
if s.lastSlotNum != last+2*solanaTestMaxDiff {
|
||||
t.Fatalf("lastSlotNum = %d, want %d", s.lastSlotNum, last+2*solanaTestMaxDiff)
|
||||
}
|
||||
select {
|
||||
case got := <-s.slotQueue.Out:
|
||||
if got != last+1 {
|
||||
t.Fatalf("first queued slot = %d, want %d: slots were skipped", got, last+1)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatalf("no slot queued: slots %d-%d were skipped", last+1, last+2*solanaTestMaxDiff)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaForwardSkipsAfterIdle(t *testing.T) {
|
||||
var head atomic.Int64
|
||||
srv := newSolanaSlotTestServer(t, &head)
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL, model.BlockHeightMaxDiff: fmt.Sprint(solanaTestMaxDiff)})
|
||||
|
||||
const last = 458000000
|
||||
s := newSolana()
|
||||
s.lastSlotNum = last
|
||||
head.Store(last + 2*solanaTestMaxDiff)
|
||||
s.syncSlotForward(t.Context()) // 没有订单,暂停扫描
|
||||
if s.lastSlotNum != last {
|
||||
t.Fatalf("lastSlotNum = %d while idle, want %d", s.lastSlotNum, last)
|
||||
}
|
||||
|
||||
createSolanaWaitingOrder(t)
|
||||
s.syncSlotForward(t.Context())
|
||||
if s.lastSlotNum != last+2*solanaTestMaxDiff || s.slotQueue.Len() != 0 {
|
||||
t.Fatalf("lastSlotNum = %d, queued = %d; want a jump to %d after idle", s.lastSlotNum, s.slotQueue.Len(), last+2*solanaTestMaxDiff)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaForwardSkipsOnStartup(t *testing.T) {
|
||||
var head atomic.Int64
|
||||
srv := newSolanaSlotTestServer(t, &head)
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL, model.BlockHeightMaxDiff: fmt.Sprint(solanaTestMaxDiff)})
|
||||
createSolanaWaitingOrder(t)
|
||||
|
||||
s := newSolana()
|
||||
head.Store(458000000)
|
||||
s.syncSlotForward(t.Context())
|
||||
if s.lastSlotNum != 458000000 || s.slotQueue.Len() != 0 {
|
||||
t.Fatalf("lastSlotNum = %d, queued = %d; want a jump to the latest slot on startup", s.lastSlotNum, s.slotQueue.Len())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
)
|
||||
|
||||
func createSolanaLookbackOrder(t *testing.T, tradeID string, status int) model.Order {
|
||||
t.Helper()
|
||||
|
||||
return createTestOrder(t, model.Order{
|
||||
OrderId: "merchant-" + tradeID,
|
||||
TradeId: tradeID,
|
||||
TradeType: model.UsdcSolana,
|
||||
Rate: "7.00",
|
||||
Amount: "1.23",
|
||||
Money: "8.61",
|
||||
Address: "GpsvqTPP7triXkqH8mVtXEM6at9DJ41UHy5dYPTFe16H",
|
||||
Status: status,
|
||||
ApiType: model.OrderApiTypeVupay,
|
||||
ExpiredAt: time.Now().Add(10 * time.Minute),
|
||||
}, time.Now().Add(-time.Minute))
|
||||
}
|
||||
|
||||
// 上一笔订单回溯到一半就取消了;一周后新订单到来时,不能接着扫上一笔订单留下的旧 slot
|
||||
func TestSolanaLookbackDropsRangeOfFinishedOrders(t *testing.T) {
|
||||
initTaskTestEnv(t, nil)
|
||||
lookbackDone.Clear()
|
||||
|
||||
canceled := createSolanaLookbackOrder(t, "lookback-canceled", model.OrderStatusCanceled)
|
||||
waiting := createSolanaLookbackOrder(t, "lookback-waiting", model.OrderStatusWaiting)
|
||||
lookbackDone.Store(waiting.ID, struct{}{}) // 新订单的回溯不在本测试范围,避免请求区块高度接口
|
||||
|
||||
s := newSolana()
|
||||
s.lookbackNext, s.lookbackEnd, s.lookbackOrderIDs = 459552217, 459552221, []int64{canceled.ID}
|
||||
s.lookbackSlots(t.Context())
|
||||
|
||||
select {
|
||||
case slot := <-s.slotQueue.Out:
|
||||
t.Fatalf("queued slot %d from the range of a canceled order", slot)
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
}
|
||||
if s.lookbackNext != 0 || s.lookbackEnd != 0 || s.lookbackOrderIDs != nil {
|
||||
t.Fatalf("lookback progress kept: next = %d, end = %d, orders = %v", s.lookbackNext, s.lookbackEnd, s.lookbackOrderIDs)
|
||||
}
|
||||
}
|
||||
|
||||
// 查询订单失败时不能当作订单已结束,保留进度,下一轮再判断
|
||||
func TestSolanaLookbackKeepsRangeOnDatabaseError(t *testing.T) {
|
||||
initTaskTestEnv(t, nil)
|
||||
lookbackDone.Clear()
|
||||
|
||||
waiting := createSolanaLookbackOrder(t, "lookback-waiting", model.OrderStatusWaiting)
|
||||
|
||||
const start, end = 462296900, 462296904
|
||||
s := newSolana()
|
||||
s.lookbackNext, s.lookbackEnd, s.lookbackOrderIDs = start, end, []int64{waiting.ID}
|
||||
db, err := model.Db.DB()
|
||||
if err != nil {
|
||||
t.Fatalf("get db: %v", err)
|
||||
}
|
||||
if err := db.Close(); err != nil {
|
||||
t.Fatalf("close db: %v", err)
|
||||
}
|
||||
s.lookbackSlots(t.Context())
|
||||
|
||||
if s.lookbackNext != start || s.lookbackEnd != end {
|
||||
t.Fatalf("lookback progress dropped on a database error: next = %d, end = %d", s.lookbackNext, s.lookbackEnd)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaLookbackResumesRangeOfPendingOrders(t *testing.T) {
|
||||
initTaskTestEnv(t, nil)
|
||||
lookbackDone.Clear()
|
||||
|
||||
waiting := createSolanaLookbackOrder(t, "lookback-waiting", model.OrderStatusWaiting)
|
||||
|
||||
const start, end = 462296900, 462296904
|
||||
s := newSolana()
|
||||
s.lookbackNext, s.lookbackEnd, s.lookbackOrderIDs = start, end, []int64{waiting.ID}
|
||||
s.lookbackSlots(t.Context())
|
||||
|
||||
for want := start; want <= end; want++ {
|
||||
select {
|
||||
case got := <-s.slotQueue.Out:
|
||||
if got != want {
|
||||
t.Fatalf("queued slot = %d, want %d", got, want)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatalf("slot %d not queued", want)
|
||||
}
|
||||
}
|
||||
if s.lookbackNext != 0 {
|
||||
t.Fatalf("lookbackNext = %d after the range was queued, want 0", s.lookbackNext)
|
||||
}
|
||||
if _, done := lookbackDone.Load(waiting.ID); !done {
|
||||
t.Fatalf("order %d not marked as looked back", waiting.ID)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// 预期结果由独立的解码脚本从主网交易得出:只统计两端代币账户都在 token balances 中的 USDT/USDC transfer、transferChecked
|
||||
func TestSolanaParseTransactionMainnetFixtures(t *testing.T) {
|
||||
type want struct {
|
||||
from, to, amount string
|
||||
tradeType model.TradeType
|
||||
}
|
||||
tests := []struct {
|
||||
fixture string
|
||||
want []want
|
||||
}{
|
||||
{fixture: "success_legacy_transfer.json", want: []want{
|
||||
{from: "218mr4Lpgn5nFX4vBmgSDUSj4uvtTnx5jmwC5cZFHfSn", to: "Mdv6q9cauwiPLTn43SXuLtitAsDbNHtT3sFbknNvr6b", amount: "5.36", tradeType: model.UsdtSolana},
|
||||
}},
|
||||
{fixture: "success_legacy_transfer_checked.json", want: []want{
|
||||
{from: "8HrXbX3MdyEpgwiA1MkqR5max8gugvpX7ay4DFDd53aH", to: "8tjDqRuhYN1PZcZkwLy9sRTUb1hbJNyijJeAESxG5zxv", amount: "0.0024", tradeType: model.UsdcSolana},
|
||||
}},
|
||||
{fixture: "success_transfer_creates_token_account.json", want: []want{ // 同一笔交易里先创建收款方代币账户(非 ATA)
|
||||
{from: "Bj7j6d8sybC7rLTmGMCB4K4p6yC1v4RQvdAptDzTiURv", to: "8YKSSNbwE72ftktZS3V1NXvd8ekHzVfLk7GkBsvy8E2i", amount: "2560.021449", tradeType: model.UsdcSolana},
|
||||
}},
|
||||
{fixture: "success_v0_inner_transfer.json", want: []want{ // 地址查找表 + 内部指令
|
||||
{from: "GMCJvYGf5Ex2ARiMquaBDqU6iKM8uiEQkB8jCnoNfHpC", to: "F7p3dFrjRTbtRp8FRF6qHLomXbKRBzpvBLjtQcfcgmNe", amount: "390.990618", tradeType: model.UsdcSolana},
|
||||
}},
|
||||
{fixture: "success_v1_transfer.json", want: []want{
|
||||
{from: "2LAYGGSiF3QfyQEG1Gb3UGAsuzvD21zjHEW88v2XZ7cW", to: "FDRRDey8oQeRMgM5msEzy4yayKccuN2k47UdSnNNVVGQ", amount: "103.347262", tradeType: model.UsdcSolana},
|
||||
{from: "FDRRDey8oQeRMgM5msEzy4yayKccuN2k47UdSnNNVVGQ", to: "6EVgUURuvprazVdpd717E9uqruHcqRPbhRKDm5Czdidu", amount: "103.347262", tradeType: model.UsdcSolana},
|
||||
}},
|
||||
{fixture: "failed_v1_transfer.json"},
|
||||
{fixture: "failed_v0_inner_transfer.json"},
|
||||
}
|
||||
|
||||
s := &solana{}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.fixture, func(t *testing.T) {
|
||||
block := readSolanaFixture(t, tt.fixture)
|
||||
trans := gjson.GetBytes(block, "result.transactions.0")
|
||||
slot := solanaFixtureSlot(block)
|
||||
timestamp := time.Unix(gjson.GetBytes(block, "result.blockTime").Int(), 0)
|
||||
|
||||
got := s.parseTransaction(trans, slot, timestamp)
|
||||
if len(got) != len(tt.want) {
|
||||
t.Fatalf("transfers = %d, want %d: %+v", len(got), len(tt.want), got)
|
||||
}
|
||||
for i, w := range tt.want {
|
||||
g := got[i]
|
||||
if g.FromAddress != w.from || g.RecvAddress != w.to || g.Amount.String() != w.amount || g.TradeType != w.tradeType {
|
||||
t.Fatalf("transfer %d = %s -> %s %s %s, want %s -> %s %s %s", i, g.FromAddress, g.RecvAddress, g.Amount, g.TradeType, w.from, w.to, w.amount, w.tradeType)
|
||||
}
|
||||
if g.TxHash != trans.Get("transaction.signatures.0").String() || g.Network != conf.Solana || g.BlockNum != slot || !g.Timestamp.Equal(timestamp) {
|
||||
t.Fatalf("transfer %d metadata = %s %s %d %s", i, g.TxHash, g.Network, g.BlockNum, g.Timestamp)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
)
|
||||
|
||||
const solanaBlockCleanedUpResponse = `{"jsonrpc":"2.0","error":{"code":-32001,"message":"Block 459552217 cleaned up, does not exist on node. First available block: 461715420"},"id":1}`
|
||||
|
||||
func TestValidateSolanaBlockResponseCleanedUp(t *testing.T) {
|
||||
if _, err := validateSolanaBlockResponse([]byte(solanaBlockCleanedUpResponse)); !errors.Is(err, errSolanaBlockCleanedUp) {
|
||||
t.Fatalf("error = %v, want errSolanaBlockCleanedUp", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 并发处理同一个 slot 时,较晚返回的普通错误不能在 BlockCleanedUp 已经终止后重新建立重试
|
||||
func TestSolanaSlotParseCleanedUpWinsConcurrentFailure(t *testing.T) {
|
||||
firstStarted := make(chan struct{})
|
||||
releaseFirst := make(chan struct{})
|
||||
var calls atomic.Int64
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if calls.Add(1) == 1 {
|
||||
close(firstStarted)
|
||||
<-releaseFirst
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(solanaBlockCleanedUpResponse))
|
||||
}))
|
||||
defer srv.Close()
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
|
||||
|
||||
const slot = 459552217
|
||||
s := newSolana()
|
||||
t.Cleanup(s.stopSlotRetryTimers)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
s.slotParse(slot)
|
||||
close(done)
|
||||
}()
|
||||
<-firstStarted
|
||||
s.slotParse(slot)
|
||||
close(releaseFirst)
|
||||
<-done
|
||||
|
||||
if got := s.pendingSlotRetryCount(); got != 0 {
|
||||
t.Fatalf("pending retries after concurrent cleaned up = %d, want 0", got)
|
||||
}
|
||||
s.retryMu.Lock()
|
||||
_, scheduled := s.retryScheduled[slot]
|
||||
s.retryMu.Unlock()
|
||||
if scheduled {
|
||||
t.Fatalf("concurrent failure rescheduled cleaned up slot")
|
||||
}
|
||||
}
|
||||
|
||||
// 节点已清理的 slot 只请求一次就放弃,不留下待重试记录,向前扫描不会因此暂停;之前因为限流留下的重试也一并清除
|
||||
func TestSolanaSlotParseGivesUpCleanedUpSlot(t *testing.T) {
|
||||
var cleaned atomic.Bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !cleaned.Load() {
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(solanaBlockCleanedUpResponse))
|
||||
}))
|
||||
defer srv.Close()
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
|
||||
|
||||
const slot = 459552217
|
||||
s := newSolana()
|
||||
t.Cleanup(s.stopSlotRetryTimers)
|
||||
|
||||
s.slotParse(slot)
|
||||
if got := s.pendingSlotRetryCount(); got != 1 {
|
||||
t.Fatalf("pending retries after 429 = %d, want 1", got)
|
||||
}
|
||||
s.expireSlotRetryTimer(slot)
|
||||
|
||||
cleaned.Store(true)
|
||||
s.slotParse(slot)
|
||||
if got := s.pendingSlotRetryCount(); got != 0 {
|
||||
t.Fatalf("pending retries after cleaned up = %d, want 0: forward sync stays paused", got)
|
||||
}
|
||||
s.retryMu.Lock()
|
||||
_, scheduled := s.retryScheduled[slot]
|
||||
s.retryMu.Unlock()
|
||||
if scheduled {
|
||||
t.Fatalf("cleaned up slot still scheduled for retry")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"filippo.io/edwards25519"
|
||||
"git.viaeon.com/admin/vupay/app/conf"
|
||||
"git.viaeon.com/admin/vupay/app/log"
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"github.com/btcsuite/btcd/btcutil/base58"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// 订单过期后,按收款账户的链上历史对账一次。
|
||||
// 扫块每个 slot 只有一次机会,跳块、放弃重试的 slot、重启、回溯范围不完整都会让有效期内的付款漏掉;
|
||||
// 收款账户的签名列表是独立的链上历史,可以把这些付款找回来。
|
||||
|
||||
const (
|
||||
solanaReconcileDelay = time.Minute // 过期后等待交易 finalized 再对账
|
||||
solanaReconcileWindow = 2 * time.Hour // 只对最近过期的订单对账
|
||||
solanaSignaturePageLimit = 1000
|
||||
|
||||
solanaAssociatedTokenProgram = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
|
||||
)
|
||||
|
||||
// solanaReconciled 记录已完成对账的订单 ID;RPC 失败的订单不记录,下一轮重试
|
||||
var solanaReconciled sync.Map // key: int64 order ID, value: struct{}
|
||||
|
||||
func (s *solana) reconcileExpiredOrders(ctx context.Context) {
|
||||
now := time.Now()
|
||||
var orders []model.Order
|
||||
model.Db.Where("status = ? and trade_type in (?)", model.OrderStatusExpired, model.GetNetworkTrades(conf.Solana)).
|
||||
Where("expired_at > ? and expired_at < ?", now.Add(-solanaReconcileWindow), now.Add(-solanaReconcileDelay)).
|
||||
Find(&orders)
|
||||
|
||||
for _, o := range orders {
|
||||
if ctx.Err() != nil {
|
||||
|
||||
return
|
||||
}
|
||||
if _, done := solanaReconciled.Load(o.ID); done {
|
||||
|
||||
continue
|
||||
}
|
||||
if err := s.reconcileOrder(ctx, o); err != nil {
|
||||
log.Task.Warn(fmt.Sprintf("Solana 订单对账失败,稍后重试 %s:%v", o.TradeId, err))
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
solanaReconciled.Store(o.ID, struct{}{})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *solana) reconcileOrder(ctx context.Context, o model.Order) error {
|
||||
accounts, err := s.tokenAccounts(ctx, orderMatchAddress(o), model.GetTradeContract(o.TradeType))
|
||||
if err != nil {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
for _, account := range accounts {
|
||||
signatures, err := s.orderSignatures(ctx, account, o)
|
||||
if err != nil {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
for _, signature := range signatures {
|
||||
var used int64
|
||||
model.Db.Model(&model.Order{}).Where("ref_hash = ?", signature).Count(&used)
|
||||
if used > 0 {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
trans, err := s.rpcCall(ctx, "getTransaction", signature,
|
||||
map[string]any{"encoding": "json", "maxSupportedTransactionVersion": 1, "commitment": "finalized"})
|
||||
if err != nil {
|
||||
|
||||
return err
|
||||
}
|
||||
if trans.Type == gjson.Null {
|
||||
|
||||
return fmt.Errorf("getTransaction %s: transaction not found", signature)
|
||||
}
|
||||
|
||||
timestamp := time.Unix(trans.Get("blockTime").Int(), 0)
|
||||
for _, t := range s.parseTransaction(trans, int(trans.Get("slot").Int()), timestamp) {
|
||||
if !orderTransferMatch(o, t) {
|
||||
|
||||
continue
|
||||
}
|
||||
if err := o.MarkConfirming(t.BlockNum, t.FromAddress, t.TxHash, t.Timestamp, t.Amount); err != nil {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
log.Task.Info(fmt.Sprintf("Solana 对账找回付款 %s:%s", o.TradeId, t.TxHash))
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// tokenAccounts 返回钱包在该 mint 下的代币账户:总是包含关联代币账户(ATA),节点支持 getTokenAccountsByOwner 时再加上其他代币账户。
|
||||
// 部分节点(如 publicnode 免费节点)不提供 getTokenAccountsByOwner,此时只检查 ATA,绝大多数付款都转入 ATA。
|
||||
func (s *solana) tokenAccounts(ctx context.Context, owner, mint string) ([]string, error) {
|
||||
ata, err := solanaAssociatedTokenAccount(owner, mint)
|
||||
if err != nil {
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
accounts := []string{ata}
|
||||
result, err := s.rpcCall(ctx, "getTokenAccountsByOwner", owner, map[string]any{"mint": mint},
|
||||
map[string]any{"encoding": "base64", "dataSlice": map[string]int{"offset": 0, "length": 0}, "commitment": "finalized"})
|
||||
if err != nil {
|
||||
|
||||
return accounts, nil
|
||||
}
|
||||
for _, account := range result.Get("value.#.pubkey").Array() {
|
||||
if account.String() != ata {
|
||||
accounts = append(accounts, account.String())
|
||||
}
|
||||
}
|
||||
|
||||
return accounts, nil
|
||||
}
|
||||
|
||||
// solanaAssociatedTokenAccount 按 Associated Token Account 程序的规则推导地址:
|
||||
// seeds = [钱包, Token 程序, mint],从 bump 255 往下找第一个不在 ed25519 曲线上的哈希
|
||||
func solanaAssociatedTokenAccount(owner, mint string) (string, error) {
|
||||
seeds := [][]byte{base58.Decode(owner), base58.Decode(conf.SolSplToken), base58.Decode(mint)}
|
||||
for _, seed := range seeds {
|
||||
if len(seed) != 32 {
|
||||
|
||||
return "", fmt.Errorf("invalid Solana address: %s / %s", owner, mint)
|
||||
}
|
||||
}
|
||||
|
||||
program := base58.Decode(solanaAssociatedTokenProgram)
|
||||
for bump := 255; bump >= 0; bump-- {
|
||||
h := sha256.New()
|
||||
for _, seed := range seeds {
|
||||
h.Write(seed)
|
||||
}
|
||||
h.Write([]byte{byte(bump)})
|
||||
h.Write(program)
|
||||
h.Write([]byte("ProgramDerivedAddress"))
|
||||
|
||||
addr := h.Sum(nil)
|
||||
if _, err := new(edwards25519.Point).SetBytes(addr); err != nil {
|
||||
|
||||
return base58.Encode(addr), nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("no associated token account for %s / %s", owner, mint)
|
||||
}
|
||||
|
||||
// orderSignatures 返回代币账户在订单有效期内执行成功的交易签名;签名按时间倒序分页返回
|
||||
func (s *solana) orderSignatures(ctx context.Context, account string, o model.Order) ([]string, error) {
|
||||
var result []string
|
||||
opts := map[string]any{"limit": solanaSignaturePageLimit, "commitment": "finalized"}
|
||||
for {
|
||||
page, err := s.rpcCall(ctx, "getSignaturesForAddress", account, opts)
|
||||
if err != nil {
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
items := page.Array()
|
||||
for _, itm := range items {
|
||||
if !itm.Get("blockTime").Exists() || itm.Get("blockTime").Type == gjson.Null {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
at := time.Unix(itm.Get("blockTime").Int(), 0)
|
||||
if !o.CreatedAt.Before(at) { // 已早于订单创建时间
|
||||
|
||||
return result, nil
|
||||
}
|
||||
if o.ExpiredAt.After(at) && solanaTxSucceeded(itm.Get("err")) {
|
||||
result = append(result, itm.Get("signature").String())
|
||||
}
|
||||
}
|
||||
if len(items) < solanaSignaturePageLimit {
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
opts["before"] = items[len(items)-1].Get("signature").String()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *solana) rpcCall(ctx context.Context, method string, params ...any) (gjson.Result, error) {
|
||||
post, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": method, "params": params})
|
||||
if err != nil {
|
||||
|
||||
return gjson.Result{}, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", model.Endpoint(conf.Solana), bytes.NewBuffer(post))
|
||||
if err != nil {
|
||||
|
||||
return gjson.Result{}, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
|
||||
return gjson.Result{}, err
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
|
||||
return gjson.Result{}, fmt.Errorf("%s response status code %d", method, resp.StatusCode)
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
|
||||
return gjson.Result{}, err
|
||||
}
|
||||
if !gjson.ValidBytes(body) {
|
||||
|
||||
return gjson.Result{}, fmt.Errorf("%s invalid JSON response", method)
|
||||
}
|
||||
|
||||
data := gjson.ParseBytes(body)
|
||||
if rpcErr := data.Get("error"); rpcErr.Exists() {
|
||||
|
||||
return gjson.Result{}, fmt.Errorf("%s RPC error: %s", method, rpcErr.Raw)
|
||||
}
|
||||
if !data.Get("result").Exists() {
|
||||
|
||||
return gjson.Result{}, fmt.Errorf("%s missing result", method)
|
||||
}
|
||||
|
||||
return data.Get("result"), nil
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
const (
|
||||
reconcileTestOwner = "F7p3dFrjRTbtRp8FRF6qHLomXbKRBzpvBLjtQcfcgmNe"
|
||||
reconcileTestSignature = "DohbsAfxAerDTAX9XS1b9jXY5XYMXQsCnyY3qu42eEEcTeJ6UzMbFs3JTdY14QgNKQPdy6yezdgbqLbnRVj6YB6"
|
||||
reconcileTestSlot = 451914288
|
||||
)
|
||||
|
||||
type reconcileTestRPC struct {
|
||||
blockTime int64 // 交易时间,同时用于签名列表和 getTransaction
|
||||
signatureErr string // 签名列表里的 err 字段
|
||||
paidAccount string // 签名列表里有这笔付款的代币账户,默认是收款钱包的 ATA
|
||||
extraAccount string // getTokenAccountsByOwner 额外返回的代币账户;为空时该方法报错,模拟 publicnode 免费节点
|
||||
failSignatures atomic.Bool
|
||||
getTransaction atomic.Int64
|
||||
}
|
||||
|
||||
// 按 JSON-RPC 方法返回;getTransaction 使用主网交易 success_v0_inner_transfer.json,只改 blockTime
|
||||
func newReconcileTestServer(t *testing.T, rpc *reconcileTestRPC) *httptest.Server {
|
||||
t.Helper()
|
||||
|
||||
ata, err := solanaAssociatedTokenAccount(reconcileTestOwner, model.GetTradeContract(model.UsdcSolana))
|
||||
if err != nil {
|
||||
t.Fatalf("derive ATA: %v", err)
|
||||
}
|
||||
if rpc.paidAccount == "" {
|
||||
rpc.paidAccount = ata
|
||||
}
|
||||
|
||||
trans := gjson.GetBytes(readSolanaFixture(t, "success_v0_inner_transfer.json"), "result.transactions.0").Raw
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/notify" {
|
||||
_, _ = w.Write([]byte("ok"))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
switch gjson.GetBytes(body, "method").String() {
|
||||
case "getTokenAccountsByOwner":
|
||||
if rpc.extraAccount == "" {
|
||||
_, _ = w.Write([]byte(`{"jsonrpc":"2.0","error":{"code":-32602,"message":"Indexed requests require a personal token"},"id":1}`))
|
||||
|
||||
return
|
||||
}
|
||||
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":{"context":{"slot":%d},"value":[{"pubkey":"%s","account":{}},{"pubkey":"%s","account":{}}]},"id":1}`, reconcileTestSlot+1000, ata, rpc.extraAccount)
|
||||
case "getSignaturesForAddress":
|
||||
if rpc.failSignatures.Load() {
|
||||
_, _ = w.Write([]byte(`{"jsonrpc":"2.0","error":{"code":-32005,"message":"Node is behind"},"id":1}`))
|
||||
|
||||
return
|
||||
}
|
||||
if gjson.GetBytes(body, "params.0").String() != rpc.paidAccount {
|
||||
_, _ = w.Write([]byte(`{"jsonrpc":"2.0","result":[],"id":1}`))
|
||||
|
||||
return
|
||||
}
|
||||
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":[{"signature":"%s","slot":%d,"err":%s,"memo":null,"blockTime":%d,"confirmationStatus":"finalized"}],"id":1}`, reconcileTestSignature, reconcileTestSlot, rpc.signatureErr, rpc.blockTime)
|
||||
case "getSignatureStatuses":
|
||||
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":{"context":{"slot":%d},"value":[{"confirmationStatus":"finalized","confirmations":null,"err":null,"slot":%d,"status":{"Ok":null}}]},"id":1}`, reconcileTestSlot+1000, reconcileTestSlot)
|
||||
case "getTransaction":
|
||||
rpc.getTransaction.Add(1)
|
||||
_, _ = fmt.Fprintf(w, `{"jsonrpc":"2.0","result":{"slot":%d,"blockTime":%d,%s,"id":1}`, reconcileTestSlot, rpc.blockTime, trans[1:])
|
||||
default:
|
||||
t.Errorf("unexpected method: %s", body)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
return srv
|
||||
}
|
||||
|
||||
func createReconcileTestOrder(t *testing.T, tradeID, amount string) model.Order {
|
||||
t.Helper()
|
||||
|
||||
return createTestOrder(t, model.Order{
|
||||
NotifyUrl: model.GetC(model.RpcEndpointSolana) + "/notify",
|
||||
OrderId: "merchant-" + tradeID,
|
||||
TradeId: tradeID,
|
||||
TradeType: model.UsdcSolana,
|
||||
Rate: "7.00",
|
||||
Amount: amount,
|
||||
Money: "2736.93",
|
||||
Address: reconcileTestOwner,
|
||||
Status: model.OrderStatusExpired,
|
||||
ApiType: model.OrderApiTypeVupay,
|
||||
ExpiredAt: time.Now().Add(-5 * time.Minute),
|
||||
}, time.Now().Add(-15*time.Minute))
|
||||
}
|
||||
|
||||
func initReconcileTest(t *testing.T, rpc *reconcileTestRPC) *solana {
|
||||
t.Helper()
|
||||
|
||||
srv := newReconcileTestServer(t, rpc)
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
|
||||
solanaReconciled.Clear()
|
||||
s := newSolana()
|
||||
|
||||
return &s
|
||||
}
|
||||
|
||||
func TestSolanaReconcileFindsMissedPayment(t *testing.T) {
|
||||
rpc := &reconcileTestRPC{blockTime: time.Now().Add(-10 * time.Minute).Unix(), signatureErr: "null"}
|
||||
s := initReconcileTest(t, rpc)
|
||||
order := createReconcileTestOrder(t, "trade-order-1", "390.990618")
|
||||
|
||||
s.reconcileExpiredOrders(t.Context())
|
||||
|
||||
got := getTestOrder(t, order.TradeId)
|
||||
if got.Status != model.OrderStatusConfirming || got.RefHash != reconcileTestSignature || got.RefBlockNum != reconcileTestSlot ||
|
||||
got.FromAddress != "GMCJvYGf5Ex2ARiMquaBDqU6iKM8uiEQkB8jCnoNfHpC" {
|
||||
t.Fatalf("order = status %d ref %s slot %d from %s, want confirming with the payment", got.Status, got.RefHash, got.RefBlockNum, got.FromAddress)
|
||||
}
|
||||
if got.ConfirmedAt == nil || got.ConfirmedAt.Unix() != rpc.blockTime {
|
||||
t.Fatalf("confirmed_at = %v, want the transaction time", got.ConfirmedAt)
|
||||
}
|
||||
|
||||
// 之后按原流程确认并回调:订单虽已过期,但付款时间在有效期内
|
||||
s.tradeConfirmHandle(t.Context())
|
||||
if got := getTestOrder(t, order.TradeId); got.Status != model.OrderStatusSuccess {
|
||||
t.Fatalf("order status = %d after confirm, want success", got.Status)
|
||||
}
|
||||
waitOrderNotified(t, order.TradeId)
|
||||
}
|
||||
|
||||
func TestSolanaReconcileSkipsUnmatchedPayments(t *testing.T) {
|
||||
inWindow := time.Now().Add(-10 * time.Minute).Unix()
|
||||
tests := []struct {
|
||||
name string
|
||||
blockTime int64
|
||||
signatureErr string
|
||||
amount string
|
||||
usedByOtherOrder bool
|
||||
wantGetTransaction int64
|
||||
}{
|
||||
{name: "failed transaction", blockTime: inWindow, signatureErr: `{"InstructionError":[1,{"Custom":6001}]}`, amount: "390.990618"},
|
||||
{name: "paid before order created", blockTime: time.Now().Add(-30 * time.Minute).Unix(), signatureErr: "null", amount: "390.990618"},
|
||||
{name: "paid after expiry", blockTime: time.Now().Add(-2 * time.Minute).Unix(), signatureErr: "null", amount: "390.990618"},
|
||||
{name: "signature used by another order", blockTime: inWindow, signatureErr: "null", amount: "390.990618", usedByOtherOrder: true},
|
||||
{name: "amount mismatch", blockTime: inWindow, signatureErr: "null", amount: "1.23", wantGetTransaction: 1},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
rpc := &reconcileTestRPC{blockTime: tt.blockTime, signatureErr: tt.signatureErr}
|
||||
s := initReconcileTest(t, rpc)
|
||||
order := createReconcileTestOrder(t, "trade-order-1", tt.amount)
|
||||
if tt.usedByOtherOrder {
|
||||
other := createReconcileTestOrder(t, "trade-order-2", "100")
|
||||
other.Status = model.OrderStatusSuccess
|
||||
other.RefHash = reconcileTestSignature
|
||||
model.Db.Save(&other)
|
||||
}
|
||||
|
||||
s.reconcileExpiredOrders(t.Context())
|
||||
|
||||
if got := getTestOrder(t, order.TradeId); got.Status != model.OrderStatusExpired || got.RefHash != "" {
|
||||
t.Fatalf("order = status %d ref %s, want unchanged", got.Status, got.RefHash)
|
||||
}
|
||||
if got := rpc.getTransaction.Load(); got != tt.wantGetTransaction {
|
||||
t.Fatalf("getTransaction calls = %d, want %d", got, tt.wantGetTransaction)
|
||||
}
|
||||
if _, done := solanaReconciled.Load(order.ID); !done {
|
||||
t.Fatalf("order not marked as reconciled")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaReconcileRetriesOnRPCError(t *testing.T) {
|
||||
rpc := &reconcileTestRPC{blockTime: time.Now().Add(-10 * time.Minute).Unix(), signatureErr: "null"}
|
||||
s := initReconcileTest(t, rpc)
|
||||
order := createReconcileTestOrder(t, "trade-order-1", "390.990618")
|
||||
|
||||
rpc.failSignatures.Store(true)
|
||||
s.reconcileExpiredOrders(t.Context())
|
||||
if _, done := solanaReconciled.Load(order.ID); done {
|
||||
t.Fatalf("order marked as reconciled after RPC error")
|
||||
}
|
||||
|
||||
rpc.failSignatures.Store(false)
|
||||
s.reconcileExpiredOrders(t.Context())
|
||||
if got := getTestOrder(t, order.TradeId); got.Status != model.OrderStatusConfirming {
|
||||
t.Fatalf("order status = %d after retry, want confirming", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaReconcileOnlyRecentlyExpiredOrders(t *testing.T) {
|
||||
rpc := &reconcileTestRPC{blockTime: time.Now().Add(-10 * time.Minute).Unix(), signatureErr: "null"}
|
||||
s := initReconcileTest(t, rpc)
|
||||
order := createReconcileTestOrder(t, "trade-order-1", "390.990618")
|
||||
order.ExpiredAt = time.Now().Add(-30 * time.Second) // 还没到对账延迟,交易可能尚未 finalized
|
||||
model.Db.Save(&order)
|
||||
|
||||
s.reconcileExpiredOrders(t.Context())
|
||||
if got := getTestOrder(t, order.TradeId); got.Status != model.OrderStatusExpired {
|
||||
t.Fatalf("order status = %d, want expired until the reconcile delay passes", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaReconcileChecksOtherTokenAccounts(t *testing.T) {
|
||||
const other = "ReconcileTestTokenAccount111111111111111111"
|
||||
rpc := &reconcileTestRPC{blockTime: time.Now().Add(-10 * time.Minute).Unix(), signatureErr: "null", paidAccount: other, extraAccount: other}
|
||||
s := initReconcileTest(t, rpc)
|
||||
order := createReconcileTestOrder(t, "trade-order-1", "390.990618")
|
||||
|
||||
s.reconcileExpiredOrders(t.Context())
|
||||
if got := getTestOrder(t, order.TradeId); got.Status != model.OrderStatusConfirming || got.RefHash != reconcileTestSignature {
|
||||
t.Fatalf("order = status %d ref %s, want the payment to the non-ATA token account", got.Status, got.RefHash)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaAssociatedTokenAccount(t *testing.T) {
|
||||
tests := []struct {
|
||||
owner, mint, want string
|
||||
}{
|
||||
// 主网交易中的代币账户(success_legacy_transfer.json、success_legacy_transfer_checked.json)
|
||||
{owner: "Mdv6q9cauwiPLTn43SXuLtitAsDbNHtT3sFbknNvr6b", mint: "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", want: "Hwnrd47xhiULAjwLThEnuxnVTCwJyr5phkfwDyB58ns1"},
|
||||
{owner: "8tjDqRuhYN1PZcZkwLy9sRTUb1hbJNyijJeAESxG5zxv", mint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", want: "9un7p7bo7Y4TBwVdsQZTWtLZtkvW9hAUzdeV7mardWo5"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got, err := solanaAssociatedTokenAccount(tt.owner, tt.mint); err != nil || got != tt.want {
|
||||
t.Fatalf("ATA(%s, %s) = %s, %v; want %s", tt.owner, tt.mint, got, err, tt.want)
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := solanaAssociatedTokenAccount("not-an-address", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"); err == nil {
|
||||
t.Fatalf("invalid owner accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.viaeon.com/admin/vupay/app/model"
|
||||
)
|
||||
|
||||
// 模拟重试定时器到期并再次扫描失败:取消定时器,下一次 scheduleSlotRetry 计为新的失败
|
||||
func (s *solana) expireSlotRetryTimer(slot int) {
|
||||
s.retryMu.Lock()
|
||||
defer s.retryMu.Unlock()
|
||||
|
||||
if timer, ok := s.retryScheduled[slot]; ok {
|
||||
timer.Stop()
|
||||
delete(s.retryScheduled, slot)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *solana) stopSlotRetryTimers() {
|
||||
s.retryMu.Lock()
|
||||
defer s.retryMu.Unlock()
|
||||
|
||||
for slot, timer := range s.retryScheduled {
|
||||
timer.Stop()
|
||||
delete(s.retryScheduled, slot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaSlotRetryGivesUpAfterMaxRetries(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"jsonrpc":"2.0","error":{"code":-32004,"message":"Block not available for slot 457000000"},"id":1}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
initTaskTestEnv(t, map[model.ConfKey]string{model.RpcEndpointSolana: srv.URL})
|
||||
|
||||
const slot = 457000000
|
||||
s := newSolana()
|
||||
t.Cleanup(s.stopSlotRetryTimers)
|
||||
for i := 1; i <= solanaSlotMaxRetries; i++ {
|
||||
s.slotParse(slot)
|
||||
if got := s.pendingSlotRetryCount(); got != 1 {
|
||||
t.Fatalf("after %d failures pending retries = %d, want 1", i, got)
|
||||
}
|
||||
s.expireSlotRetryTimer(slot)
|
||||
}
|
||||
|
||||
s.slotParse(slot)
|
||||
if got := s.pendingSlotRetryCount(); got != 0 {
|
||||
t.Fatalf("pending retries = %d after giving up, forward sync stays paused", got)
|
||||
}
|
||||
s.retryMu.Lock()
|
||||
_, scheduled := s.retryScheduled[slot]
|
||||
s.retryMu.Unlock()
|
||||
if scheduled {
|
||||
t.Fatalf("slot still scheduled after giving up")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func TestSolanaGetBlockPayloadSupportsVersionOne(t *testing.T) {
|
||||
payload := string(solanaGetBlockPayload(456519571))
|
||||
if !strings.Contains(payload, `"maxSupportedTransactionVersion":1`) {
|
||||
t.Fatalf("payload does not support Solana v1 transactions: %s", payload)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSolanaBlockResponse(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
wantErr bool
|
||||
wantSkipped bool
|
||||
}{
|
||||
{name: "valid empty block", body: `{"jsonrpc":"2.0","result":{"blockTime":1760380000,"transactions":[]},"id":1}`},
|
||||
{name: "null result", body: `{"jsonrpc":"2.0","result":null,"id":1}`, wantSkipped: true},
|
||||
{name: "slot skipped", body: `{"jsonrpc":"2.0","error":{"code":-32007,"message":"Slot 300000092 was skipped, or missing due to ledger jump to recent snapshot"},"id":1}`, wantSkipped: true},
|
||||
{name: "long-term storage slot skipped", body: `{"jsonrpc":"2.0","error":{"code":-32009,"message":"Slot 300000092 was skipped, or missing in long-term storage"},"id":1}`, wantSkipped: true},
|
||||
{name: "block not available", body: `{"jsonrpc":"2.0","error":{"code":-32004,"message":"Block not available for slot 456731994"},"id":1}`, wantErr: true},
|
||||
{name: "unsupported transaction version", body: `{"jsonrpc":"2.0","error":{"code":-32015,"message":"Transaction version (1) is not supported by the requesting client"},"id":1}`, wantErr: true},
|
||||
{name: "missing result", body: `{"jsonrpc":"2.0","id":1}`, wantErr: true},
|
||||
{name: "missing transactions", body: `{"jsonrpc":"2.0","result":{"blockTime":1760380000},"id":1}`, wantErr: true},
|
||||
{name: "invalid json", body: `<html>rate limited</html>`, wantErr: true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := validateSolanaBlockResponse([]byte(tt.body))
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("error = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
if err == nil && (result.Type == gjson.Null) != tt.wantSkipped {
|
||||
t.Fatalf("skipped = %v, want %v", result.Type == gjson.Null, tt.wantSkipped)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolanaRetryDelayIsBounded(t *testing.T) {
|
||||
tests := []struct {
|
||||
attempt int
|
||||
want time.Duration
|
||||
}{
|
||||
{attempt: 1, want: 2 * time.Second},
|
||||
{attempt: 2, want: 5 * time.Second},
|
||||
{attempt: 3, want: 15 * time.Second},
|
||||
{attempt: 4, want: 30 * time.Second},
|
||||
{attempt: 5, want: time.Minute},
|
||||
{attempt: 100, want: time.Minute},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := solanaRetryDelay(tt.attempt); got != tt.want {
|
||||
t.Fatalf("attempt %d delay = %s, want %s", tt.attempt, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidSolanaLookbackRange(t *testing.T) {
|
||||
tests := []struct {
|
||||
start int64
|
||||
end int64
|
||||
want bool
|
||||
}{
|
||||
{start: 458225400, end: 458225500, want: true},
|
||||
{start: 0, end: 0, want: false},
|
||||
{start: 0, end: 458225500, want: false},
|
||||
{start: 458225500, end: 458225400, want: false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := validSolanaLookbackRange(tt.start, tt.end); got != tt.want {
|
||||
t.Fatalf("validSolanaLookbackRange(%d, %d) = %v, want %v", tt.start, tt.end, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user