UNPKG

@xcapit/shelter-sdk

Version:

SDK for Shelter smart contracts on Stellar

58 lines (57 loc) 2.25 kB
import { Client, contract, hash, xdr, } from "shelter-sdk"; export class DefaultPass { _recipient; _shelterId; _rpc; constructor(_recipient, _shelterId, _rpc) { this._recipient = _recipient; this._shelterId = _shelterId; this._rpc = _rpc; } async applyTo(tx) { await tx.signAuthEntries({ address: this._shelterId, authorizeEntry: (entry) => { const clone = xdr.SorobanAuthorizationEntry.fromXDR(entry.toXDR()); return this._signAuthEntry(clone); }, }); return tx; } async _signAuthEntry(entry) { const credentials = entry.credentials().address(); let expiration = credentials.signatureExpirationLedger(); if (!expiration) { const { sequence } = await this._rpc.server().getLatestLedger(); expiration = sequence + contract.DEFAULT_TIMEOUT / 5; } credentials.signatureExpirationLedger(expiration); const preimage = xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(new xdr.HashIdPreimageSorobanAuthorization({ networkId: hash(Buffer.from(await this._rpc.network())), nonce: credentials.nonce(), signatureExpirationLedger: credentials.signatureExpirationLedger(), invocation: entry.rootInvocation(), })); const payload = hash(preimage.toXDR()); const signature = this._recipient.sign(payload); const shelterSignature = { public_key: this._recipient.rawPublicKey(), signature, }; const shelter = new Client({ contractId: this._shelterId, networkPassphrase: await this._rpc.network(), rpcUrl: this._rpc.url(), }); const scValType = xdr.ScSpecTypeDef.scSpecTypeUdt(new xdr.ScSpecTypeUdt({ name: "Pass" })); const scVal = shelter.spec.nativeToScVal(shelterSignature, scValType); switch (credentials.signature().switch().name) { case "scvVoid": credentials.signature(scVal); break; default: throw new Error("Unsupported signature"); } return entry; } }