@albedo-link/intent
Version:
A lightweight browser wrapper for Albedo API that provides a promise-based interface for all supported intents.
2 lines • 19.3 kB
JavaScript
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.albedo=t():e.albedo=t()}(this,(()=>(()=>{"use strict";var e={d:(t,i)=>{for(var n in i)e.o(i,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:i[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};function i(){const e=new Uint32Array(4);if("undefined"!=typeof crypto&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(4294967295*Math.random());return Array.from(e).map((e=>e.toString(36))).join("")}e.d(t,{default:()=>_});const n={public_key:{title:"View public key",description:"Requests account public key. It's a simple way of authentication for Stellar-based applications. The response ensures that a user owns the corresponding secret key.",implicitFlow:!1,params:{token:{description:"Verification token generated by the application (should be unique or random).",type:"string",required:!1},callback:{description:"Optional URL callback where Albedo will POST a signed token and public key.",type:"string",required:!1},require_existing:{description:"Allow existing Albedo accounts only.",type:"boolean",required:!1}},returns:{pubkey:{description:"User-selected public key.",type:"string"},signed_message:{description:"HEX-encoded authentication message derived from the public key and verification token.",type:"string"},signature:{description:"HEX-encoded ED25519 signature of the authentication message that can be further used to verify user's keypair ownership.",type:"string"}}},sign_message:{title:"Sign text message",description:"Requests arbitrary message signing. Can be used to implement identity/ownership verification.",implicitFlow:!0,params:{message:{description:"Text message to sign.",type:"string",required:!0},pubkey:{description:"Specific public key requested by the application.",type:"string",required:!1},callback:{description:"Optional URL callback where Albedo will POST a signed message.",type:"string",required:!1}},returns:{pubkey:{description:"User-selected public key.",type:"string"},original_message:{description:"Text message to sign from request.",type:"string"},signed_message:{description:"HEX-encoded message derived from the public key and original message.",type:"string"},message_signature:{description:"HEX-encoded ED25519 signature of the signed message.",type:"string"}}},tx:{title:"Sign transaction",description:"Requests a signature for the transaction. Returns the signed transaction envelope that can be submitted to the network or used for multi-sig coordination.",implicitFlow:!0,params:{xdr:{description:"XDR-encoded transaction envelope to sign.",type:"string",required:!0},pubkey:{description:"Specific public key requested by the application.",type:"string",required:!1},network:{description:"Stellar network identifier.",type:"string",required:!1},callback:{description:"Optional URL callback where Albedo will POST the signed transaction XDR instead of submitting it to Horizon.",type:"string",required:!1},description:{description:"Optional human-friendly short transaction description provided by developers.",type:"string",required:!1},submit:{description:"If set, the signed transaction will be submitted to the Horizon server instead of returning it to the application.",type:"boolean",required:!1}},returns:{xdr:{description:"XDR-encoded transaction envelope from request.",type:"string"},tx_hash:{description:"HEX-encoded transaction hash.",type:"string"},signed_envelope_xdr:{description:"XDR-encoded transaction envelope with new signatures.",type:"string"},network:{description:"Stellar network identifier.",type:"string"},result:{description:"Optional response from Horizon if the transaction has been submitted automatically.",type:"object"}}},pay:{title:"Make payment",description:"Requests a payment from a user. Works with any Stellar asset, supports transaction memo.",implicitFlow:!0,params:{amount:{description:"Requested payment amount.",type:"string",required:!0},destination:{description:"Payment destination address.",type:"string",required:!0},asset_code:{description:"Asset code (skip for XLM).",type:"string",required:!1},asset_issuer:{description:"Asset issuer (skip for XLM).",type:"string",required:!1},memo:{description:"Transaction memo (required for exchanges and some anchors).",type:"string",required:!1},memo_type:{description:"Transaction memo type.",type:"string",required:!1},pubkey:{description:"Specific public key requested by the application.",type:"string",required:!1},network:{description:"Stellar network identifier or private network passphrase.",type:"string",required:!1},callback:{description:"Optional URL callback where Albedo will POST the signed transaction XDR instead of submitting it to Horizon. ",type:"string",required:!1},submit:{description:"If set, the signed transaction will be submitted to the Horizon server instead of returning it to the application.",type:"boolean",required:!1}},returns:{amount:{description:"Payment amount from request.",type:"string"},destination:{description:"Payment destination address from request.",type:"string"},asset_code:{description:"Asset code from request.",type:"string"},asset_issuer:{description:"Asset issuer from request.",type:"string"},memo:{description:"Transaction memo from request.",type:"string"},memo_type:{description:"Transaction memo type from request.",type:"string"},tx_hash:{description:"HEX-encoded transaction hash.",type:"string"},signed_envelope_xdr:{description:"XDR-encoded transaction envelope with new signatures.",type:"string"},pubkey:{description:"User-selected public key.",type:"string"},network:{description:"Stellar network identifier.",type:"string"},result:{description:"Optional response from Horizon if the transaction has been submitted automatically.",type:"object"}}},trust:{title:"Establish trustline",description:"Requests permission to create a trustline to a given Stellar asset. Gradually simplifies the process of creating trustlines for anchors, ICOs, and airdrops.",implicitFlow:!0,params:{asset_code:{description:"Trustline asset code.",type:"string",required:!0},asset_issuer:{description:"Trustline asset issuer address.",type:"string",required:!0},limit:{description:"Trust limit.",type:"string",required:!1},memo:{description:"Transaction memo (required for exchanges and some anchors).",type:"string",required:!1},memo_type:{description:"Transaction memo type.",type:"string",required:!1},pubkey:{description:"Specific public key requested by the application.",type:"string",required:!1},network:{description:"Stellar network identifier or private network passphrase.",type:"string",required:!1},callback:{description:"Optional URL callback where Albedo will POST the signed transaction XDR instead of submitting it to Horizon. ",type:"string",required:!1},submit:{description:"If set, the signed transaction will be submitted to the Horizon server instead of returning it to the application.",type:"boolean",required:!1}},returns:{asset_code:{description:"Trustline asset code from request.",type:"string"},asset_issuer:{description:"Trustline asset issuer address from request.",type:"string"},limit:{description:"Trust limit from request.",type:"string"},tx_hash:{description:"HEX-encoded transaction hash.",type:"string"},signed_envelope_xdr:{description:"XDR-encoded transaction envelope with new signatures.",type:"string"},pubkey:{description:"User-selected public key.",type:"string"},network:{description:"Stellar network identifier.",type:"string"},result:{description:"Optional response from Horizon if the transaction has been submitted automatically.",type:"object"}}},exchange:{title:"Swap tokens",description:"Requests permission to buy tokens on Stellar DEX at market price.",implicitFlow:!1,params:{amount:{description:"The amount of asset to buy.",type:"string",required:!0},max_price:{description:"Maximum price the user willing to pay.",type:"string",required:!0},sell_asset_code:{description:"Asset code of the asset to sell.",type:"string",required:!1},sell_asset_issuer:{description:"Issuer account of the asset to sell.",type:"string",required:!1},buy_asset_code:{description:"Asset code of the asset to buy.",type:"string",required:!1},buy_asset_issuer:{description:"Issuer account of the asset to buy.",type:"string",required:!1},memo:{description:"Transaction memo (required for exchanges and some anchors).",type:"string",required:!1},memo_type:{description:"Transaction memo type.",type:"string",required:!1},pubkey:{description:"Specific public key requested by the application.",type:"string",required:!1},network:{description:"Stellar network identifier or private network passphrase.",type:"string",required:!1},callback:{description:"Optional URL callback where Albedo will POST the signed transaction XDR instead of submitting it to Horizon.",type:"string",required:!1},submit:{description:"If set, the signed transaction will be submitted to the Horizon server instead of returning it to the application.",type:"boolean",required:!1}},returns:{amount:{description:"The amount of asset to buy from request.",type:"string"},max_price:{description:"Maximum price the user willing to pay from request.",type:"string"},sell_asset_code:{description:"Asset code of the asset to sell from request.",type:"string"},sell_asset_issuer:{description:"Issuer account of the asset to sell from request.",type:"string"},buy_asset_code:{description:"Asset code of the asset to buy from request.",type:"string"},buy_asset_issuer:{description:"Issuer account of the asset to buy from request.",type:"string"},tx_hash:{description:"HEX-encoded transaction hash.",type:"string"},signed_envelope_xdr:{description:"XDR-encoded transaction envelope with new signatures.",type:"string"},pubkey:{description:"User-selected public key.",type:"string"},network:{description:"Stellar network identifier.",type:"string"},result:{description:"Optional response from Horizon if the transaction has been submitted automatically.",type:"object"}}},implicit_flow:{title:"Implicit permissions",description:'Requests temporary access token for one or more intents that can be used to execute actions without explicit confirmation from the user. In order to be executed implicitly, an implicit flow permissions for a given intent should be granted and "pubkey" parameter set.',implicitFlow:!1,params:{intents:{description:"Requested implicit flow intents.",type:"string|string[]",required:!0},network:{description:"Stellar network identifier or private network passphrase.",type:"string",required:!1}},returns:{granted:{description:"Whether a user granted permissions or not.",type:"boolean"},intents:{description:"Requested implicit flow intents.",type:"string[]"},grants:{description:"Implicit flow intents that have been granted.",type:"string[]"},session:{description:"Unique implicit session id.",type:"string"},valid_until:{description:"Session expiration timestamp.",type:"number"},pubkey:{description:"User-selected public key.",type:"string"},network:{description:"Stellar network identifier.",type:"string"}}},manage_account:{title:"Open account settings",description:"Opens account settings window for a given account.",implicitFlow:!1,params:{pubkey:{description:"Specific public key requested by the application.",type:"string",required:!0},network:{description:"Stellar network identifier or private network passphrase.",type:"string",required:!1}},returns:{pubkey:{description:"Public key from intent request.",type:"string"}}},batch:{title:"Intents batch",description:"Requests execution of several tx intents bundled together. This intent is atomic – a user confirms or rejects all bundled requests at once, with the same account and the same Stellar network.",implicitFlow:!0,params:{intents:{description:"Requested tx intents that should be executed together.",type:"object[]",required:!0},pubkey:{description:"Specific public key requested by the application.",type:"string",required:!1},network:{description:"Stellar network identifier or private network passphrase.",type:"string",required:!1}},returns:{intents:{description:"Requested tx intents.",type:"object[]"},results:{description:"Array of results for each requested intent.",type:"object[]"},pubkey:{description:"User-selected public key.",type:"string"},network:{description:"Stellar network identifier.",type:"string"}}}},s={unhandledError:{message:"Unhandled error occurred. If this error persists, please contact Albedo support.",code:-1},externalError:{message:"External error occurred.",code:-2},invalidIntentRequest:{message:"Intent request is invalid.",code:-3},actionRejectedByUser:{message:"Action request was rejected by the user.",code:-4},horizonError:{message:"Transaction failed when submitted to Stellar network.",code:-5},callbackError:{message:"Callback redirect failed.",code:-6}};function r(e,t=!1){this.windowHandler=e,this.ephemeral=!!t,this.isLoaded=!1,this.pendingRequests={},this.preprocessRequestParams=null,this.onLoaded=new Promise(((e,t)=>this.onLoadedCallback=e)).then((()=>this)),this.messageHandler=this.messageHandler.bind(this),window.addEventListener("message",this.messageHandler,!1)}function o(e,t,i){i.error?t(i):e(i)}r.prototype={isLoaded:!1,protocolVersion:3,markLoaded(){const{onLoadedCallback:e}=this;e&&(this.onLoadedCallback=null,this.isLoaded=!0,e())},messageHandler({data:e}){if(e.albedo)return this.matchProtocolVersion(e.albedo.protocol),this.markLoaded();if(e.albedoIntentResult){const{__reqid:t,...i}=e.albedoIntentResult,n=this.pendingRequests[t];n&&(delete this.pendingRequests[t],n(i),this.ephemeral&&(window.removeEventListener("message",this.messageHandler,!1),this.windowHandler.close()))}},transportCloseHandler(){for(let e in this.pendingRequests)if(this.pendingRequests.hasOwnProperty(e)){const t=this.pendingRequests[e];delete this.pendingRequests[e],t(s.actionRejectedByUser)}},postMessage(e){const t=i();return new Promise(((i,n)=>{this.onLoaded.then((()=>{this.pendingRequests[t]=o.bind(this,i,n),e=Object.assign({__reqid:t,__albedo_intent_version:this.protocolVersion},e),this.preprocessRequestParams&&(e=this.preprocessRequestParams(e)),this.windowHandler.postMessage(e,"*")}))}))},matchProtocolVersion(e){const t=e-this.protocolVersion;if(0===t)return;const i=`@albedo-link/intent module protocol version (${this.protocolVersion}) is incompatible with current Albedo protocol version ${e}.`;if(t>0)console.warn(i+" Please update @albedo-link/intent module to avoid possible connection problems.");else if(t<0)throw this.windowHandler.close(),new Error(i)}};const a=r;let c=null;function d(e){if(!c){const t=document.createElement("iframe");t.style.border="none",Object.assign(t,{width:"0",height:"0",frameBorder:"0",referrerPolicy:"origin",src:`${e}`}),document.body.appendChild(t),c=new a(t.contentWindow)}return c.onLoaded}function p({session:e,pubkey:t,grants:i,valid_until:n}){this.key=e,this.pubkey=t,this.grants=i.slice(),this.validUntil=n,Object.freeze(this),Object.freeze(this.grants)}p.prototype={key:"",pubkey:"",grants:[],validUntil:0,get isExpired(){return this.validUntil-2e3<(new Date).getTime()},toJSON(){return{session:this.key,pubkey:this.pubkey,grants:this.grants.slice(),valid_until:this.validUntil}}};const l=p,u="albedo_session_";function m(){return window.sessionStorage}function g(e){let t;{const i=m().getItem(u+e);i&&(t=new l(JSON.parse(i)))}return t?t.isExpired?(h(e),null):t:null}function y(e,t){const i=g(t);return i&&i.grants.includes(e)?i:null}function h(e){m().removeItem(u+e)}function f(e){return Object.assign(new Error,s.invalidIntentRequest,{ext:e})}if("object"==typeof window&&"function"!=typeof window.fetch)throw new Error("Browser FetchAPI is not available. For legacy browsers support use polyfills such as whatwg-fetch.");function b(){}b.prototype={frontendUrl:"https://albedo.link",intentInterface:n,intentErrors:s,request(e,t){return function(e,t){try{const{intent:i}=e;if(!i)throw f('Parameter "intent" is required.');const s=n[i];if(!s)throw f(`Unknown intent: "${i}".`);const r=function(e,t){if("object"!=typeof t)throw f("Intent parameters expected.");const{intent:i,pubkey:n}=t,s={intent:i};if(n&&!/^G[0-9A-Z]{55}$/.test(n))throw f('Invalid "pubkey" parameter. Stellar account public key expected.');for(const n in e.params){const r=e.params[n],o=t[n];if(o)s[n]=o;else if(r.required)throw f(`Parameter "${n}" is required for intent "${i}".`)}return s}(s,e);return function(e,t){if(e.pubkey){const i=y(e.intent,e.pubkey);if(i)return e.session=i.key,d(t)}return setTimeout((()=>{"implicit_flow"===e.intent&&d(t)}),200),function(e){const t=`${e}/confirm`,i=void 0!==window.screenLeft?window.screenLeft:window.screenX,n=void 0!==window.screenTop?window.screenTop:window.screenY,s=(window.innerWidth?window.innerWidth:document.documentElement.clientWidth?document.documentElement.clientWidth:screen.width)/2-240+i,r=(window.innerHeight?window.innerHeight:document.documentElement.clientHeight?document.documentElement.clientHeight:screen.height)/2-300+n,o=window.open(t,"auth.albedo.link",`height=600,width=480,top=${r},left=${s},menubar=0,toolbar=0,location=0,status=0,personalbar=0,scrollbars=0,dependent=1`);return new a(o,!0).onLoaded}(t)}(r,t).then((e=>function(e,t){return t.postMessage(e).then((e=>("implicit_flow"===e.intent&&e.granted&&function(e){const t=new l(e);m().setItem(u+t.pubkey,JSON.stringify(t))}(e),e)))}(r,e)))}catch(e){const{code:t=-1,message:i,ext:n}=e,s={message:i,code:t};return n&&(s.ext=n),Promise.reject(s)}}(Object.assign(t||{},{intent:e}),this.frontendUrl)},implicitFlow(e){return this.request("implicit_flow",e)},publicKey(e){return(e=Object.assign({},e)).token||(e.token=i()),this.request("public_key",e)},tx(e){return this.request("tx",e)},batch(e){return this.request("batch",e)},pay(e){return this.request("pay",e)},trust(e){return this.request("trust",e)},exchange(e){return this.request("exchange",e)},signMessage(e){return e=Object.assign({},e,((t=e.message)instanceof Uint8Array&&(t=t.reduce(((e,t)=>e+t.toString(16).padStart(2,"0")),"")),{message:t,binary:!0})),this.request("sign_message",e);var t},manageAccount(e){return this.request("manage_account",e)},generateRandomToken:()=>i(),isImplicitSessionAllowed:(e,t)=>!!y(e,t),listImplicitSessions:()=>function(){const e=m();return Object.keys(e).filter((e=>0===e.indexOf(u))).map((e=>g(e.substr(15)))).filter((e=>!!e))}(),forgetImplicitSession(e){h(e)}};const w=new b;var k;w.default=w,k=w,"undefined"!=typeof document&&document.addEventListener&&document.addEventListener("click",(function(e){if("A"!==e.target.tagName||0!==(e.target.href||"").indexOf("web+stellar:"))return;e.preventDefault(),e.stopImmediatePropagation();const{pathname:t,search:i}=new URL(e.target.href);if(!["tx","pay"].includes(t))return void alert(`Invalid operation requested: ${t}. It's likely an external application error. Please contact support team of ${window.location.origin}.`);const n=function(e=null){null===e&&(e=window.location.search),"?"===e[0]&&(e=e.substr(1));const t={};for(let i of e.split("&")){const[e,n]=i.split("=").map((e=>decodeURIComponent(e)));t[e]=n}return t}(i);k.request(t,n)}),!1);const q=w;q.intentInterface=n,q.intentErrors=s;const _=q;return t.default})()));
//# sourceMappingURL=albedo.intent.js.map