-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrenew.go
More file actions
271 lines (267 loc) · 7.54 KB
/
Copy pathrenew.go
File metadata and controls
271 lines (267 loc) · 7.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
// Copyright 2025 Blink Labs Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package txbuilder
import (
"bytes"
"context"
"encoding/hex"
"fmt"
"time"
"github.com/Salvionied/apollo"
"github.com/Salvionied/apollo/serialization"
serAddress "github.com/Salvionied/apollo/serialization/Address"
"github.com/Salvionied/apollo/serialization/PlutusData"
"github.com/Salvionied/apollo/serialization/Redeemer"
"github.com/SundaeSwap-finance/ogmigo/v6"
"github.com/blinklabs-io/gouroboros/cbor"
"github.com/blinklabs-io/vpn-indexer/internal/config"
"github.com/blinklabs-io/vpn-indexer/internal/database"
)
func BuildRenewTransferTx(
db *database.Database,
paymentAddress string,
ownerAddress string,
clientId string,
price int,
duration int,
) ([]byte, error) {
// Validate inputs
if paymentAddress == "" {
return nil, NewInputValidationError("empty payment address provided")
}
cfg := config.GetConfig()
cc, err := apolloBackend()
if err != nil {
return nil, err
}
// Lookup current client information
clientAssetName, err := hex.DecodeString(clientId)
if err != nil {
return nil, fmt.Errorf("decode client ID: %w", err)
}
client, err := db.ClientByAssetName(clientAssetName)
if err != nil {
return nil, fmt.Errorf("lookup client: %w", err)
}
// Decode payment address
paymentAddr, err := serAddress.DecodeAddress(paymentAddress)
if err != nil {
return nil, NewInputValidationError("failed to decode payment address")
}
// Determine owner credential
// Use existing owner for client by default
ownerCredential := client.Credential
if ownerAddress != "" && ownerAddress != paymentAddress {
ownerAddr, err := serAddress.DecodeAddress(ownerAddress)
if err != nil {
return nil, NewInputValidationError("failed to decode owner address")
}
ownerCredential = ownerAddr.PaymentPart
}
// Determine if the owner is changing
newOwnerCred := []byte{}
if !bytes.Equal(ownerCredential, client.Credential) {
newOwnerCred = ownerCredential
}
// Decode script address
scriptAddress, err := serAddress.DecodeAddress(cfg.Indexer.ScriptAddress)
if err != nil {
return nil, fmt.Errorf("script address: %w", err)
}
scriptHash := scriptAddress.PaymentPart
// Decode provider address
providerAddress, err := serAddress.DecodeAddress(
cfg.TxBuilder.ProviderAddress,
)
if err != nil {
return nil, fmt.Errorf("provider address: %w", err)
}
// Lookup reference data
refData, err := db.ReferenceData()
if err != nil {
return nil, fmt.Errorf("reference data: %w", err)
}
// Parse script ref
scriptRef, err := inputRefFromString(cfg.TxBuilder.ScriptRefInput)
if err != nil {
return nil, err
}
// Get available UTxOs from user's wallet
availableUtxos, err := cc.Utxos(paymentAddr)
if err != nil {
return nil, fmt.Errorf(
"lookup UTxOs for address: %s: %w",
paymentAddr.String(),
err,
)
}
// Choose input UTxOs from user's wallet
inputUtxos, err := chooseInputUtxos(availableUtxos, price+5_000_000)
if err != nil {
return nil, fmt.Errorf("choose input UTxOs: %w", err)
}
if len(inputUtxos) == 0 {
return nil, NewInputValidationError("no input UTxOs found")
}
// Lookup UTxO for client asset
clientUtxo, err := cc.GetUtxoFromRef(
hex.EncodeToString(client.TxHash),
int(client.TxOutputIndex), // nolint:gosec
)
if err != nil {
return nil, fmt.Errorf("lookup client UTxO: %w", err)
}
// Determine plan selection
// The default of -1 represents transfer without renewal
selectionId := -1
// Lookup plan by price/duration, if provided
if price > 0 && duration > 0 {
selectionId, err = determinePlanSelection(refData, price, duration)
if err != nil {
return nil, NewInputValidationError("could not determine plan selection from provided price/duration")
}
}
// Get last known slot
curSlot, err := cc.LastBlockSlot()
if err != nil {
return nil, fmt.Errorf("query latest block slot: %w", err)
}
// Determine new expiration
var newExpiry time.Time
if time.Now().After(client.Expiration) {
// Previous client has expired, so we calculate expiration from the last known slot
ogmios := OgmiosClient()
systemStart, err := ogmiosSystemStart(ogmios)
if err != nil {
return nil, fmt.Errorf("query system start: %w", err)
}
eraHistory, err := ogmios.EraSummaries(context.Background())
if err != nil {
return nil, fmt.Errorf("query era summaries: %w", err)
}
curSlotTime := systemStart.Add(
time.Duration(
ogmigo.SlotToElapsedMilliseconds(
eraHistory,
uint64(curSlot),
),
) * time.Millisecond,
)
newExpiry = curSlotTime.
Add(time.Duration(duration) * time.Millisecond)
} else {
// Existing client is not expired, so we add the new duration to the end
newExpiry = client.Expiration.
Add(time.Duration(duration) * time.Millisecond)
}
// Configure transaction builder
apollob := apollo.New(cc)
apollob, err = apollob.
SetWalletFromBech32(paymentAddress).
SetWalletAsChangeAddress()
if err != nil {
return nil, fmt.Errorf("build transaction: %w", err)
}
// Build client datum
clientDatum := PlutusData.PlutusData{
PlutusDataType: PlutusData.PlutusBytes,
TagNr: 0,
Value: cbor.NewConstructor(
1,
cbor.IndefLengthList{
ownerCredential,
[]byte(client.Region),
newExpiry.UnixMilli(),
},
),
}
// Build spend redeemer
redeemer := Redeemer.Redeemer{
Tag: Redeemer.SPEND,
// NOTE: these values are estimated
ExUnits: Redeemer.ExecutionUnits{
Mem: 400_000,
Steps: 110_000_000,
},
Data: PlutusData.PlutusData{
PlutusDataType: PlutusData.PlutusBytes,
TagNr: 0,
Value: cbor.NewConstructor(
2,
cbor.IndefLengthList{
newOwnerCred,
clientAssetName,
selectionId,
},
),
},
}
apollob = apollob.
// Load all available UTxOs from user's wallet
AddLoadedUTxOs(availableUtxos...).
// Explicitly set our chosen inputs
AddInput(inputUtxos...).
// Pad out the fee until we figure out why Apollo isn't calculating it correctly
SetFeePadding(200_000).
// Set transaction not valid before current slot
SetValidityStart(int64(curSlot)).
// Set TTL
SetTtl(int64(curSlot+transactionTtlSlots)).
// Send service payment to provider address
PayToAddress(
providerAddress, price,
).
// Send client asset to contract
PayToContract(
scriptAddress,
&clientDatum,
0,
true,
apollo.NewUnit(
hex.EncodeToString(scriptHash),
string(clientAssetName),
1,
),
).
// Reference data
AddReferenceInputV3(
hex.EncodeToString(refData.TxId),
int(refData.OutputIdx),
).
// Script ref
AddReferenceInputV3(
scriptRef.Id().String(),
int(scriptRef.Index()),
).
CollectFrom(
*clientUtxo,
redeemer,
)
// We only require the current owner to sign if we're changing ownership
if len(newOwnerCred) > 0 {
apollob = apollob.AddRequiredSigner(
serialization.PubKeyHash(client.Credential),
)
}
apollob, err = apollob.Complete()
if err != nil {
return nil, fmt.Errorf("build transaction: %w", err)
}
tx := apollob.GetTx()
cborData, err := cbor.Encode(tx)
if err != nil {
return nil, fmt.Errorf("generate transaction CBOR: %w", err)
}
return cborData, nil
}