Skip to content

Commit e2c5f90

Browse files
committed
update map name/methods and clients
1 parent 10960d0 commit e2c5f90

File tree

10 files changed

+160
-94
lines changed

10 files changed

+160
-94
lines changed

clients/tfchain-client-go/events.go

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,13 @@ type TwinEntityRemoved struct {
100100
Topics []types.Hash
101101
}
102102

103+
type MyceliumTwinUpdated struct {
104+
Phase types.Phase
105+
MyceliumPk []byte `json:"mycelium_pk"`
106+
TwinId types.U32 `json:"twin_id"`
107+
Topics []types.Hash
108+
}
109+
103110
type TwinAccountBounded struct {
104111
Phase types.Phase
105112
Twin types.U32 `json:"twin_id"`
@@ -414,12 +421,13 @@ type EventRecords struct {
414421
TfgridModule_EntityDeleted []EntityDeleted //nolint:stylecheck,golint
415422

416423
// twin events
417-
TfgridModule_TwinStored []TwinStored //nolint:stylecheck,golint
418-
TfgridModule_TwinUpdated []TwinStored //nolint:stylecheck,golint
419-
TfgridModule_TwinDeleted []TwinDeleted //nolint:stylecheck,golint
420-
TfgridModule_TwinEntityStored []TwinEntityStored //nolint:stylecheck,golint
421-
TfgridModule_TwinEntityRemoved []TwinEntityRemoved //nolint:stylecheck,golint
422-
TfgridModule_TwinAccountBounded []TwinAccountBounded //nolint:stylecheck,golint
424+
TfgridModule_TwinStored []TwinStored //nolint:stylecheck,golint
425+
TfgridModule_TwinUpdated []TwinStored //nolint:stylecheck,golint
426+
TfgridModule_TwinDeleted []TwinDeleted //nolint:stylecheck,golint
427+
TfgridModule_TwinEntityStored []TwinEntityStored //nolint:stylecheck,golint
428+
TfgridModule_TwinEntityRemoved []TwinEntityRemoved //nolint:stylecheck,golint
429+
TfgridModule_TwinAccountBounded []TwinAccountBounded //nolint:stylecheck,golint
430+
TfgridModule_MyceliumTwinUpdated []MyceliumTwinUpdated //nolint:stylecheck,golint
423431

424432
// policy events
425433
TfgridModule_PricingPolicyStored []PricingPolicyStored //nolint:stylecheck,golint

clients/tfchain-client-go/twin.go

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -183,52 +183,68 @@ func (s *Substrate) UpdateTwin(identity Identity, relay string, pk []byte) (uint
183183
return s.GetTwinByPubKey(identity.PublicKey())
184184
}
185185

186-
// SetTwinMyceliumPK sets the mycelium PK for a twin
187-
func (s *Substrate) SetTwinMyceliumPK(identity Identity, twinID uint32, myceliumPK []byte) error {
186+
// SetMyceliumTwin sets the mycelium public key mapping for a twin
187+
//
188+
// Parameters:
189+
// - identity: The identity for signing the transaction
190+
// - myceliumPK: The mycelium public key (hex string), ip will work as well
191+
// - twinID: The twin ID to map to the mycelium public key
192+
//
193+
// Returns:
194+
// - error: nil on success, error on failure
195+
func (s *Substrate) SetMyceliumTwin(identity Identity, myceliumPK string, twinID uint32) error {
188196
cl, meta, err := s.GetClient()
189197
if err != nil {
190198
return err
191199
}
192200

193-
c, err := types.NewCall(meta, "TfgridModule.set_twin_mycelium_pk", twinID, myceliumPK)
201+
bytes := []byte(myceliumPK)
202+
c, err := types.NewCall(meta, "TfgridModule.set_mycelium_twin", bytes, twinID)
194203
if err != nil {
195204
return errors.Wrap(err, "failed to create call")
196205
}
197206

198207
if _, err := s.Call(cl, meta, identity, c); err != nil {
199-
return errors.Wrap(err, "failed to set twin mycelium pk")
208+
return errors.Wrap(err, "failed to set mycelium twin")
200209
}
201210

202211
return nil
203212
}
204213

205-
// GetTwinIdByMyceliumPK gets twin id by mycelium PK
206-
func (s *Substrate) GetTwinIdByMyceliumPK(myceliumPK []byte) (*Twin, error) {
214+
// GetMyceliumTwin gets the twin ID associated with a mycelium public key
215+
//
216+
// Parameters:
217+
// - myceliumPK: The mycelium public key (hex string)
218+
//
219+
// Returns:
220+
// - uint32: The twin ID associated with the mycelium public key
221+
// - error: nil on success, error on failure (including ErrNotFound if no twin is found)
222+
func (s *Substrate) GetMyceliumTwin(myceliumPK string) (uint32, error) {
207223
cl, meta, err := s.GetClient()
208224
if err != nil {
209-
return nil, err
225+
return 0, err
210226
}
211227

212228
// must use encode to convert byte slice to encoded format
213229
bytes, err := Encode(myceliumPK)
214230
if err != nil {
215-
return nil, errors.Wrap(err, "substrate: encoding error building query arguments")
231+
return 0, errors.Wrap(err, "substrate: encoding error building query arguments")
216232
}
217233

218-
key, err := types.CreateStorageKey(meta, "TfgridModule", "TwinByMyceliumPk", bytes, nil)
234+
key, err := types.CreateStorageKey(meta, "TfgridModule", "MyceliumTwin", bytes, nil)
219235
if err != nil {
220-
return nil, errors.Wrap(err, "failed to create substrate query key")
236+
return 0, errors.Wrap(err, "failed to create substrate query key")
221237
}
222238

223239
var twinID types.U32
224240
ok, err := cl.RPC.State.GetStorageLatest(key, &twinID)
225241
if err != nil {
226-
return nil, errors.Wrap(err, "failed to lookup twin by mycelium pk")
242+
return 0, errors.Wrap(err, "failed to lookup twin by mycelium pk")
227243
}
228244

229245
if !ok || twinID == 0 {
230-
return nil, errors.Wrap(ErrNotFound, "twin not found for mycelium pk")
246+
return 0, errors.Wrap(ErrNotFound, "twin not found for mycelium pk")
231247
}
232248

233-
return s.GetTwin(uint32(twinID))
249+
return uint32(twinID), nil
234250
}

clients/tfchain-client-js/lib/client.js

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ const {
1111
const {
1212
createTwin, getTwin, getTwinIdByAccountId, updateTwin,
1313
deleteTwin, addTwinEntity, deleteTwinEntity, listTwins,
14-
setTwinMyceliumPK, getTwinByMyceliumPK
14+
setMyceliumTwin, getMyceliumTwin
1515
} = require('./twin')
1616
const {
1717
createFarm, getFarm, deleteFarm,
@@ -162,12 +162,24 @@ class Client {
162162
return deleteTwinEntity(this, twinID, entityID, callback)
163163
}
164164

165-
async setTwinMyceliumPK(twinId, myceliumPk, callback) {
166-
return setTwinMyceliumPK(this, twinId, myceliumPk, callback)
167-
}
168-
169-
async getTwinByMyceliumPK(myceliumPk) {
170-
return getTwinByMyceliumPK(this, myceliumPk)
165+
/**
166+
* Sets the mycelium public key mapping for a twin
167+
* @param {string} myceliumPk - The mycelium public key (hex string)
168+
* @param {number} twinId - The twin ID to map to the mycelium public key
169+
* @param {Function} callback - Optional callback function
170+
* @returns {Promise} Transaction result
171+
*/
172+
async setMyceliumTwin(myceliumPk, twinId, callback) {
173+
return setMyceliumTwin(this, myceliumPk, twinId, callback)
174+
}
175+
176+
/**
177+
* Gets the twin ID associated with a mycelium public key
178+
* @param {string} myceliumPk - The mycelium public key (hex string)
179+
* @returns {Promise<number>} The twin ID associated with the mycelium public key
180+
*/
181+
async getMyceliumTwin(myceliumPk) {
182+
return getMyceliumTwin(this, myceliumPk)
171183
}
172184

173185
async createFarm(name, certificationType, publicIPs, callback) {

clients/tfchain-client-js/lib/twin.js

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -92,26 +92,38 @@ async function deleteTwin (self, id, callback) {
9292
.signAndSend(self.key, { nonce }, callback)
9393
}
9494

95-
// setTwinMyceliumPK sets the mycelium public key for a twin
96-
async function setTwinMyceliumPK (self, twinId, myceliumPk, callback) {
97-
const setMyceliumPk = self.api.tx.tfgridModule.setTwinMyceliumPk(twinId, myceliumPk)
95+
/**
96+
* Sets the mycelium public key mapping for a twin
97+
* @param {Object} self - The client instance
98+
* @param {string} myceliumPk - The mycelium public key (hex string)
99+
* @param {number} twinId - The twin ID to map to the mycelium public key
100+
* @param {Function} callback - Optional callback function
101+
* @returns {Promise} Transaction result
102+
*/
103+
async function setMyceliumTwin (self, myceliumPk, twinId, callback) {
104+
const setMyceliumTx = self.api.tx.tfgridModule.setMyceliumTwin(myceliumPk, twinId)
98105
const nonce = await self.api.rpc.system.accountNextIndex(self.address)
99106

100-
return setMyceliumPk.signAndSend(self.key, { nonce }, callback)
107+
return setMyceliumTx.signAndSend(self.key, { nonce }, callback)
101108
}
102109

103-
// getTwinByMyceliumPK gets a twin by mycelium public key
104-
async function getTwinByMyceliumPK (self, myceliumPk) {
105-
// First, get the twin ID from the mycelium PK mapping
106-
const twinIdResult = await self.api.query.tfgridModule.twinByMyceliumPk(myceliumPk)
110+
/**
111+
* Gets the twin ID associated with a mycelium public key
112+
* @param {Object} self - The client instance
113+
* @param {string} myceliumPk - The mycelium public key (hex string)
114+
* @returns {Promise<number>} The twin ID associated with the mycelium public key
115+
* @throws {Error} If no twin is found for the given mycelium public key
116+
*/
117+
async function getMyceliumTwin (self, myceliumPk) {
118+
// Get the twin ID from the mycelium PK mapping using the storage getter
119+
const twinIdResult = await self.api.query.tfgridModule.myceliumTwin(myceliumPk)
107120
const twinId = twinIdResult.toJSON()
108121

109122
if (!twinId || twinId === 0) {
110123
throw Error(`Couldn't find a twin for mycelium pk: ${myceliumPk}`)
111124
}
112125

113-
// Now get the full twin object using the twin ID
114-
return getTwin(self, twinId)
126+
return twinId
115127
}
116128

117129
module.exports = {
@@ -123,6 +135,6 @@ module.exports = {
123135
addTwinEntity,
124136
deleteTwinEntity,
125137
listTwins,
126-
setTwinMyceliumPK,
127-
getTwinByMyceliumPK
138+
setMyceliumTwin,
139+
getMyceliumTwin
128140
}

clients/tfchain-client-rs/src/client.rs

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -152,24 +152,36 @@ impl Client {
152152
current::get_twin_id_by_account(self, account).await
153153
}
154154

155-
// Sets mycelium public key for a twin and checks for success, blockhash is returned on success
156-
pub async fn set_twin_mycelium_pk(
155+
/// Sets the mycelium public key mapping for a twin
156+
///
157+
/// # Arguments
158+
/// * `kp` - The keypair for signing the transaction
159+
/// * `mycelium_pk` - The mycelium public key (as bytes)
160+
/// * `twin_id` - The twin ID to map to the mycelium public key
161+
///
162+
/// # Returns
163+
/// * `Result<Hash, Error>` - The block hash on success
164+
pub async fn set_mycelium_twin(
157165
&self,
158166
kp: &KeyPair,
159-
twin_id: u32,
160167
mycelium_pk: Vec<u8>,
168+
twin_id: u32,
161169
) -> Result<Hash, Error> {
162-
current::set_twin_mycelium_pk(self, kp, twin_id, mycelium_pk).await
170+
current::set_mycelium_twin(self, kp, mycelium_pk, twin_id).await
163171
}
164172

165-
// Gets a twin by mycelium public key and returns the full twin object
166-
pub async fn get_twin_by_mycelium_pk(
173+
/// Gets the twin ID associated with a mycelium public key
174+
///
175+
/// # Arguments
176+
/// * `mycelium_pk` - The mycelium public key (as bytes)
177+
///
178+
/// # Returns
179+
/// * `Result<Option<u32>, Error>` - The twin ID if found, None otherwise
180+
pub async fn get_mycelium_twin(
167181
&self,
168182
mycelium_pk: Vec<u8>,
169-
) -> Result<Option<Twin>, Error> {
170-
// We pass a dummy keypair since it's not used in the implementation
171-
let dummy_kp = KeyPair::Sr25519(sr25519::Pair::from_seed(&[0u8; 32]));
172-
current::get_twin_by_mycelium_pk(self, &dummy_kp, mycelium_pk).await
183+
) -> Result<Option<u32>, Error> {
184+
current::get_mycelium_twin(self, mycelium_pk).await
173185
}
174186

175187
pub async fn get_farm_by_id(&self, id: u32) -> Result<Option<Farm>, Error> {

clients/tfchain-client-rs/src/runtimes/current.rs

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -202,47 +202,42 @@ pub async fn get_balance(
202202
.await?)
203203
}
204204

205-
pub async fn set_twin_mycelium_pk(
205+
pub async fn set_mycelium_twin(
206206
cl: &Client,
207207
kp: &KeyPair,
208-
twin_id: u32,
209208
mycelium_pk: Vec<u8>,
209+
twin_id: u32,
210210
) -> Result<H256, Error> {
211-
let set_mycelium_pk_tx = current::tx().tfgrid_module().set_twin_mycelium_pk(
212-
twin_id,
211+
let set_mycelium_tx = current::tx().tfgrid_module().set_mycelium_twin(
213212
BoundedVec(mycelium_pk),
213+
twin_id,
214214
);
215215

216216
let signer = kp.signer();
217217

218-
let set_mycelium_pk = cl
218+
let set_mycelium = cl
219219
.api
220220
.tx()
221-
.sign_and_submit_then_watch_default(&set_mycelium_pk_tx, &signer)
221+
.sign_and_submit_then_watch_default(&set_mycelium_tx, &signer)
222222
.await?
223223
.wait_for_finalized_success()
224224
.await?;
225225

226-
Ok(set_mycelium_pk.block_hash())
226+
Ok(set_mycelium.block_hash())
227227
}
228228

229-
pub async fn get_twin_by_mycelium_pk(
229+
pub async fn get_mycelium_twin(
230230
cl: &Client,
231-
_kp: &KeyPair,
232231
mycelium_pk: Vec<u8>,
233-
) -> Result<Option<Twin>, Error> {
232+
) -> Result<Option<u32>, Error> {
234233
// Query the storage directly using the mycelium pk to get twin ID
235234
let twin_id = cl
236235
.api
237236
.storage()
238237
.at_latest()
239238
.await?
240-
.fetch(&current::storage().tfgrid_module().twin_by_mycelium_pk(BoundedVec(mycelium_pk)))
239+
.fetch(&current::storage().tfgrid_module().mycelium_twin(BoundedVec(mycelium_pk)))
241240
.await?;
242241

243-
if let Some(id) = twin_id {
244-
get_twin_by_id(cl, id).await
245-
} else {
246-
Ok(None)
247-
}
242+
Ok(twin_id)
248243
}

substrate-node/pallets/pallet-tfgrid/src/benchmarking.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -737,15 +737,15 @@ benchmarks! {
737737
assert_last_event::<T>(Event::NodeUptimeReported(node_id, now, uptime).into());
738738
}
739739

740-
// set_twin_mycelium_pk
741-
set_twin_mycelium_pk {
740+
// set_mycelium_twin
741+
set_mycelium_twin {
742742
let caller: T::AccountId = whitelisted_caller();
743743
_create_twin::<T>(caller.clone());
744-
let twin_id = 1;
745744
let mycelium_pk = get_mycelium_pk_input(b"some_mycelium_pk");
746-
}: _(RawOrigin::Signed(caller), twin_id, mycelium_pk.clone())
745+
let twin_id = 1;
746+
}: _(RawOrigin::Signed(caller), mycelium_pk.clone(), twin_id)
747747
verify {
748-
assert_eq!(TfgridModule::<T>::twin_by_mycelium_pk(&mycelium_pk), Some(twin_id));
748+
assert_eq!(TfgridModule::<T>::get_mycelium_twin(&mycelium_pk), Some(twin_id));
749749
}
750750

751751
// Calling the `impl_benchmark_test_suite` macro inside the `benchmarks`
@@ -1033,3 +1033,7 @@ pub(crate) fn get_pub_config_gw6_input(gw6_input: &[u8]) -> Gw6Input {
10331033
pub(crate) fn get_pub_config_domain_input(domain_input: &[u8]) -> DomainInput {
10341034
BoundedVec::try_from(domain_input.to_vec()).expect("Invalid domain input.")
10351035
}
1036+
1037+
pub(crate) fn get_mycelium_pk_input(mycelium_pk_input: &[u8]) -> MyceliumPkInput {
1038+
BoundedVec::try_from(mycelium_pk_input.to_vec()).expect("Invalid mycelium pk input.")
1039+
}

substrate-node/pallets/pallet-tfgrid/src/lib.rs

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -266,8 +266,8 @@ pub mod pallet {
266266
>;
267267

268268
#[pallet::storage]
269-
#[pallet::getter(fn twin_by_mycelium_pk)]
270-
pub type TwinByMyceliumPk<T: Config> = StorageMap<
269+
#[pallet::getter(fn get_mycelium_twin)]
270+
pub type MyceliumTwin<T: Config> = StorageMap<
271271
_,
272272
Blake2_128Concat,
273273
MyceliumPkInput, // key is mycelium pk
@@ -423,7 +423,7 @@ pub mod pallet {
423423
TwinEntityRemoved(u32, u32),
424424
TwinDeleted(u32),
425425
TwinAccountBounded(u32, T::AccountId),
426-
TwinMyceliumPkSet(u32, MyceliumPkInput),
426+
MyceliumTwinUpdated(MyceliumPkInput, u32),
427427

428428
PricingPolicyStored(types::PricingPolicy<T::AccountId>),
429429
// CertificationCodeStored(types::CertificationCodes),
@@ -1253,25 +1253,14 @@ pub mod pallet {
12531253
// #[pallet::weight(<T as Config>::WeightInfo::set_node_gpu_status())]
12541254

12551255
#[pallet::call_index(40)]
1256-
#[pallet::weight(<T as Config>::WeightInfo::set_twin_mycelium_pk())]
1257-
pub fn set_twin_mycelium_pk(
1256+
#[pallet::weight(<T as Config>::WeightInfo::set_mycelium_twin())]
1257+
pub fn set_mycelium_twin(
12581258
origin: OriginFor<T>,
1259-
twin_id: u32,
12601259
mycelium_pk: MyceliumPkInput,
1260+
twin_id: u32,
12611261
) -> DispatchResultWithPostInfo {
12621262
let account_id = ensure_signed(origin)?;
1263-
1264-
// Ensure the caller owns this twin
1265-
let twin = Twins::<T>::get(twin_id).ok_or(Error::<T>::TwinNotExists)?;
1266-
ensure!(twin.account_id == account_id, Error::<T>::UnauthorizedToUpdateTwin);
1267-
1268-
// Store the mapping
1269-
TwinByMyceliumPk::<T>::insert(&mycelium_pk, twin_id);
1270-
1271-
// Emit event that mycelium-twin mapping is updated
1272-
Self::deposit_event(Event::TwinMyceliumPkSet(twin_id, mycelium_pk));
1273-
1274-
Ok(().into())
1263+
Self::_set_mycelium_twin(account_id, mycelium_pk, twin_id)
12751264
}
12761265
}
12771266
}

0 commit comments

Comments
 (0)