@flowtyio/flow-contracts 0.1.0-beta.26 → 0.1.0-beta.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,360 @@
1
+ import "FungibleToken"
2
+
3
+ /// The contract that allows an account to receive payments in multiple fungible
4
+ /// tokens using a single `{FungibleToken.Receiver}` capability.
5
+ /// This capability should ideally be stored at the
6
+ /// `FungibleTokenSwitchboard.ReceiverPublicPath = /public/GenericFTReceiver`
7
+ /// but it can be stored anywhere.
8
+ ///
9
+ access(all) contract FungibleTokenSwitchboard {
10
+
11
+ // Storage and Public Paths
12
+ access(all) let StoragePath: StoragePath
13
+ access(all) let PublicPath: PublicPath
14
+ access(all) let ReceiverPublicPath: PublicPath
15
+
16
+ access(all) entitlement Owner
17
+
18
+ /// The event that is emitted when a new vault capability is added to a
19
+ /// switchboard resource.
20
+ ///
21
+ access(all) event VaultCapabilityAdded(type: Type, switchboardOwner: Address?,
22
+ capabilityOwner: Address?)
23
+
24
+ /// The event that is emitted when a vault capability is removed from a
25
+ /// switchboard resource.
26
+ ///
27
+ access(all) event VaultCapabilityRemoved(type: Type, switchboardOwner: Address?,
28
+ capabilityOwner: Address?)
29
+
30
+ /// The event that is emitted when a deposit can not be completed.
31
+ ///
32
+ access(all) event NotCompletedDeposit(type: Type, amount: UFix64,
33
+ switchboardOwner: Address?)
34
+
35
+ /// The interface that enforces the method to allow anyone to check on the
36
+ /// available capabilities of a switchboard resource and also exposes the
37
+ /// deposit methods to deposit funds on it.
38
+ ///
39
+ access(all) resource interface SwitchboardPublic {
40
+ access(all) view fun getVaultTypesWithAddress(): {Type: Address}
41
+ access(all) view fun getSupportedVaultTypes(): {Type: Bool}
42
+ access(all) view fun isSupportedVaultType(type: Type): Bool
43
+ access(all) fun deposit(from: @{FungibleToken.Vault})
44
+ access(all) fun safeDeposit(from: @{FungibleToken.Vault}): @{FungibleToken.Vault}?
45
+ access(all) view fun safeBorrowByType(type: Type): &{FungibleToken.Receiver}?
46
+ }
47
+
48
+ /// The resource that stores the multiple fungible token receiver
49
+ /// capabilities, allowing the owner to add and remove them and anyone to
50
+ /// deposit any fungible token among the available types.
51
+ ///
52
+ access(all) resource Switchboard: FungibleToken.Receiver, SwitchboardPublic {
53
+
54
+ /// Dictionary holding the fungible token receiver capabilities,
55
+ /// indexed by the fungible token vault type.
56
+ ///
57
+ access(contract) var receiverCapabilities: {Type: Capability<&{FungibleToken.Receiver}>}
58
+
59
+ /// Adds a new fungible token receiver capability to the switchboard
60
+ /// resource.
61
+ ///
62
+ /// @param capability: The capability to expose a certain fungible
63
+ /// token vault deposit function through `{FungibleToken.Receiver}` that
64
+ /// will be added to the switchboard.
65
+ ///
66
+ access(Owner) fun addNewVault(capability: Capability<&{FungibleToken.Receiver}>) {
67
+ // Borrow a reference to the vault pointed to by the capability we
68
+ // want to store inside the switchboard
69
+ let vaultRef = capability.borrow()
70
+ ?? panic ("Cannot borrow reference to vault from capability")
71
+ // Check if there is a previous capability for this token, if not
72
+ if (self.receiverCapabilities[vaultRef.getType()] == nil) {
73
+ // use the vault reference type as key for storing the
74
+ // capability and then
75
+ self.receiverCapabilities[vaultRef.getType()] = capability
76
+ // emit the event that indicates that a new capability has been
77
+ // added
78
+ emit VaultCapabilityAdded(type: vaultRef.getType(),
79
+ switchboardOwner: self.owner?.address,
80
+ capabilityOwner: capability.address)
81
+ } else {
82
+ // If there was already a capability for that token, panic
83
+ panic("There is already a vault in the Switchboard for this token")
84
+ }
85
+ }
86
+
87
+ /// Adds a number of new fungible token receiver capabilities by using
88
+ /// the paths where they are stored.
89
+ ///
90
+ /// @param paths: The paths where the public capabilities are stored.
91
+ /// @param address: The address of the owner of the capabilities.
92
+ ///
93
+ access(Owner) fun addNewVaultsByPath(paths: [PublicPath], address: Address) {
94
+ // Get the account where the public capabilities are stored
95
+ let owner = getAccount(address)
96
+ // For each path, get the saved capability and store it
97
+ // into the switchboard's receiver capabilities dictionary
98
+ for path in paths {
99
+ let capability = owner.capabilities.get<&{FungibleToken.Receiver}>(path)
100
+ // Borrow a reference to the vault pointed to by the capability
101
+ // we want to store inside the switchboard
102
+ // If the vault was borrowed successfully...
103
+ if let vaultRef = capability.borrow() {
104
+ // ...and if there is no previous capability added for that token
105
+ if (self.receiverCapabilities[vaultRef!.getType()] == nil) {
106
+ // Use the vault reference type as key for storing the
107
+ // capability
108
+ self.receiverCapabilities[vaultRef!.getType()] = capability
109
+ // and emit the event that indicates that a new
110
+ // capability has been added
111
+ emit VaultCapabilityAdded(type: vaultRef.getType(),
112
+ switchboardOwner: self.owner?.address,
113
+ capabilityOwner: address,
114
+ )
115
+ }
116
+ }
117
+ }
118
+ }
119
+
120
+ /// Adds a new fungible token receiver capability to the switchboard
121
+ /// resource specifying which `Type` of `@{FungibleToken.Vault}` can be
122
+ /// deposited to it. Use it to include in your switchboard "wrapper"
123
+ /// receivers such as a `@TokenForwarding.Forwarder`. It can also be
124
+ /// used to overwrite the type attached to a certain capability without
125
+ /// having to remove that capability first.
126
+ ///
127
+ /// @param capability: The capability to expose a certain fungible
128
+ /// token vault deposit function through `{FungibleToken.Receiver}` that
129
+ /// will be added to the switchboard.
130
+ ///
131
+ /// @param type: The type of fungible token that can be deposited to that
132
+ /// capability, rather than the `Type` from the reference borrowed from
133
+ /// said capability
134
+ ///
135
+ access(Owner) fun addNewVaultWrapper(capability: Capability<&{FungibleToken.Receiver}>,
136
+ type: Type) {
137
+ // Check if the capability is working
138
+ assert(capability.check(), message: "The passed capability is not valid")
139
+ // Use the type parameter as key for the capability
140
+ self.receiverCapabilities[type] = capability
141
+ // emit the event that indicates that a new capability has been
142
+ // added
143
+ emit VaultCapabilityAdded(
144
+ type: type,
145
+ switchboardOwner: self.owner?.address,
146
+ capabilityOwner: capability.address,
147
+ )
148
+ }
149
+
150
+ /// Adds zero or more new fungible token receiver capabilities to the
151
+ /// switchboard resource specifying which `Type`s of `@{FungibleToken.Vault}`s
152
+ /// can be deposited to it. Use it to include in your switchboard "wrapper"
153
+ /// receivers such as a `@TokenForwarding.Forwarder`. It can also be
154
+ /// used to overwrite the types attached to certain capabilities without
155
+ /// having to remove those capabilities first.
156
+ ///
157
+ /// @param paths: The paths where the public capabilities are stored.
158
+ /// @param types: The types of the fungible token to be deposited on each path.
159
+ /// @param address: The address of the owner of the capabilities.
160
+ ///
161
+ access(Owner) fun addNewVaultWrappersByPath(paths: [PublicPath], types: [Type],
162
+ address: Address) {
163
+ // Get the account where the public capabilities are stored
164
+ let owner = getAccount(address)
165
+ // For each path, get the saved capability and store it
166
+ // into the switchboard's receiver capabilities dictionary
167
+ for i, path in paths {
168
+ let capability = owner.capabilities.get<&{FungibleToken.Receiver}>(path)
169
+ // Borrow a reference to the vault pointed to by the capability
170
+ // we want to store inside the switchboard
171
+ // If the vault was borrowed successfully...
172
+ if let vaultRef = capability.borrow() {
173
+ // Use the vault reference type as key for storing the capability
174
+ self.receiverCapabilities[types[i]] = capability
175
+ // and emit the event that indicates that a new capability has been added
176
+ emit VaultCapabilityAdded(
177
+ type: types[i],
178
+ switchboardOwner: self.owner?.address,
179
+ capabilityOwner: address,
180
+ )
181
+ }
182
+ }
183
+ }
184
+
185
+ /// Removes a fungible token receiver capability from the switchboard
186
+ /// resource.
187
+ ///
188
+ /// @param capability: The capability to a fungible token vault to be
189
+ /// removed from the switchboard.
190
+ ///
191
+ access(Owner) fun removeVault(capability: Capability<&{FungibleToken.Receiver}>) {
192
+ // Borrow a reference to the vault pointed to by the capability we
193
+ // want to remove from the switchboard
194
+ let vaultRef = capability.borrow()
195
+ ?? panic ("Cannot borrow reference to vault from capability")
196
+ // Use the vault reference to find the capability to remove
197
+ self.receiverCapabilities.remove(key: vaultRef.getType())
198
+ // Emit the event that indicates that a new capability has been
199
+ // removed
200
+ emit VaultCapabilityRemoved(
201
+ type: vaultRef.getType(),
202
+ switchboardOwner: self.owner?.address,
203
+ capabilityOwner: capability.address,
204
+ )
205
+ }
206
+
207
+ /// Takes a fungible token vault and routes it to the proper fungible
208
+ /// token receiver capability for depositing it.
209
+ ///
210
+ /// @param from: The deposited fungible token vault resource.
211
+ ///
212
+ access(all) fun deposit(from: @{FungibleToken.Vault}) {
213
+ // Get the capability from the ones stored at the switchboard
214
+ let depositedVaultCapability = self.receiverCapabilities[from.getType()]
215
+ ?? panic ("The deposited vault is not available on this switchboard")
216
+
217
+ // Borrow the reference to the desired vault
218
+ let vaultRef = depositedVaultCapability.borrow()
219
+ ?? panic ("Can not borrow a reference to the the vault")
220
+
221
+ vaultRef.deposit(from: <-from)
222
+ }
223
+
224
+ /// Takes a fungible token vault and tries to route it to the proper
225
+ /// fungible token receiver capability for depositing the funds,
226
+ /// avoiding panicking if the vault is not available.
227
+ ///
228
+ /// @param vaultType: The type of the ft vault that wants to be
229
+ /// deposited.
230
+ ///
231
+ /// @return The deposited fungible token vault resource, without the
232
+ /// funds if the deposit was successful, or still containing the funds
233
+ /// if the reference to the needed vault was not found.
234
+ ///
235
+ access(all) fun safeDeposit(from: @{FungibleToken.Vault}): @{FungibleToken.Vault}? {
236
+ // Try to get the proper vault capability from the switchboard
237
+ // If the desired vault is present on the switchboard...
238
+ if let depositedVaultCapability = self.receiverCapabilities[from.getType()] {
239
+ // We try to borrow a reference to the vault from the capability
240
+ // If we can borrow a reference to the vault...
241
+ if let vaultRef = depositedVaultCapability.borrow() {
242
+ // We deposit the funds on said vault
243
+ vaultRef.deposit(from: <-from.withdraw(amount: from.balance))
244
+ }
245
+ }
246
+ // if deposit failed for some reason
247
+ if from.balance > 0.0 {
248
+ emit NotCompletedDeposit(
249
+ type: from.getType(),
250
+ amount: from.balance,
251
+ switchboardOwner: self.owner?.address,
252
+ )
253
+ return <-from
254
+ }
255
+ destroy from
256
+ return nil
257
+ }
258
+
259
+ /// Checks that the capability tied to a type is valid
260
+ ///
261
+ /// @param vaultType: The type of the ft vault whose capability needs to be checked
262
+ ///
263
+ /// @return a boolean marking the capability for a type as valid or not
264
+ access(all) view fun checkReceiverByType(type: Type): Bool {
265
+ if self.receiverCapabilities[type] == nil {
266
+ return false
267
+ }
268
+
269
+ return self.receiverCapabilities[type]!.check()
270
+ }
271
+
272
+ /// Gets the receiver assigned to a provided vault type.
273
+ /// This is necessary because without it, it is not possible to look under the hood and see if a capability
274
+ /// is of an expected type or not. This helps guard against infinitely chained TokenForwarding or other invalid
275
+ /// malicious kinds of updates that could prevent listings from being made that are valid on storefronts.
276
+ ///
277
+ /// @param vaultType: The type of the ft vault whose capability needs to be checked
278
+ ///
279
+ /// @return an optional receiver capability for consumers of the switchboard to check/validate on their own
280
+ access(all) view fun safeBorrowByType(type: Type): &{FungibleToken.Receiver}? {
281
+ if !self.checkReceiverByType(type: type) {
282
+ return nil
283
+ }
284
+
285
+ return self.receiverCapabilities[type]!.borrow()
286
+ }
287
+
288
+ /// A getter function to know which tokens a certain switchboard
289
+ /// resource is prepared to receive along with the address where
290
+ /// those tokens will be deposited.
291
+ ///
292
+ /// @return A dictionary mapping the `{FungibleToken.Receiver}`
293
+ /// type to the receiver owner's address
294
+ ///
295
+ access(all) view fun getVaultTypesWithAddress(): {Type: Address} {
296
+ let effectiveTypesWithAddress: {Type: Address} = {}
297
+ // Check if each capability is live
298
+ for vaultType in self.receiverCapabilities.keys {
299
+ if self.receiverCapabilities[vaultType]!.check() {
300
+ // and attach it to the owner's address
301
+ effectiveTypesWithAddress[vaultType] = self.receiverCapabilities[vaultType]!.address
302
+ }
303
+ }
304
+ return effectiveTypesWithAddress
305
+ }
306
+
307
+ /// A getter function that returns the token types supported by this resource,
308
+ /// which can be deposited using the 'deposit' function.
309
+ ///
310
+ /// @return Dictionary of FT types that can be deposited.
311
+ access(all) view fun getSupportedVaultTypes(): {Type: Bool} {
312
+ let supportedVaults: {Type: Bool} = {}
313
+ for receiverType in self.receiverCapabilities.keys {
314
+ if self.receiverCapabilities[receiverType]!.check() {
315
+ if receiverType.isSubtype(of: Type<@{FungibleToken.Vault}>()) {
316
+ supportedVaults[receiverType] = true
317
+ }
318
+ if receiverType.isSubtype(of: Type<@{FungibleToken.Receiver}>()) {
319
+ let receiverRef = self.receiverCapabilities[receiverType]!.borrow()!
320
+ let subReceiverSupportedTypes = receiverRef.getSupportedVaultTypes()
321
+ for subReceiverType in subReceiverSupportedTypes.keys {
322
+ if subReceiverType.isSubtype(of: Type<@{FungibleToken.Vault}>()) {
323
+ supportedVaults[subReceiverType] = true
324
+ }
325
+ }
326
+ }
327
+ }
328
+ }
329
+ return supportedVaults
330
+ }
331
+
332
+ /// Returns whether or not the given type is accepted by the Receiver
333
+ /// A vault that can accept any type should just return true by default
334
+ access(all) view fun isSupportedVaultType(type: Type): Bool {
335
+ let supportedVaults = self.getSupportedVaultTypes()
336
+ if let supported = supportedVaults[type] {
337
+ return supported
338
+ } else { return false }
339
+ }
340
+
341
+ init() {
342
+ // Initialize the capabilities dictionary
343
+ self.receiverCapabilities = {}
344
+ }
345
+
346
+ }
347
+
348
+ /// Function that allows to create a new blank switchboard. A user must call
349
+ /// this function and store the returned resource in their storage.
350
+ ///
351
+ access(all) fun createSwitchboard(): @Switchboard {
352
+ return <-create Switchboard()
353
+ }
354
+
355
+ init() {
356
+ self.StoragePath = /storage/fungibleTokenSwitchboard
357
+ self.PublicPath = /public/fungibleTokenSwitchboardPublic
358
+ self.ReceiverPublicPath = /public/GenericFTReceiver
359
+ }
360
+ }
@@ -0,0 +1,90 @@
1
+ /*
2
+ FungibleTokenRouter forwards tokens from one account to another using
3
+ FungibleToken metadata views. If a token is not configured to be received,
4
+ any deposits will panic like they would a deposit that it attempt to a
5
+ non-existent receiver
6
+
7
+ https://github.com/Flowtyio/fungible-token-router
8
+ */
9
+
10
+ import "FungibleToken"
11
+ import "FungibleTokenMetadataViews"
12
+
13
+ access(all) contract FungibleTokenRouter {
14
+ access(all) let StoragePath: StoragePath
15
+ access(all) let PublicPath: PublicPath
16
+
17
+ access(all) entitlement Owner
18
+
19
+ access(all) event RouterCreated(uuid: UInt64, defaultAddress: Address)
20
+ access(all) event OverrideAdded(uuid: UInt64, owner: Address?, overrideAddress: Address, tokenType: String)
21
+ access(all) event OverrideRemoved(uuid: UInt64, owner: Address?, overrideAddress: Address?, tokenType: String)
22
+ access(all) event TokensRouted(tokenType: String, amount: UFix64, to: Address)
23
+
24
+ access(all) resource Router: FungibleToken.Receiver {
25
+ // a default address that is used for any token type that is not overridden
26
+ access(all) var defaultAddress: Address
27
+
28
+ // token type identifier -> destination address
29
+ access(all) var addressOverrides: {String: Address}
30
+
31
+ access(Owner) fun setDefaultAddress(_ addr: Address) {
32
+ self.defaultAddress = addr
33
+ }
34
+
35
+ access(Owner) fun addOverride(type: Type, addr: Address) {
36
+ emit OverrideAdded(uuid: self.uuid, owner: self.owner?.address, overrideAddress: addr, tokenType: type.identifier)
37
+ self.addressOverrides[type.identifier] = addr
38
+ }
39
+
40
+ access(Owner) fun removeOverride(type: Type): Address? {
41
+ let removedAddr = self.addressOverrides.remove(key: type.identifier)
42
+ emit OverrideRemoved(uuid: self.uuid, owner: self.owner?.address, overrideAddress: removedAddr, tokenType: type.identifier)
43
+ return removedAddr
44
+ }
45
+
46
+ access(all) fun deposit(from: @{FungibleToken.Vault}) {
47
+ let tokenType = from.getType().identifier
48
+ let destination = self.addressOverrides[tokenType] ?? self.defaultAddress
49
+
50
+ if let md = from.resolveView(Type<FungibleTokenMetadataViews.FTVaultData>()) {
51
+ let vaultData = md as! FungibleTokenMetadataViews.FTVaultData
52
+ let receiver = getAccount(destination).capabilities.get<&{FungibleToken.Receiver}>(vaultData.receiverPath)
53
+
54
+ assert(receiver.check(), message: "no receiver found at path: ".concat(vaultData.receiverPath.toString()))
55
+
56
+ emit TokensRouted(tokenType: tokenType, amount: from.balance, to: destination)
57
+ receiver.borrow()!.deposit(from: <-from)
58
+ }
59
+
60
+ panic("Could not find FungibleTokenMetadataViews.FTVaultData on depositing tokens")
61
+ }
62
+
63
+ access(all) view fun getSupportedVaultTypes(): {Type: Bool} {
64
+ // theoretically any token is supported, it depends on the defaultAddress
65
+ return {}
66
+ }
67
+
68
+ access(all) view fun isSupportedVaultType(type: Type): Bool {
69
+ // theoretically any token is supported, it depends on the defaultAddress
70
+ return true
71
+ }
72
+
73
+ init(defaultAddress: Address) {
74
+ self.defaultAddress = defaultAddress
75
+ self.addressOverrides = {}
76
+
77
+ emit RouterCreated(uuid: self.uuid, defaultAddress: defaultAddress)
78
+ }
79
+ }
80
+
81
+ access(all) fun createRouter(defaultAddress: Address): @Router {
82
+ return <- create Router(defaultAddress: defaultAddress)
83
+ }
84
+
85
+ init() {
86
+ let identifier = "FungibleTokenRouter_".concat(self.account.address.toString())
87
+ self.StoragePath = StoragePath(identifier: identifier)!
88
+ self.PublicPath = PublicPath(identifier: identifier)!
89
+ }
90
+ }
package/flow.json CHANGED
@@ -61,6 +61,14 @@
61
61
  "mainnet": "0xf233dcee88fe0abe"
62
62
  }
63
63
  },
64
+ "FungibleTokenSwitchboard": {
65
+ "source": "./contracts/FungibleTokenSwitchboard.cdc",
66
+ "aliases": {
67
+ "emulator": "0xee82856bf20e2aa6",
68
+ "testnet": "0x9a0766d93b6608b7",
69
+ "mainnet": "0xf233dcee88fe0abe"
70
+ }
71
+ },
64
72
  "ViewResolver": {
65
73
  "source": "./contracts/ViewResolver.cdc",
66
74
  "aliases": {
@@ -488,7 +496,17 @@
488
496
  "aliases": {
489
497
  "testing": "0x0000000000000007",
490
498
  "emulator": "0xf8d6e0586b0a20c7",
491
- "testnet": "0x83d75469f66d2ee6"
499
+ "testnet": "0x83d75469f66d2ee6",
500
+ "mainnet": "0xacc5081c003e24cf"
501
+ }
502
+ },
503
+ "FungibleTokenRouter": {
504
+ "source": "./contracts/fungible-token-router/FungibleTokenRouter.cdc",
505
+ "aliases": {
506
+ "testing": "0x0000000000000007",
507
+ "emulator": "0xf8d6e0586b0a20c7",
508
+ "testnet": "0x83231f90a288bc35",
509
+ "mainnet": "0x707c0b39a8d689cb"
492
510
  }
493
511
  }
494
512
  },
@@ -536,7 +554,8 @@
536
554
  ],
537
555
  "emulator-ft": [
538
556
  "FungibleToken",
539
- "FungibleTokenMetadataViews"
557
+ "FungibleTokenMetadataViews",
558
+ "FungibleTokenSwitchboard"
540
559
  ],
541
560
  "emulator-flowtoken": [
542
561
  "FlowToken"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flowtyio/flow-contracts",
3
- "version": "0.1.0-beta.26",
3
+ "version": "0.1.0-beta.28",
4
4
  "main": "index.json",
5
5
  "description": "An NPM package for common flow contracts",
6
6
  "author": "flowtyio",